diff --git a/.travis/script.sh b/.travis/script.sh index 20dbe57e0..928a6d3fc 100755 --- a/.travis/script.sh +++ b/.travis/script.sh @@ -43,7 +43,7 @@ python --version || die } [ $BUILD_TARGET != py-pretty-check ] || { - flake8 --config=script/pystyle.cfg tools/harness-thci/ || die + flake8 --config=script/pystyle.cfg tests tools || die } [ $BUILD_TARGET != scan-build ] || { diff --git a/tests/scripts/thread-cert/Cert_5_1_01_RouterAttach.py b/tests/scripts/thread-cert/Cert_5_1_01_RouterAttach.py index fd9ca3baf..9cd6eb499 100755 --- a/tests/scripts/thread-cert/Cert_5_1_01_RouterAttach.py +++ b/tests/scripts/thread-cert/Cert_5_1_01_RouterAttach.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,7 +39,6 @@ ROUTER = 2 class Cert_5_1_01_RouterAttach(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -60,9 +58,9 @@ class Cert_5_1_01_RouterAttach(unittest.TestCase): self.nodes[ROUTER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -112,7 +110,9 @@ class Cert_5_1_01_RouterAttach(unittest.TestCase): msg.assertMleMessageContainsTlv(mle.Version) # 4 - Router - msg = router_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) + msg = router_messages.next_mle_message( + mle.CommandType.CHILD_ID_REQUEST + ) msg.assertSentToNode(self.nodes[LEADER]) msg.assertMleMessageContainsTlv(mle.Response) msg.assertMleMessageContainsTlv(mle.LinkLayerFrameCounter) @@ -124,7 +124,9 @@ class Cert_5_1_01_RouterAttach(unittest.TestCase): msg.assertMleMessageDoesNotContainTlv(mle.AddressRegistration) # 5 - Leader - msg = leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) + msg = leader_messages.next_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ) msg.assertSentToNode(self.nodes[ROUTER]) msg.assertMleMessageContainsTlv(mle.SourceAddress) msg.assertMleMessageContainsTlv(mle.LeaderData) @@ -159,7 +161,9 @@ class Cert_5_1_01_RouterAttach(unittest.TestCase): self.assertIn(mle.TlvType.LINK_MARGIN, tlv_request.tlvs) # 9 - Leader - msg = leader_messages.next_mle_message(mle.CommandType.LINK_ACCEPT_AND_REQUEST) + msg = leader_messages.next_mle_message( + mle.CommandType.LINK_ACCEPT_AND_REQUEST + ) msg.assertMleMessageContainsTlv(mle.SourceAddress) msg.assertMleMessageContainsTlv(mle.LeaderData) msg.assertMleMessageContainsTlv(mle.Response) @@ -181,5 +185,6 @@ class Cert_5_1_01_RouterAttach(unittest.TestCase): for addr in self.nodes[LEADER].get_addrs(): self.assertTrue(self.nodes[ROUTER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_1_02_ChildAddressTimeout.py b/tests/scripts/thread-cert/Cert_5_1_02_ChildAddressTimeout.py index bc77d06e2..eeccbf260 100755 --- a/tests/scripts/thread-cert/Cert_5_1_02_ChildAddressTimeout.py +++ b/tests/scripts/thread-cert/Cert_5_1_02_ChildAddressTimeout.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -41,8 +40,8 @@ SED = 4 MTDS = [ED, SED] -class Cert_5_1_02_ChildAddressTimeout(unittest.TestCase): +class Cert_5_1_02_ChildAddressTimeout(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() @@ -76,9 +75,9 @@ class Cert_5_1_02_ChildAddressTimeout(unittest.TestCase): self.nodes[SED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): diff --git a/tests/scripts/thread-cert/Cert_5_1_03_RouterAddressReallocation.py b/tests/scripts/thread-cert/Cert_5_1_03_RouterAddressReallocation.py index 67045520c..c7dbd4957 100755 --- a/tests/scripts/thread-cert/Cert_5_1_03_RouterAddressReallocation.py +++ b/tests/scripts/thread-cert/Cert_5_1_03_RouterAddressReallocation.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -41,7 +40,6 @@ ROUTER2 = 3 class Cert_5_1_03_RouterAddressReallocation(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -70,9 +68,9 @@ class Cert_5_1_03_RouterAddressReallocation(unittest.TestCase): self.nodes[ROUTER2].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -125,7 +123,9 @@ class Cert_5_1_03_RouterAddressReallocation(unittest.TestCase): router2_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) # Leader or Router1 can be parent of Router2 - if leader_messages.contains_mle_message(mle.CommandType.CHILD_ID_RESPONSE): + if leader_messages.contains_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ): leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) msg = router2_messages.next_coap_message("0.02") @@ -133,8 +133,12 @@ class Cert_5_1_03_RouterAddressReallocation(unittest.TestCase): msg = leader_messages.next_coap_message("2.04") - elif router1_messages.contains_mle_message(mle.CommandType.CHILD_ID_RESPONSE): - router1_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) + elif router1_messages.contains_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ): + router1_messages.next_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ) msg = router2_messages.next_coap_message("0.02") msg.assertCoapMessageRequestUriPath("/a/as") @@ -149,7 +153,9 @@ class Cert_5_1_03_RouterAddressReallocation(unittest.TestCase): # 5 - Router1 # Router1 make two attempts to reconnect to its current Partition. for _ in range(4): - msg = router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) + msg = router1_messages.next_mle_message( + mle.CommandType.PARENT_REQUEST + ) msg.assertSentWithHopLimit(255) msg.assertSentToDestinationAddress("ff02::2") msg.assertMleMessageContainsTlv(mle.Mode) @@ -175,7 +181,9 @@ class Cert_5_1_03_RouterAddressReallocation(unittest.TestCase): self.assertEqual(0, scan_mask_tlv.end_device) # 7 - Router1 - msg = router1_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) + msg = router1_messages.next_mle_message( + mle.CommandType.CHILD_ID_REQUEST + ) msg.assertSentToNode(self.nodes[ROUTER2]) msg.assertMleMessageContainsTlv(mle.Response) msg.assertMleMessageContainsTlv(mle.LinkLayerFrameCounter) diff --git a/tests/scripts/thread-cert/Cert_5_1_04_RouterAddressReallocation.py b/tests/scripts/thread-cert/Cert_5_1_04_RouterAddressReallocation.py index 190e94125..4cdeaddd7 100755 --- a/tests/scripts/thread-cert/Cert_5_1_04_RouterAddressReallocation.py +++ b/tests/scripts/thread-cert/Cert_5_1_04_RouterAddressReallocation.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -41,7 +40,6 @@ ROUTER2 = 3 class Cert_5_1_04_RouterAddressReallocation(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -70,9 +68,9 @@ class Cert_5_1_04_RouterAddressReallocation(unittest.TestCase): self.nodes[ROUTER2].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -124,7 +122,9 @@ class Cert_5_1_04_RouterAddressReallocation(unittest.TestCase): router2_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) # Leader or Router1 can be parent of Router2 - if leader_messages.contains_mle_message(mle.CommandType.CHILD_ID_RESPONSE): + if leader_messages.contains_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ): leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) msg = router2_messages.next_coap_message("0.02") @@ -132,8 +132,12 @@ class Cert_5_1_04_RouterAddressReallocation(unittest.TestCase): msg = leader_messages.next_coap_message("2.04") - elif router1_messages.contains_mle_message(mle.CommandType.CHILD_ID_RESPONSE): - router1_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) + elif router1_messages.contains_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ): + router1_messages.next_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ) msg = router2_messages.next_coap_message("0.02") msg.assertCoapMessageRequestUriPath("/a/as") @@ -148,7 +152,9 @@ class Cert_5_1_04_RouterAddressReallocation(unittest.TestCase): # 5 - Router1 # Router1 make two attempts to reconnect to its current Partition. for _ in range(4): - msg = router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) + msg = router1_messages.next_mle_message( + mle.CommandType.PARENT_REQUEST + ) msg.assertSentWithHopLimit(255) msg.assertSentToDestinationAddress("ff02::2") msg.assertMleMessageContainsTlv(mle.Mode) @@ -178,7 +184,9 @@ class Cert_5_1_04_RouterAddressReallocation(unittest.TestCase): router2_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) # 9 - Router1 - msg = router1_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router1_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[ROUTER2]) msg.assertMleMessageContainsTlv(mle.SourceAddress) msg.assertMleMessageContainsTlv(mle.LeaderData) @@ -190,7 +198,9 @@ class Cert_5_1_04_RouterAddressReallocation(unittest.TestCase): msg.assertMleMessageContainsTlv(mle.Connectivity) msg.assertMleMessageContainsTlv(mle.Version) - msg = router1_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) + msg = router1_messages.next_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ) msg.assertSentToNode(self.nodes[ROUTER2]) msg.assertMleMessageContainsTlv(mle.SourceAddress) msg.assertMleMessageContainsTlv(mle.LeaderData) diff --git a/tests/scripts/thread-cert/Cert_5_1_05_RouterAddressTimeout.py b/tests/scripts/thread-cert/Cert_5_1_05_RouterAddressTimeout.py index cacbf28d0..e3aab6603 100755 --- a/tests/scripts/thread-cert/Cert_5_1_05_RouterAddressTimeout.py +++ b/tests/scripts/thread-cert/Cert_5_1_05_RouterAddressTimeout.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,7 +39,6 @@ ROUTER1 = 2 class Cert_5_1_05_RouterAddressTimeout(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -63,9 +61,9 @@ class Cert_5_1_05_RouterAddressTimeout(unittest.TestCase): self.nodes[ROUTER1].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): diff --git a/tests/scripts/thread-cert/Cert_5_1_06_RemoveRouterId.py b/tests/scripts/thread-cert/Cert_5_1_06_RemoveRouterId.py index 7646ec312..030fc4cdf 100755 --- a/tests/scripts/thread-cert/Cert_5_1_06_RemoveRouterId.py +++ b/tests/scripts/thread-cert/Cert_5_1_06_RemoveRouterId.py @@ -27,14 +27,12 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import command from command import CheckType import config import mle -import network_layer import node LEADER = 1 @@ -42,7 +40,6 @@ ROUTER1 = 2 class Cert_5_1_06_RemoveRouterId(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -62,9 +59,9 @@ class Cert_5_1_06_RemoveRouterId(unittest.TestCase): self.nodes[ROUTER1].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -107,10 +104,17 @@ class Cert_5_1_06_RemoveRouterId(unittest.TestCase): msg = router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) command.check_parent_request(msg, is_first_request=True) - msg = router1_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST, sent_to_node=self.nodes[LEADER]) - command.check_child_id_request(msg, tlv_request=CheckType.CONTAIN, - mle_frame_counter=CheckType.OPTIONAL, address_registration=CheckType.NOT_CONTAIN, - active_timestamp=CheckType.OPTIONAL, pending_timestamp=CheckType.OPTIONAL) + msg = router1_messages.next_mle_message( + mle.CommandType.CHILD_ID_REQUEST, sent_to_node=self.nodes[LEADER] + ) + command.check_child_id_request( + msg, + tlv_request=CheckType.CONTAIN, + mle_frame_counter=CheckType.OPTIONAL, + address_registration=CheckType.NOT_CONTAIN, + active_timestamp=CheckType.OPTIONAL, + pending_timestamp=CheckType.OPTIONAL, + ) msg = router1_messages.next_coap_message(code="0.02") command.check_address_solicit(msg, was_router=True) diff --git a/tests/scripts/thread-cert/Cert_5_1_07_MaxChildCount.py b/tests/scripts/thread-cert/Cert_5_1_07_MaxChildCount.py index 1cdc0d472..c625834fe 100755 --- a/tests/scripts/thread-cert/Cert_5_1_07_MaxChildCount.py +++ b/tests/scripts/thread-cert/Cert_5_1_07_MaxChildCount.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,6 +36,7 @@ LEADER = 1 ROUTER = 2 SED1 = 7 + class Cert_5_1_07_MaxChildCount(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() @@ -69,9 +69,9 @@ class Cert_5_1_07_MaxChildCount(unittest.TestCase): self.nodes[i].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -101,5 +101,6 @@ class Cert_5_1_07_MaxChildCount(unittest.TestCase): self.assertTrue(self.nodes[LEADER].ping(addr, size=106)) break + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_1_08_RouterAttachConnectivity.py b/tests/scripts/thread-cert/Cert_5_1_08_RouterAttachConnectivity.py index e2fc82b1c..908b7f70e 100755 --- a/tests/scripts/thread-cert/Cert_5_1_08_RouterAttachConnectivity.py +++ b/tests/scripts/thread-cert/Cert_5_1_08_RouterAttachConnectivity.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -42,7 +41,6 @@ ROUTER4 = 5 class Cert_5_1_08_RouterAttachConnectivity(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -87,9 +85,9 @@ class Cert_5_1_08_RouterAttachConnectivity(unittest.TestCase): self.nodes[ROUTER4].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -137,14 +135,20 @@ class Cert_5_1_08_RouterAttachConnectivity(unittest.TestCase): self.assertEqual(0, scan_mask_tlv.end_device) # 3 - Router2, Router3 - msg = router2_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router2_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[ROUTER4]) - msg = router3_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router3_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[ROUTER4]) # 4 - Router4 - msg = router4_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) + msg = router4_messages.next_mle_message( + mle.CommandType.CHILD_ID_REQUEST + ) msg.assertSentToNode(self.nodes[ROUTER3]) msg.assertMleMessageContainsTlv(mle.Response) msg.assertMleMessageContainsTlv(mle.LinkLayerFrameCounter) diff --git a/tests/scripts/thread-cert/Cert_5_1_09_REEDAttachConnectivity.py b/tests/scripts/thread-cert/Cert_5_1_09_REEDAttachConnectivity.py index d75bff772..7e0189331 100755 --- a/tests/scripts/thread-cert/Cert_5_1_09_REEDAttachConnectivity.py +++ b/tests/scripts/thread-cert/Cert_5_1_09_REEDAttachConnectivity.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -42,7 +41,6 @@ ROUTER2 = 5 class Cert_5_1_09_REEDAttachConnectivity(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -87,9 +85,9 @@ class Cert_5_1_09_REEDAttachConnectivity(unittest.TestCase): self.nodes[ROUTER2].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -156,10 +154,15 @@ class Cert_5_1_09_REEDAttachConnectivity(unittest.TestCase): msg = reed1_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) connectivity_tlv_reed1 = msg.get_mle_message_tlv(mle.Connectivity) - self.assertGreater(connectivity_tlv_reed1.link_quality_3, connectivity_tlv_reed0.link_quality_3) + self.assertGreater( + connectivity_tlv_reed1.link_quality_3, + connectivity_tlv_reed0.link_quality_3, + ) # 6 - Router2 - msg = router2_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) + msg = router2_messages.next_mle_message( + mle.CommandType.CHILD_ID_REQUEST + ) msg.assertSentToNode(self.nodes[REED1]) msg.assertMleMessageContainsTlv(mle.Response) msg.assertMleMessageContainsTlv(mle.LinkLayerFrameCounter) diff --git a/tests/scripts/thread-cert/Cert_5_1_10_RouterAttachLinkQuality.py b/tests/scripts/thread-cert/Cert_5_1_10_RouterAttachLinkQuality.py index ade58f6aa..743296f13 100755 --- a/tests/scripts/thread-cert/Cert_5_1_10_RouterAttachLinkQuality.py +++ b/tests/scripts/thread-cert/Cert_5_1_10_RouterAttachLinkQuality.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -41,7 +40,6 @@ ROUTER3 = 4 class Cert_5_1_10_RouterAttachLinkQuality(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -65,7 +63,9 @@ class Cert_5_1_10_RouterAttachLinkQuality(unittest.TestCase): self.nodes[ROUTER2].set_panid(0xface) self.nodes[ROUTER2].set_mode('rsdn') self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64()) - self.nodes[ROUTER2].add_whitelist(self.nodes[ROUTER3].get_addr64(), rssi=-85) + self.nodes[ROUTER2].add_whitelist( + self.nodes[ROUTER3].get_addr64(), rssi=-85 + ) self.nodes[ROUTER2].enable_whitelist() self.nodes[ROUTER2].set_router_selection_jitter(1) @@ -77,9 +77,9 @@ class Cert_5_1_10_RouterAttachLinkQuality(unittest.TestCase): self.nodes[ROUTER3].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -142,14 +142,20 @@ class Cert_5_1_10_RouterAttachLinkQuality(unittest.TestCase): msg.assertMleMessageContainsTlv(mle.Version) # 4 - Router1, Router2 - msg = router1_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router1_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[ROUTER3]) - msg = router2_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router2_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[ROUTER3]) # 5 - Router3 - msg = router3_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) + msg = router3_messages.next_mle_message( + mle.CommandType.CHILD_ID_REQUEST + ) msg.assertSentToNode(self.nodes[ROUTER1]) msg.assertMleMessageContainsTlv(mle.Response) msg.assertMleMessageContainsTlv(mle.LinkLayerFrameCounter) diff --git a/tests/scripts/thread-cert/Cert_5_1_11_REEDAttachLinkQuality.py b/tests/scripts/thread-cert/Cert_5_1_11_REEDAttachLinkQuality.py index 5774f22ba..e4dd91330 100755 --- a/tests/scripts/thread-cert/Cert_5_1_11_REEDAttachLinkQuality.py +++ b/tests/scripts/thread-cert/Cert_5_1_11_REEDAttachLinkQuality.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -41,7 +40,6 @@ ROUTER1 = 4 class Cert_5_1_11_REEDAttachLinkQuality(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -65,7 +63,9 @@ class Cert_5_1_11_REEDAttachLinkQuality(unittest.TestCase): self.nodes[ROUTER2].set_panid(0xface) self.nodes[ROUTER2].set_mode('rsdn') self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64()) - self.nodes[ROUTER2].add_whitelist(self.nodes[ROUTER1].get_addr64(), rssi=-85) + self.nodes[ROUTER2].add_whitelist( + self.nodes[ROUTER1].get_addr64(), rssi=-85 + ) self.nodes[ROUTER2].enable_whitelist() self.nodes[ROUTER2].set_router_selection_jitter(1) @@ -77,9 +77,9 @@ class Cert_5_1_11_REEDAttachLinkQuality(unittest.TestCase): self.nodes[ROUTER1].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -141,7 +141,9 @@ class Cert_5_1_11_REEDAttachLinkQuality(unittest.TestCase): self.assertEqual(0, scan_mask_tlv.end_device) # 4 - Router2 - msg = router2_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router2_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[ROUTER1]) # 5 - Router1 @@ -158,7 +160,9 @@ class Cert_5_1_11_REEDAttachLinkQuality(unittest.TestCase): self.assertEqual(1, scan_mask_tlv.end_device) # 6 - Router1 - msg = router1_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) + msg = router1_messages.next_mle_message( + mle.CommandType.CHILD_ID_REQUEST + ) msg.assertMleMessageContainsTlv(mle.LinkLayerFrameCounter) msg.assertMleMessageContainsTlv(mle.Mode) msg.assertMleMessageContainsTlv(mle.Response) @@ -172,5 +176,6 @@ class Cert_5_1_11_REEDAttachLinkQuality(unittest.TestCase): msg = reed_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) msg.assertSentToNode(self.nodes[ROUTER1]) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_1_12_NewRouterNeighborSync.py b/tests/scripts/thread-cert/Cert_5_1_12_NewRouterNeighborSync.py index 7344deea5..c7ea1c8dd 100755 --- a/tests/scripts/thread-cert/Cert_5_1_12_NewRouterNeighborSync.py +++ b/tests/scripts/thread-cert/Cert_5_1_12_NewRouterNeighborSync.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,7 +39,6 @@ ROUTER2 = 3 class Cert_5_1_12_NewRouterSync(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -67,17 +65,26 @@ class Cert_5_1_12_NewRouterSync(unittest.TestCase): self.nodes[ROUTER2].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() - def verify_step_4(self, router1_messages, router2_messages, req_receiver, accept_receiver): - if router2_messages.contains_mle_message(mle.CommandType.LINK_REQUEST) and \ - (router1_messages.contains_mle_message(mle.CommandType.LINK_ACCEPT) or - router1_messages.contains_mle_message(mle.CommandType.LINK_ACCEPT_AND_REQUEST)): + def verify_step_4( + self, router1_messages, router2_messages, req_receiver, accept_receiver + ): + if router2_messages.contains_mle_message( + mle.CommandType.LINK_REQUEST + ) and ( + router1_messages.contains_mle_message(mle.CommandType.LINK_ACCEPT) + or router1_messages.contains_mle_message( + mle.CommandType.LINK_ACCEPT_AND_REQUEST + ) + ): - msg = router2_messages.next_mle_message(mle.CommandType.LINK_REQUEST) + msg = router2_messages.next_mle_message( + mle.CommandType.LINK_REQUEST + ) msg.assertSentToNode(self.nodes[req_receiver]) msg.assertMleMessageContainsTlv(mle.SourceAddress) @@ -86,8 +93,10 @@ class Cert_5_1_12_NewRouterSync(unittest.TestCase): msg.assertMleMessageContainsTlv(mle.Version) msg.assertMleMessageContainsTlv(mle.TlvRequest) - msg = router1_messages.next_mle_message_of_one_of_command_types(mle.CommandType.LINK_ACCEPT_AND_REQUEST, - mle.CommandType.LINK_ACCEPT) + msg = router1_messages.next_mle_message_of_one_of_command_types( + mle.CommandType.LINK_ACCEPT_AND_REQUEST, + mle.CommandType.LINK_ACCEPT, + ) self.assertIsNotNone(msg) msg.assertSentToNode(self.nodes[accept_receiver]) @@ -122,7 +131,7 @@ class Cert_5_1_12_NewRouterSync(unittest.TestCase): self.simulator.go(10) - leader_messages = self.simulator.get_messages_sent_by(LEADER) + self.simulator.get_messages_sent_by(LEADER) router1_messages = self.simulator.get_messages_sent_by(ROUTER1) router2_messages = self.simulator.get_messages_sent_by(ROUTER2) @@ -139,13 +148,20 @@ class Cert_5_1_12_NewRouterSync(unittest.TestCase): self.simulator.go(35) - leader_messages = self.simulator.get_messages_sent_by(LEADER) + self.simulator.get_messages_sent_by(LEADER) router1_messages = self.simulator.get_messages_sent_by(ROUTER1) router2_messages = self.simulator.get_messages_sent_by(ROUTER2) # 4 - Router1, Router2 - self.assertTrue(self.verify_step_4(router1_messages, router2_messages, ROUTER1, ROUTER2) or - self.verify_step_4(router2_messages, router1_messages, ROUTER2, ROUTER1)) + self.assertTrue( + self.verify_step_4( + router1_messages, router2_messages, ROUTER1, ROUTER2 + ) + or self.verify_step_4( + router2_messages, router1_messages, ROUTER2, ROUTER1 + ) + ) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_1_13_RouterReset.py b/tests/scripts/thread-cert/Cert_5_1_13_RouterReset.py index 02b0fb4bc..6c2952d48 100755 --- a/tests/scripts/thread-cert/Cert_5_1_13_RouterReset.py +++ b/tests/scripts/thread-cert/Cert_5_1_13_RouterReset.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -39,7 +38,6 @@ ROUTER = 2 class Cert_5_1_13_RouterReset(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -62,9 +60,9 @@ class Cert_5_1_13_RouterReset(unittest.TestCase): self.nodes[ROUTER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -105,8 +103,10 @@ class Cert_5_1_13_RouterReset(unittest.TestCase): msg = leader_messages.next_coap_message("2.04") router1_messages.next_mle_message(mle.CommandType.LINK_REQUEST) - msg = leader_messages.next_mle_message_of_one_of_command_types(mle.CommandType.LINK_ACCEPT_AND_REQUEST, - mle.CommandType.LINK_ACCEPT) + msg = leader_messages.next_mle_message_of_one_of_command_types( + mle.CommandType.LINK_ACCEPT_AND_REQUEST, + mle.CommandType.LINK_ACCEPT, + ) self.assertIsNotNone(msg) # 2 - Router1 / Leader diff --git a/tests/scripts/thread-cert/Cert_5_2_01_REEDAttach.py b/tests/scripts/thread-cert/Cert_5_2_01_REEDAttach.py index acd1afc77..0571c220d 100755 --- a/tests/scripts/thread-cert/Cert_5_2_01_REEDAttach.py +++ b/tests/scripts/thread-cert/Cert_5_2_01_REEDAttach.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node @@ -35,14 +34,13 @@ import mle import config import command -import shutil -import os LEADER = 1 DUT_ROUTER1 = 2 REED1 = 3 MED1 = 4 + class Cert_5_2_01_REEDAttach(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() @@ -77,9 +75,9 @@ class Cert_5_2_01_REEDAttach(unittest.TestCase): self.nodes[MED1].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -104,12 +102,16 @@ class Cert_5_2_01_REEDAttach(unittest.TestCase): # 3 DUT_ROUTER1: Verify MLE Parent Response router1_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) - msg = router1_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router1_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[REED1]) command.check_parent_response(msg) # 4 DUT_ROUTER1: Verify MLE Child ID Response - msg = router1_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) + msg = router1_messages.next_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ) msg.assertSentToNode(self.nodes[REED1]) command.check_child_id_response(msg) @@ -123,26 +125,32 @@ class Cert_5_2_01_REEDAttach(unittest.TestCase): # 7 REED1: Verify sending Address Solicit Request to DUT_ROUTER1 reed1_messages = self.simulator.get_messages_sent_by(REED1) msg = reed1_messages.next_coap_message('0.02') - reed1_ipv6_address = msg.ipv6_packet.ipv6_header.source_address.compressed - msg.assertSentToNode(self.nodes[DUT_ROUTER1]); + reed1_ipv6_address = ( + msg.ipv6_packet.ipv6_header.source_address.compressed + ) + msg.assertSentToNode(self.nodes[DUT_ROUTER1]) msg.assertCoapMessageRequestUriPath('/a/as') - # 8 DUT_ROUTER1: Verify forwarding REED1's Address Solicit Request to LEADER + # 8 DUT_ROUTER1: Verify forwarding REED1's Address Solicit Request to + # LEADER router1_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) msg = router1_messages.next_coap_message('0.02') - msg.assertSentToNode(self.nodes[LEADER]); + msg.assertSentToNode(self.nodes[LEADER]) msg.assertCoapMessageRequestUriPath('/a/as') - # DUT_ROUTER1: Verify forwarding LEADER's Address Solicit Response to REED1 + # DUT_ROUTER1: Verify forwarding LEADER's Address Solicit Response to + # REED1 msg = router1_messages.next_coap_message('2.04') msg.assertSentToDestinationAddress(reed1_ipv6_address) self.simulator.go(config.MAX_ADVERTISEMENT_INTERVAL) - # 9 LEADER: Verify connectivity by sending an ICMPv6 Echo Request to REED1 + # 9 LEADER: Verify connectivity by sending an ICMPv6 Echo Request to + # REED1 for addr in self.nodes[REED1].get_addrs(): if addr[0:4] != 'fe80': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_2_03_LeaderReject2Hops.py b/tests/scripts/thread-cert/Cert_5_2_03_LeaderReject2Hops.py index 82148c384..a28f74aaf 100755 --- a/tests/scripts/thread-cert/Cert_5_2_03_LeaderReject2Hops.py +++ b/tests/scripts/thread-cert/Cert_5_2_03_LeaderReject2Hops.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node @@ -40,13 +39,16 @@ ROUTER_1 = 2 ROUTER_31 = 32 ROUTER_32 = 33 + class Cert_5_2_3_LeaderReject2Hops(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - self.nodes[DUT_LEADER] = node.Node(DUT_LEADER, simulator=self.simulator) + self.nodes[DUT_LEADER] = node.Node( + DUT_LEADER, simulator=self.simulator + ) self.nodes[DUT_LEADER].set_panid(0xface) self.nodes[DUT_LEADER].set_mode('rsdn') self.nodes[DUT_LEADER].enable_whitelist() @@ -75,9 +77,9 @@ class Cert_5_2_3_LeaderReject2Hops(unittest.TestCase): self.nodes[ROUTER_32].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -99,7 +101,8 @@ class Cert_5_2_3_LeaderReject2Hops(unittest.TestCase): self.assertEqual(self.nodes[ROUTER_31].get_state(), 'router') # 3 - DUT_LEADER - # This method flushes the message queue so calling this method again will return only the newly logged messages. + # This method flushes the message queue so calling this method again + # will return only the newly logged messages. leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = leader_messages.next_coap_message('2.04') msg.assertCoapMessageContainsTlv(network_layer.Status) @@ -123,7 +126,10 @@ class Cert_5_2_3_LeaderReject2Hops(unittest.TestCase): msg.assertCoapMessageContainsTlv(network_layer.Status) status_tlv = msg.get_coap_message_tlv(network_layer.Status) - self.assertEqual(network_layer.StatusValues.NO_ADDRESS_AVAILABLE, status_tlv.status) + self.assertEqual( + network_layer.StatusValues.NO_ADDRESS_AVAILABLE, status_tlv.status + ) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_2_04_REEDUpgrade.py b/tests/scripts/thread-cert/Cert_5_2_04_REEDUpgrade.py index e9987d491..ce54fd438 100755 --- a/tests/scripts/thread-cert/Cert_5_2_04_REEDUpgrade.py +++ b/tests/scripts/thread-cert/Cert_5_2_04_REEDUpgrade.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node @@ -45,6 +44,7 @@ REED_ADVERTISEMENT_INTERVAL = 570 REED_ADVERTISEMENT_MAX_JITTER = 60 ROUTER_SELECTION_JITTER = 1 + class Cert_5_2_4_REEDUpgrade(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() @@ -79,9 +79,9 @@ class Cert_5_2_4_REEDUpgrade(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -115,7 +115,9 @@ class Cert_5_2_4_REEDUpgrade(unittest.TestCase): msg.assertMleMessageDoesNotContainTlv(mle.Route64) # 4 Wait for DUT_REED to send the second packet. - self.simulator.go(REED_ADVERTISEMENT_INTERVAL + REED_ADVERTISEMENT_MAX_JITTER) + self.simulator.go( + REED_ADVERTISEMENT_INTERVAL + REED_ADVERTISEMENT_MAX_JITTER + ) # 5 DUT_REED: Verify the second MLE Advertisement. reed_messages = self.simulator.get_messages_sent_by(DUT_REED) @@ -160,14 +162,19 @@ class Cert_5_2_4_REEDUpgrade(unittest.TestCase): msg.assertSentToNode(self.nodes[ED]) msg.assertMleMessageContainsTlv(mle.Address16) - # 11 Verify connectivity by sending an ICMPv6 Echo Request to the Leader. + # 11 Verify connectivity by sending an ICMPv6 Echo Request to the + # Leader. mleid = None for addr in self.nodes[LEADER].get_addrs(): - if addr.find(MESH_LOCAL_PREFIX) != -1 and addr.find(ROUTING_LACATOR) == -1: + if ( + addr.find(MESH_LOCAL_PREFIX) != -1 + and addr.find(ROUTING_LACATOR) == -1 + ): mleid = addr break self.assertTrue(self.nodes[ED].ping(mleid)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_2_05_AddressQuery.py b/tests/scripts/thread-cert/Cert_5_2_05_AddressQuery.py index c56d3891a..9efb67442 100755 --- a/tests/scripts/thread-cert/Cert_5_2_05_AddressQuery.py +++ b/tests/scripts/thread-cert/Cert_5_2_05_AddressQuery.py @@ -40,6 +40,7 @@ ED1 = 17 DUT_REED = 18 ROUTER_SELECTION_JITTER = 1 + class Cert_5_2_5_AddressQuery(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() @@ -74,9 +75,9 @@ class Cert_5_2_5_AddressQuery(unittest.TestCase): self.nodes[DUT_REED].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -123,8 +124,11 @@ class Cert_5_2_5_AddressQuery(unittest.TestCase): self.nodes[DUT_REED].add_whitelist(self.nodes[BR].get_addr64()) self.nodes[BR].add_whitelist(self.nodes[DUT_REED].get_addr64()) - # 6. Verify DUT_REED would send Address Notification when ping to its ML-EID. - mleid = self.nodes[DUT_REED].get_ip6_address(config.ADDRESS_TYPE.ML_EID) + # 6. Verify DUT_REED would send Address Notification when ping to its + # ML-EID. + mleid = self.nodes[DUT_REED].get_ip6_address( + config.ADDRESS_TYPE.ML_EID + ) self.assertTrue(self.nodes[ED1].ping(mleid)) # Wait for sniffer collecting packets @@ -132,12 +136,17 @@ class Cert_5_2_5_AddressQuery(unittest.TestCase): reed_messages = self.simulator.get_messages_sent_by(DUT_REED) msg = reed_messages.next_coap_message('0.02', '/a/an') - command.check_address_notification(msg, self.nodes[DUT_REED], self.nodes[LEADER]) + command.check_address_notification( + msg, self.nodes[DUT_REED], self.nodes[LEADER] + ) - # 7 & 8. Verify DUT_REED would send Address Notification when ping to its 2001::EID and 2002::EID. + # 7 & 8. Verify DUT_REED would send Address Notification when ping to + # its 2001::EID and 2002::EID. flag2001 = 0 flag2002 = 0 - for global_address in self.nodes[DUT_REED].get_ip6_address(config.ADDRESS_TYPE.GLOBAL): + for global_address in self.nodes[DUT_REED].get_ip6_address( + config.ADDRESS_TYPE.GLOBAL + ): if global_address[0:4] == '2001': flag2001 += 1 elif global_address[0:4] == '2002': @@ -151,10 +160,13 @@ class Cert_5_2_5_AddressQuery(unittest.TestCase): reed_messages = self.simulator.get_messages_sent_by(DUT_REED) msg = reed_messages.next_coap_message('0.02', '/a/an') - command.check_address_notification(msg, self.nodes[DUT_REED], self.nodes[LEADER]) + command.check_address_notification( + msg, self.nodes[DUT_REED], self.nodes[LEADER] + ) + + assert flag2001 == 1, "Error: Expecting address 2001::EID not appear." + assert flag2002 == 1, "Error: Expecting address 2002::EID not appear." - assert flag2001 == 1 , "Error: Expecting address 2001::EID not appear." - assert flag2002 == 1 , "Error: Expecting address 2002::EID not appear." if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_2_06_RouterDowngrade.py b/tests/scripts/thread-cert/Cert_5_2_06_RouterDowngrade.py index e016b543c..91c6d30c0 100755 --- a/tests/scripts/thread-cert/Cert_5_2_06_RouterDowngrade.py +++ b/tests/scripts/thread-cert/Cert_5_2_06_RouterDowngrade.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node @@ -40,6 +39,7 @@ DUT_ROUTER1 = 2 ROUTER2 = 3 ROUTER24 = 24 + class Cert_5_2_06_RouterDowngrade(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() @@ -55,9 +55,9 @@ class Cert_5_2_06_RouterDowngrade(unittest.TestCase): self.nodes[i].set_router_downgrade_threshold(32) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -71,12 +71,14 @@ class Cert_5_2_06_RouterDowngrade(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[i].get_state(), 'router') - # This method flushes the message queue so calling this method again will return only the newly logged messages. + # This method flushes the message queue so calling this method again + # will return only the newly logged messages. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) # 2 ROUTER24: Attach to network. # All reference testbed devices have been configured with downgrade threshold as 32 except DUT_ROUTER1, - # so we don't need to ensure ROUTER24 has a better link quality on posix. + # so we don't need to ensure ROUTER24 has a better link quality on + # posix. self.nodes[ROUTER24].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER24].get_state(), 'router') @@ -90,13 +92,17 @@ class Cert_5_2_06_RouterDowngrade(unittest.TestCase): dut_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) dut_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) - # Verify it sent an Address Release Message to the Leader when it attached as a child. + # Verify it sent an Address Release Message to the Leader when it + # attached as a child. msg = dut_messages.next_coap_message('0.02') command.check_address_release(msg, self.nodes[LEADER]) # 4 & 5 - router1_rloc = self.nodes[DUT_ROUTER1].get_ip6_address(config.ADDRESS_TYPE.RLOC) + router1_rloc = self.nodes[DUT_ROUTER1].get_ip6_address( + config.ADDRESS_TYPE.RLOC + ) self.assertTrue(self.nodes[LEADER].ping(router1_rloc)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_2_07_REEDSynchronization.py b/tests/scripts/thread-cert/Cert_5_2_07_REEDSynchronization.py index 4c294e6be..49315f678 100755 --- a/tests/scripts/thread-cert/Cert_5_2_07_REEDSynchronization.py +++ b/tests/scripts/thread-cert/Cert_5_2_07_REEDSynchronization.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import ipv6 @@ -42,6 +41,7 @@ DUT_REED = 17 MLE_MIN_LINKS = 3 + class Cert_5_2_7_REEDSynchronization(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() @@ -54,9 +54,9 @@ class Cert_5_2_7_REEDSynchronization(unittest.TestCase): self.nodes[i].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -74,7 +74,9 @@ class Cert_5_2_7_REEDSynchronization(unittest.TestCase): # 2. DUT_REED: Attach to network. Verify it didn't send an Address Solicit Request. # Avoid DUT_REED attach to DUT_ROUTER1. - self.nodes[DUT_REED].add_whitelist(self.nodes[DUT_ROUTER1].get_addr64(), config.RSSI['LINK_QULITY_1']) + self.nodes[DUT_REED].add_whitelist( + self.nodes[DUT_ROUTER1].get_addr64(), config.RSSI['LINK_QULITY_1'] + ) self.nodes[DUT_REED].start() self.simulator.go(config.MAX_ADVERTISEMENT_INTERVAL) @@ -83,33 +85,49 @@ class Cert_5_2_7_REEDSynchronization(unittest.TestCase): # The DUT_REED must not send a coap message here. reed_messages = self.simulator.get_messages_sent_by(DUT_REED) msg = reed_messages.does_not_contain_coap_message() - assert msg is True, "Error: The DUT_REED sent an Address Solicit Request" + assert ( + msg is True + ), "Error: The DUT_REED sent an Address Solicit Request" - # 3. DUT_REED: Verify sent a Link Request to at least 3 neighboring Routers. + # 3. DUT_REED: Verify sent a Link Request to at least 3 neighboring + # Routers. for i in range(0, MLE_MIN_LINKS): msg = reed_messages.next_mle_message(mle.CommandType.LINK_REQUEST) - command.check_link_request(msg, source_address = command.CheckType.CONTAIN, \ - leader_data = command.CheckType.CONTAIN) + command.check_link_request( + msg, + source_address=command.CheckType.CONTAIN, + leader_data=command.CheckType.CONTAIN, + ) # 4. DUT_REED: Verify at least 3 Link Accept messages sent to DUT_REED. self.simulator.go(config.MAX_ADVERTISEMENT_INTERVAL) link_accept_count = 0 - destination_link_local = self.nodes[DUT_REED].get_ip6_address(config.ADDRESS_TYPE.LINK_LOCAL) + destination_link_local = self.nodes[DUT_REED].get_ip6_address( + config.ADDRESS_TYPE.LINK_LOCAL + ) for i in range(1, DUT_REED): dut_messages = self.simulator.get_messages_sent_by(i) while True: - msg = dut_messages.next_mle_message(mle.CommandType.LINK_ACCEPT, False) - if msg == None: + msg = dut_messages.next_mle_message( + mle.CommandType.LINK_ACCEPT, False + ) + if msg is None: break - if ipv6.ip_address(destination_link_local) == msg.ipv6_packet.ipv6_header.destination_address: + if ( + ipv6.ip_address(destination_link_local) + == msg.ipv6_packet.ipv6_header.destination_address + ): command.check_link_accept(msg, self.nodes[DUT_REED]) link_accept_count += 1 break - assert (link_accept_count >= MLE_MIN_LINKS) is True, "Error: too few Link Accept sent to DUT_REED" + assert ( + link_accept_count >= MLE_MIN_LINKS + ) is True, "Error: too few Link Accept sent to DUT_REED" + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_01_LinkLocal.py b/tests/scripts/thread-cert/Cert_5_3_01_LinkLocal.py index 95adcbcaf..90a90426e 100755 --- a/tests/scripts/thread-cert/Cert_5_3_01_LinkLocal.py +++ b/tests/scripts/thread-cert/Cert_5_3_01_LinkLocal.py @@ -27,22 +27,21 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node import config -import command LEADER = 1 DUT_ROUTER1 = 2 + class Cert_5_3_1_LinkLocal(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -53,9 +52,9 @@ class Cert_5_3_1_LinkLocal(unittest.TestCase): self.nodes[DUT_ROUTER1].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -69,7 +68,9 @@ class Cert_5_3_1_LinkLocal(unittest.TestCase): self.assertEqual(self.nodes[DUT_ROUTER1].get_state(), 'router') # 2 & 3 - link_local = self.nodes[DUT_ROUTER1].get_ip6_address(config.ADDRESS_TYPE.LINK_LOCAL) + link_local = self.nodes[DUT_ROUTER1].get_ip6_address( + config.ADDRESS_TYPE.LINK_LOCAL + ) self.assertTrue(self.nodes[LEADER].ping(link_local, size=256)) self.assertTrue(self.nodes[LEADER].ping(link_local)) @@ -82,7 +83,12 @@ class Cert_5_3_1_LinkLocal(unittest.TestCase): self.assertTrue(self.nodes[LEADER].ping('ff02::2')) # 8 - self.assertTrue(self.nodes[LEADER].ping(config.LINK_LOCAL_All_THREAD_NODES_MULTICAST_ADDRESS)) + self.assertTrue( + self.nodes[LEADER].ping( + config.LINK_LOCAL_All_THREAD_NODES_MULTICAST_ADDRESS + ) + ) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_02_RealmLocal.py b/tests/scripts/thread-cert/Cert_5_3_02_RealmLocal.py index aa2e77add..97452b6e2 100755 --- a/tests/scripts/thread-cert/Cert_5_3_02_RealmLocal.py +++ b/tests/scripts/thread-cert/Cert_5_3_02_RealmLocal.py @@ -27,24 +27,23 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node import config -import command LEADER = 1 ROUTER1 = 2 DUT_ROUTER2 = 3 SED1 = 4 + class Cert_5_3_2_RealmLocal(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i == SED1), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -73,9 +72,9 @@ class Cert_5_3_2_RealmLocal(unittest.TestCase): self.nodes[SED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -97,12 +96,16 @@ class Cert_5_3_2_RealmLocal(unittest.TestCase): self.assertEqual(self.nodes[SED1].get_state(), 'child') # 2 & 3 - mleid = self.nodes[DUT_ROUTER2].get_ip6_address(config.ADDRESS_TYPE.ML_EID) + mleid = self.nodes[DUT_ROUTER2].get_ip6_address( + config.ADDRESS_TYPE.ML_EID + ) self.assertTrue(self.nodes[LEADER].ping(mleid, size=256)) self.assertTrue(self.nodes[LEADER].ping(mleid)) # 4 & 5 - self.assertTrue(self.nodes[LEADER].ping('ff03::1', num_responses=2, size=256)) + self.assertTrue( + self.nodes[LEADER].ping('ff03::1', num_responses=2, size=256) + ) sed_messages = self.simulator.get_messages_sent_by(SED1) self.assertFalse(sed_messages.contains_icmp_message()) @@ -111,7 +114,9 @@ class Cert_5_3_2_RealmLocal(unittest.TestCase): self.assertFalse(sed_messages.contains_icmp_message()) # 6 & 7 - self.assertTrue(self.nodes[LEADER].ping('ff03::2', num_responses=2, size=256)) + self.assertTrue( + self.nodes[LEADER].ping('ff03::2', num_responses=2, size=256) + ) sed_messages = self.simulator.get_messages_sent_by(SED1) self.assertFalse(sed_messages.contains_icmp_message()) @@ -120,15 +125,27 @@ class Cert_5_3_2_RealmLocal(unittest.TestCase): self.assertFalse(sed_messages.contains_icmp_message()) # 8 - self.assertTrue(self.nodes[LEADER].ping(config.REALM_LOCAL_All_THREAD_NODES_MULTICAST_ADDRESS, num_responses=3, size=256)) + self.assertTrue( + self.nodes[LEADER].ping( + config.REALM_LOCAL_All_THREAD_NODES_MULTICAST_ADDRESS, + num_responses=3, + size=256, + ) + ) self.simulator.go(2) sed_messages = self.simulator.get_messages_sent_by(SED1) self.assertTrue(sed_messages.contains_icmp_message()) - self.assertTrue(self.nodes[LEADER].ping(config.REALM_LOCAL_All_THREAD_NODES_MULTICAST_ADDRESS, num_responses=3)) + self.assertTrue( + self.nodes[LEADER].ping( + config.REALM_LOCAL_All_THREAD_NODES_MULTICAST_ADDRESS, + num_responses=3, + ) + ) self.simulator.go(2) sed_messages = self.simulator.get_messages_sent_by(SED1) self.assertTrue(sed_messages.contains_icmp_message()) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_03_AddressQuery.py b/tests/scripts/thread-cert/Cert_5_3_03_AddressQuery.py index 93eb09c17..7d438c3f6 100755 --- a/tests/scripts/thread-cert/Cert_5_3_03_AddressQuery.py +++ b/tests/scripts/thread-cert/Cert_5_3_03_AddressQuery.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node @@ -41,12 +40,13 @@ ROUTER3 = 4 MED1 = 5 MED1_TIMEOUT = 3 + class Cert_5_3_3_AddressQuery(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i == MED1), simulator=self.simulator) self.nodes[LEADER].set_panid() @@ -84,9 +84,9 @@ class Cert_5_3_3_AddressQuery(unittest.TestCase): self.nodes[MED1].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -106,39 +106,54 @@ class Cert_5_3_3_AddressQuery(unittest.TestCase): self.assertEqual(self.nodes[ROUTER3].get_state(), 'router') self.assertEqual(self.nodes[MED1].get_state(), 'child') - # 2 - # Flush the message queue to avoid possible impact on follow-up verification. + # Flush the message queue to avoid possible impact on follow-up + # verification. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) - router3_mleid = self.nodes[ROUTER3].get_ip6_address(config.ADDRESS_TYPE.ML_EID) + router3_mleid = self.nodes[ROUTER3].get_ip6_address( + config.ADDRESS_TYPE.ML_EID + ) self.assertTrue(self.nodes[MED1].ping(router3_mleid)) - # Verify DUT_ROUTER2 sent an Address Query Request to the Realm local address. + # Verify DUT_ROUTER2 sent an Address Query Request to the Realm local + # address. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_messages.next_coap_message('0.02', '/a/aq') - command.check_address_query(msg, self.nodes[DUT_ROUTER2], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + command.check_address_query( + msg, + self.nodes[DUT_ROUTER2], + config.REALM_LOCAL_ALL_ROUTERS_ADDRESS, + ) # 3 - # Wait the finish of address resolution traffic triggerred by previous ping. + # Wait the finish of address resolution traffic triggerred by previous + # ping. self.simulator.go(5) - # Flush the message queue to avoid possible impact on follow-up verification. + # Flush the message queue to avoid possible impact on follow-up + # verification. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) - med1_mleid = self.nodes[MED1].get_ip6_address(config.ADDRESS_TYPE.ML_EID) + med1_mleid = self.nodes[MED1].get_ip6_address( + config.ADDRESS_TYPE.ML_EID + ) self.assertTrue(self.nodes[ROUTER1].ping(med1_mleid)) # Verify DUT_ROUTER2 responded with an Address Notification. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_messages.next_coap_message('0.02', '/a/an') - command.check_address_notification(msg, self.nodes[DUT_ROUTER2], self.nodes[ROUTER1]) + command.check_address_notification( + msg, self.nodes[DUT_ROUTER2], self.nodes[ROUTER1] + ) # 4 - # Wait the finish of address resolution traffic triggerred by previous ping. + # Wait the finish of address resolution traffic triggerred by previous + # ping. self.simulator.go(5) - # Flush the message queue to avoid possible impact on follow-up verification. + # Flush the message queue to avoid possible impact on follow-up + # verification. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) self.assertTrue(self.nodes[MED1].ping(router3_mleid)) @@ -152,25 +167,33 @@ class Cert_5_3_3_AddressQuery(unittest.TestCase): # Power off ROUTER3 and wait for leader to expire its Router ID. # In this topology, ROUTER3 has two neighbors (Leader and DUT_ROUTER2), # so the wait time is (MAX_NEIGHBOR_AGE (100s) + worst propagation time (32s * 15) for bad routing +\ - # INFINITE_COST_TIMEOUT (90s) + transmission time + extra redundancy), totally ~700s. + # INFINITE_COST_TIMEOUT (90s) + transmission time + extra redundancy), + # totally ~700s. self.nodes[ROUTER3].stop() self.simulator.go(700) - # Flush the message queue to avoid possible impact on follow-up verification. + # Flush the message queue to avoid possible impact on follow-up + # verification. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) self.assertFalse(self.nodes[MED1].ping(router3_mleid)) - # Verify DUT_ROUTER2 sent an Address Query Request to the Realm local address. + # Verify DUT_ROUTER2 sent an Address Query Request to the Realm local + # address. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_messages.next_coap_message('0.02', '/a/aq') - command.check_address_query(msg, self.nodes[DUT_ROUTER2], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + command.check_address_query( + msg, + self.nodes[DUT_ROUTER2], + config.REALM_LOCAL_ALL_ROUTERS_ADDRESS, + ) # 6 self.nodes[MED1].stop() self.simulator.go(MED1_TIMEOUT) - # Flush the message queue to avoid possible impact on follow-up verification. + # Flush the message queue to avoid possible impact on follow-up + # verification. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) self.assertFalse(self.nodes[ROUTER1].ping(med1_mleid)) @@ -181,5 +204,6 @@ class Cert_5_3_3_AddressQuery(unittest.TestCase): msg = dut_messages.next_coap_message('0.02', '/a/an', False) assert msg is None, "The Address Notification is not expected." + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_04_AddressMapCache.py b/tests/scripts/thread-cert/Cert_5_3_04_AddressMapCache.py index d454c566a..178bf7666 100755 --- a/tests/scripts/thread-cert/Cert_5_3_04_AddressMapCache.py +++ b/tests/scripts/thread-cert/Cert_5_3_04_AddressMapCache.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node @@ -44,12 +43,13 @@ ED4 = 7 MTDS = [SED1, ED1, ED2, ED3, ED4] + class Cert_5_3_4_AddressMapCache(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,8): + for i in range(1, 8): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -72,7 +72,8 @@ class Cert_5_3_4_AddressMapCache(unittest.TestCase): self.nodes[SED1].set_mode('s') self.nodes[SED1].add_whitelist(self.nodes[DUT_ROUTER1].get_addr64()) - # Set the SED1's timeout in order to receive the icmp reply when keep alive with DUT_ROUTER. + # Set the SED1's timeout in order to receive the icmp reply when keep + # alive with DUT_ROUTER. self.nodes[SED1].set_timeout(5) self.nodes[SED1].enable_whitelist() @@ -83,9 +84,9 @@ class Cert_5_3_4_AddressMapCache(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -104,33 +105,47 @@ class Cert_5_3_4_AddressMapCache(unittest.TestCase): for i in MTDS: self.assertEqual(self.nodes[i].get_state(), 'child') - # This method flushes the message queue so calling this method again will return only the newly logged messages. + # This method flushes the message queue so calling this method again + # will return only the newly logged messages. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) # 2 for ED in [ED1, ED2, ED3, ED4]: - ed_mleid = self.nodes[ED].get_ip6_address(config.ADDRESS_TYPE.ML_EID) + ed_mleid = self.nodes[ED].get_ip6_address( + config.ADDRESS_TYPE.ML_EID + ) self.assertTrue(self.nodes[SED1].ping(ed_mleid)) self.simulator.go(5) - # Verify DUT_ROUTER1 generated an Address Query Request to find each node's RLOC. + # Verify DUT_ROUTER1 generated an Address Query Request to find + # each node's RLOC. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) msg = dut_messages.next_coap_message('0.02', '/a/aq') - command.check_address_query(msg, self.nodes[DUT_ROUTER1], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + command.check_address_query( + msg, + self.nodes[DUT_ROUTER1], + config.REALM_LOCAL_ALL_ROUTERS_ADDRESS, + ) # 3 & 4 - # This method flushes the message queue so calling this method again will return only the newly logged messages. + # This method flushes the message queue so calling this method again + # will return only the newly logged messages. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) for ED in [ED1, ED2, ED3, ED4]: - ed_mleid = self.nodes[ED].get_ip6_address(config.ADDRESS_TYPE.ML_EID) + ed_mleid = self.nodes[ED].get_ip6_address( + config.ADDRESS_TYPE.ML_EID + ) self.assertTrue(self.nodes[SED1].ping(ed_mleid)) self.simulator.go(5) # Verify DUT_ROUTER1 didn't generate an Address Query Request. dut_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) msg = dut_messages.next_coap_message('0.02', '/a/aq', False) - assert msg is None, "Error: The DUT sent an unexpected Address Query Request" + assert ( + msg is None + ), "Error: The DUT sent an unexpected Address Query Request" + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_05_RoutingLinkQuality.py b/tests/scripts/thread-cert/Cert_5_3_05_RoutingLinkQuality.py index 7938e4909..14a76ae18 100755 --- a/tests/scripts/thread-cert/Cert_5_3_05_RoutingLinkQuality.py +++ b/tests/scripts/thread-cert/Cert_5_3_05_RoutingLinkQuality.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node @@ -39,12 +38,13 @@ DUT_ROUTER1 = 2 ROUTER2 = 3 ROUTER3 = 4 + class Cert_5_3_5_RoutingLinkQuality(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -75,9 +75,9 @@ class Cert_5_3_5_RoutingLinkQuality(unittest.TestCase): self.nodes[ROUTER3].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -94,7 +94,9 @@ class Cert_5_3_5_RoutingLinkQuality(unittest.TestCase): self.assertEqual(self.nodes[router].get_state(), 'router') # 2 & 3 - leader_rloc = self.nodes[LEADER].get_ip6_address(config.ADDRESS_TYPE.RLOC) + leader_rloc = self.nodes[LEADER].get_ip6_address( + config.ADDRESS_TYPE.RLOC + ) # Verify the ICMPv6 Echo Request took the least cost path. self.assertTrue(self.nodes[ROUTER3].ping(leader_rloc)) @@ -102,35 +104,52 @@ class Cert_5_3_5_RoutingLinkQuality(unittest.TestCase): command.check_icmp_path(self.simulator, path, self.nodes) # 4 & 5 - self.nodes[LEADER].add_whitelist(self.nodes[DUT_ROUTER1].get_addr64(), config.RSSI['LINK_QULITY_1']) - self.nodes[DUT_ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64(), config.RSSI['LINK_QULITY_1']) + self.nodes[LEADER].add_whitelist( + self.nodes[DUT_ROUTER1].get_addr64(), config.RSSI['LINK_QULITY_1'] + ) + self.nodes[DUT_ROUTER1].add_whitelist( + self.nodes[LEADER].get_addr64(), config.RSSI['LINK_QULITY_1'] + ) self.simulator.go(3 * config.MAX_ADVERTISEMENT_INTERVAL) - # Verify the ICMPv6 Echo Request took the longer path because it cost less. + # Verify the ICMPv6 Echo Request took the longer path because it cost + # less. self.assertTrue(self.nodes[ROUTER3].ping(leader_rloc)) path = [ROUTER3, DUT_ROUTER1, ROUTER2, LEADER] command.check_icmp_path(self.simulator, path, self.nodes) # 6 & 7 - self.nodes[LEADER].add_whitelist(self.nodes[DUT_ROUTER1].get_addr64(), config.RSSI['LINK_QULITY_2']) - self.nodes[DUT_ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64(), config.RSSI['LINK_QULITY_2']) + self.nodes[LEADER].add_whitelist( + self.nodes[DUT_ROUTER1].get_addr64(), config.RSSI['LINK_QULITY_2'] + ) + self.nodes[DUT_ROUTER1].add_whitelist( + self.nodes[LEADER].get_addr64(), config.RSSI['LINK_QULITY_2'] + ) self.simulator.go(3 * config.MAX_ADVERTISEMENT_INTERVAL) - # Verify the direct neighbor would be prioritized when there are two paths with the same cost. + # Verify the direct neighbor would be prioritized when there are two + # paths with the same cost. self.assertTrue(self.nodes[ROUTER3].ping(leader_rloc)) path = [ROUTER3, DUT_ROUTER1, LEADER] command.check_icmp_path(self.simulator, path, self.nodes) # 8 & 9 - self.nodes[LEADER].add_whitelist(self.nodes[DUT_ROUTER1].get_addr64(), config.RSSI['LINK_QULITY_0']) - self.nodes[DUT_ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64(), config.RSSI['LINK_QULITY_0']) + self.nodes[LEADER].add_whitelist( + self.nodes[DUT_ROUTER1].get_addr64(), config.RSSI['LINK_QULITY_0'] + ) + self.nodes[DUT_ROUTER1].add_whitelist( + self.nodes[LEADER].get_addr64(), config.RSSI['LINK_QULITY_0'] + ) self.simulator.go(3 * config.MAX_ADVERTISEMENT_INTERVAL) # Verify the ICMPv6 Echo Request took the longer path. - leader_rloc = self.nodes[LEADER].get_ip6_address(config.ADDRESS_TYPE.RLOC) + leader_rloc = self.nodes[LEADER].get_ip6_address( + config.ADDRESS_TYPE.RLOC + ) self.assertTrue(self.nodes[ROUTER3].ping(leader_rloc)) path = [ROUTER3, DUT_ROUTER1, ROUTER2, LEADER] command.check_icmp_path(self.simulator, path, self.nodes) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_06_RouterIdMask.py b/tests/scripts/thread-cert/Cert_5_3_06_RouterIdMask.py index bfb27d294..c62c6bec5 100755 --- a/tests/scripts/thread-cert/Cert_5_3_06_RouterIdMask.py +++ b/tests/scripts/thread-cert/Cert_5_3_06_RouterIdMask.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node @@ -39,12 +38,13 @@ DUT_LEADER = 1 ROUTER1 = 2 ROUTER2 = 3 + class Cert_5_3_6_RouterIdMask(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[DUT_LEADER].set_panid(0xface) @@ -69,9 +69,9 @@ class Cert_5_3_6_RouterIdMask(unittest.TestCase): self.nodes[ROUTER2].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -89,7 +89,8 @@ class Cert_5_3_6_RouterIdMask(unittest.TestCase): self.assertEqual(self.nodes[ROUTER2].get_state(), 'router') router2_id = self.nodes[ROUTER2].get_router_id() - # Wait DUT_LEADER to establish routing to ROUTER2 via ROUTER1's MLE advertisement. + # Wait DUT_LEADER to establish routing to ROUTER2 via ROUTER1's MLE + # advertisement. self.simulator.go(config.MAX_ADVERTISEMENT_INTERVAL) # 2 @@ -97,18 +98,22 @@ class Cert_5_3_6_RouterIdMask(unittest.TestCase): self._setUpRouter2() # 3 & 4 - # Flush the message queue to avoid possible impact on follow-up verification. - dut_messages = self.simulator.get_messages_sent_by(DUT_LEADER) + # Flush the message queue to avoid possible impact on follow-up + # verification. + self.simulator.get_messages_sent_by(DUT_LEADER) - # Verify the cost from DUT_LEADER to ROUTER2 goes to infinity in 12 mins. + # Verify the cost from DUT_LEADER to ROUTER2 goes to infinity in 12 + # mins. routing_cost = 1 for i in range(0, 24): self.simulator.go(30) - print("%ss" %((i + 1) * 30)) + print("%ss" % ((i + 1) * 30)) leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) - msg = leader_messages.last_mle_message(mle.CommandType.ADVERTISEMENT, False) - if msg == None: + msg = leader_messages.last_mle_message( + mle.CommandType.ADVERTISEMENT, False + ) + if msg is None: continue self.assertTrue(command.check_id_set(msg, router2_id)) @@ -118,14 +123,17 @@ class Cert_5_3_6_RouterIdMask(unittest.TestCase): break self.assertTrue(routing_cost == 0) - self.simulator.go(config.INFINITE_COST_TIMEOUT + config.MAX_ADVERTISEMENT_INTERVAL) + self.simulator.go( + config.INFINITE_COST_TIMEOUT + config.MAX_ADVERTISEMENT_INTERVAL + ) leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = leader_messages.last_mle_message(mle.CommandType.ADVERTISEMENT) self.assertFalse(command.check_id_set(msg, router2_id)) # 5 - # Flush the message queue to avoid possible impact on follow-up verification. - dut_messages = self.simulator.get_messages_sent_by(DUT_LEADER) + # Flush the message queue to avoid possible impact on follow-up + # verification. + self.simulator.get_messages_sent_by(DUT_LEADER) self.nodes[ROUTER2].start() self.simulator.go(5) @@ -142,16 +150,21 @@ class Cert_5_3_6_RouterIdMask(unittest.TestCase): router1_id = self.nodes[ROUTER1].get_router_id() router2_id = self.nodes[ROUTER2].get_router_id() - self.simulator.go(config.MAX_NEIGHBOR_AGE + config.MAX_ADVERTISEMENT_INTERVAL) + self.simulator.go( + config.MAX_NEIGHBOR_AGE + config.MAX_ADVERTISEMENT_INTERVAL + ) leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = leader_messages.last_mle_message(mle.CommandType.ADVERTISEMENT) self.assertEqual(command.get_routing_cost(msg, router1_id), 0) - self.simulator.go(config.INFINITE_COST_TIMEOUT + config.MAX_ADVERTISEMENT_INTERVAL) + self.simulator.go( + config.INFINITE_COST_TIMEOUT + config.MAX_ADVERTISEMENT_INTERVAL + ) leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = leader_messages.last_mle_message(mle.CommandType.ADVERTISEMENT) self.assertFalse(command.check_id_set(msg, router1_id)) self.assertFalse(command.check_id_set(msg, router2_id)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_06b_RouterIdMask.py b/tests/scripts/thread-cert/Cert_5_3_06b_RouterIdMask.py index a4c05df28..08850822e 100755 --- a/tests/scripts/thread-cert/Cert_5_3_06b_RouterIdMask.py +++ b/tests/scripts/thread-cert/Cert_5_3_06b_RouterIdMask.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,12 +36,13 @@ LEADER = 1 ROUTER1 = 2 ROUTER2 = 3 + class Cert_5_3_6_RouterIdMask(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -64,9 +64,9 @@ class Cert_5_3_6_RouterIdMask(unittest.TestCase): self.nodes[ROUTER2].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -87,5 +87,6 @@ class Cert_5_3_6_RouterIdMask(unittest.TestCase): self.simulator.go(300) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_07_DuplicateAddress.py b/tests/scripts/thread-cert/Cert_5_3_07_DuplicateAddress.py index e63849e22..7918e21fa 100755 --- a/tests/scripts/thread-cert/Cert_5_3_07_DuplicateAddress.py +++ b/tests/scripts/thread-cert/Cert_5_3_07_DuplicateAddress.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node @@ -44,12 +43,13 @@ MED3 = 6 MTDS = [MED1, SED1, MED3] + class Cert_5_3_7_DuplicateAddress(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,7): + for i in range(1, 7): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[DUT_LEADER].set_panid(0xface) @@ -89,9 +89,9 @@ class Cert_5_3_7_DuplicateAddress(unittest.TestCase): self.nodes[MED3].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -129,22 +129,30 @@ class Cert_5_3_7_DuplicateAddress(unittest.TestCase): self.simulator.go(5) # 4 - # Flush the message queue to avoid possible impact on follow-up verification. + # Flush the message queue to avoid possible impact on follow-up + # verification. self.simulator.get_messages_sent_by(DUT_LEADER) self.nodes[MED3].ping('2001:2:0:1::1234') - # Verify DUT_LEADER sent an Address Query Request to the Realm local address. + # Verify DUT_LEADER sent an Address Query Request to the Realm local + # address. dut_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = dut_messages.next_coap_message('0.02', '/a/aq') - command.check_address_query(msg, self.nodes[DUT_LEADER], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + command.check_address_query( + msg, self.nodes[DUT_LEADER], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS + ) # 5 & 6 - # Verify DUT_LEADER sent an Address Error Notification to the Realm local address. + # Verify DUT_LEADER sent an Address Error Notification to the Realm + # local address. self.simulator.go(5) dut_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = dut_messages.next_coap_message('0.02', '/a/ae') - command.check_address_error_notification(msg, self.nodes[DUT_LEADER], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + command.check_address_error_notification( + msg, self.nodes[DUT_LEADER], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS + ) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_08_ChildAddressSet.py b/tests/scripts/thread-cert/Cert_5_3_08_ChildAddressSet.py index 6926ff086..fa9c25657 100755 --- a/tests/scripts/thread-cert/Cert_5_3_08_ChildAddressSet.py +++ b/tests/scripts/thread-cert/Cert_5_3_08_ChildAddressSet.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -43,6 +42,7 @@ MED2 = 4 MTDS = [MED1, MED2] + class Cert_5_3_8_ChildAddressSet(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() @@ -71,9 +71,9 @@ class Cert_5_3_8_ChildAddressSet(unittest.TestCase): self.nodes[i].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -108,14 +108,18 @@ class Cert_5_3_8_ChildAddressSet(unittest.TestCase): self.assertEqual(self.nodes[i].get_state(), 'child') # 4 MED1: MED1 send an ICMPv6 Echo Request to the MED2 ML-EID - med2_ml_eid = self.nodes[MED2].get_ip6_address(config.ADDRESS_TYPE.ML_EID) - self.assertTrue(med2_ml_eid != None) + med2_ml_eid = self.nodes[MED2].get_ip6_address( + config.ADDRESS_TYPE.ML_EID + ) + self.assertTrue(med2_ml_eid is not None) self.assertTrue(self.nodes[MED1].ping(med2_ml_eid)) # Verify DUT_LEADER didn't generate an Address Query Request leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = leader_messages.next_coap_message('0.02', '/a/aq', False) - assert msg is None, "Error: The DUT_LEADER sent an unexpected Address Query Request" + assert ( + msg is None + ), "Error: The DUT_LEADER sent an unexpected Address Query Request" # Wait for sniffer got packets self.simulator.go(1) @@ -123,7 +127,9 @@ class Cert_5_3_8_ChildAddressSet(unittest.TestCase): # Verify MED2 sent an ICMPv6 Echo Reply med2_messages = self.simulator.get_messages_sent_by(MED2) msg = med2_messages.get_icmp_message(ipv6.ICMP_ECHO_RESPONSE) - assert msg is not None, "Error: The MED2 didn't send ICMPv6 Echo Reply to MED1" + assert ( + msg is not None + ), "Error: The MED2 didn't send ICMPv6 Echo Reply to MED1" # 5 MED1: MED1 send an ICMPv6 Echo Request to the MED2 2001::GUA addr = self.nodes[MED2].get_addr("2001::/64") @@ -133,7 +139,9 @@ class Cert_5_3_8_ChildAddressSet(unittest.TestCase): # Verify DUT_LEADER didn't generate an Address Query Request leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = leader_messages.next_coap_message('0.02', '/a/aq', False) - assert msg is None, "Error: The DUT_LEADER sent an unexpected Address Query Request" + assert ( + msg is None + ), "Error: The DUT_LEADER sent an unexpected Address Query Request" # Wait for sniffer got packets self.simulator.go(1) @@ -141,7 +149,9 @@ class Cert_5_3_8_ChildAddressSet(unittest.TestCase): # Verify MED2 sent an ICMPv6 Echo Reply med2_messages = self.simulator.get_messages_sent_by(MED2) msg = med2_messages.get_icmp_message(ipv6.ICMP_ECHO_RESPONSE) - assert msg is not None, "Error: The MED2 didn't send ICMPv6 Echo Reply to MED1" + assert ( + msg is not None + ), "Error: The MED2 didn't send ICMPv6 Echo Reply to MED1" # 6 MED1: MED1 send an ICMPv6 Echo Request to the MED2 2002::GUA addr = self.nodes[MED2].get_addr("2002::/64") @@ -151,7 +161,9 @@ class Cert_5_3_8_ChildAddressSet(unittest.TestCase): # Verify DUT_LEADER didn't generate an Address Query Request leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = leader_messages.next_coap_message('0.02', '/a/aq', False) - assert msg is None, "Error: The DUT_LEADER sent an unexpected Address Query Request" + assert ( + msg is None + ), "Error: The DUT_LEADER sent an unexpected Address Query Request" # Wait for sniffer got packets self.simulator.go(1) @@ -159,7 +171,9 @@ class Cert_5_3_8_ChildAddressSet(unittest.TestCase): # Verify MED2 sent an ICMPv6 Echo Reply med2_messages = self.simulator.get_messages_sent_by(MED2) msg = med2_messages.get_icmp_message(ipv6.ICMP_ECHO_RESPONSE) - assert msg is not None, "Error: The MED2 didn't send ICMPv6 Echo Reply to MED1" + assert ( + msg is not None + ), "Error: The MED2 didn't send ICMPv6 Echo Reply to MED1" # 7 MED1: MED1 send an ICMPv6 Echo Request to the MED2 2003::GUA addr = self.nodes[MED2].get_addr("2003::/64") @@ -169,7 +183,9 @@ class Cert_5_3_8_ChildAddressSet(unittest.TestCase): # Verify DUT_LEADER didn't generate an Address Query Request leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = leader_messages.next_coap_message('0.02', '/a/aq', False) - assert msg is None, "Error: The DUT_LEADER sent an unexpected Address Query Request" + assert ( + msg is None + ), "Error: The DUT_LEADER sent an unexpected Address Query Request" # Wait for sniffer got packets self.simulator.go(1) @@ -177,7 +193,10 @@ class Cert_5_3_8_ChildAddressSet(unittest.TestCase): # Verify MED2 sent an ICMPv6 Echo Reply med2_messages = self.simulator.get_messages_sent_by(MED2) msg = med2_messages.get_icmp_message(ipv6.ICMP_ECHO_RESPONSE) - assert msg is not None, "Error: The MED2 didn't send ICMPv6 Echo Reply to MED1" + assert ( + msg is not None + ), "Error: The MED2 didn't send ICMPv6 Echo Reply to MED1" + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_09_AddressQuery.py b/tests/scripts/thread-cert/Cert_5_3_09_AddressQuery.py index 3144c884a..496d127e5 100755 --- a/tests/scripts/thread-cert/Cert_5_3_09_AddressQuery.py +++ b/tests/scripts/thread-cert/Cert_5_3_09_AddressQuery.py @@ -28,9 +28,7 @@ # import copy -import time import unittest -import ipaddress import command import config @@ -43,12 +41,13 @@ DUT_ROUTER2 = 3 ROUTER3 = 4 SED1 = 5 + class Cert_5_3_09_AddressQuery(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i == SED1), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -84,9 +83,9 @@ class Cert_5_3_09_AddressQuery(unittest.TestCase): self.nodes[SED1].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -95,7 +94,8 @@ class Cert_5_3_09_AddressQuery(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[LEADER].get_state(), 'leader') - # Configure the LEADER to be a DHCPv6 Border Router for prefixes 2001:: & 2002:: + # Configure the LEADER to be a DHCPv6 Border Router for prefixes 2001:: + # & 2002:: self.nodes[LEADER].add_prefix('2001::/64', 'pdros') self.nodes[LEADER].add_prefix('2002::/64', 'pdro') self.nodes[LEADER].register_netdata() @@ -120,7 +120,8 @@ class Cert_5_3_09_AddressQuery(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[SED1].get_state(), 'child') - # 3 SED1: The SED1 sends an ICMPv6 Echo Request to ROUTER3 using GUA 2001:: address + # 3 SED1: The SED1 sends an ICMPv6 Echo Request to ROUTER3 using GUA + # 2001:: address router3_addr = self.nodes[ROUTER3].get_addr("2001::/64") self.assertTrue(router3_addr is not None) self.assertTrue(self.nodes[SED1].ping(router3_addr)) @@ -128,15 +129,24 @@ class Cert_5_3_09_AddressQuery(unittest.TestCase): # Verify DUT_ROUTER2 sent an Address Query Request dut_router2_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_router2_messages.next_coap_message('0.02', '/a/aq') - msg.assertSentToDestinationAddress(config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) - command.check_address_query(msg, self.nodes[DUT_ROUTER2], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + msg.assertSentToDestinationAddress( + config.REALM_LOCAL_ALL_ROUTERS_ADDRESS + ) + command.check_address_query( + msg, + self.nodes[DUT_ROUTER2], + config.REALM_LOCAL_ALL_ROUTERS_ADDRESS, + ) # Verify the DUT_ROUTER2 forwarded the ICMPv6 Echo Request to ROUTER3 msg = dut_router2_messages.get_icmp_message(ipv6.ICMP_ECHO_REQUEST) - assert msg is not None, "Error: The DUT_ROUTER2 didn't forward ICMPv6 Echo Request to ROUTER3" + assert ( + msg is not None + ), "Error: The DUT_ROUTER2 didn't forward ICMPv6 Echo Request to ROUTER3" msg.assertSentToNode(self.nodes[ROUTER3]) - # 4 ROUTER1: ROUTER1 sends an ICMPv6 Echo Request to the SED1 using GUA 2001:: address + # 4 ROUTER1: ROUTER1 sends an ICMPv6 Echo Request to the SED1 using GUA + # 2001:: address sed1_addr = self.nodes[SED1].get_addr("2001::/64") self.assertTrue(sed1_addr is not None) self.assertTrue(self.nodes[ROUTER1].ping(sed1_addr)) @@ -147,9 +157,12 @@ class Cert_5_3_09_AddressQuery(unittest.TestCase): # Verify DUT_ROUTER2 sent an Address Notification message dut_router2_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_router2_messages.next_coap_message('0.02', '/a/an') - command.check_address_notification(msg, self.nodes[DUT_ROUTER2], self.nodes[ROUTER1]) + command.check_address_notification( + msg, self.nodes[DUT_ROUTER2], self.nodes[ROUTER1] + ) - # 5 SED1: SED1 sends an ICMPv6 Echo Request to the ROUTER3 using GUA 2001:: address + # 5 SED1: SED1 sends an ICMPv6 Echo Request to the ROUTER3 using GUA + # 2001:: address self.assertTrue(self.nodes[SED1].ping(router3_addr)) # Wait for sniffer got the ICMPv6 Echo Reply @@ -159,14 +172,21 @@ class Cert_5_3_09_AddressQuery(unittest.TestCase): dut_router2_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) dut_router2_messages_temp = copy.deepcopy(dut_router2_messages) msg = dut_router2_messages.next_coap_message('0.02', '/a/aq', False) - assert msg is None, "Error: The DUT_ROUTER2 sent an unexpected Address Query Request" + assert ( + msg is None + ), "Error: The DUT_ROUTER2 sent an unexpected Address Query Request" # Verify DUT_ROUTER2 forwarded the ICMPv6 Echo Reply to SED1 - msg = dut_router2_messages_temp.get_icmp_message(ipv6.ICMP_ECHO_RESPONSE) - assert msg is not None, "Error: The DUT_ROUTER2 didn't forward ICMPv6 Echo Reply to SED1" + msg = dut_router2_messages_temp.get_icmp_message( + ipv6.ICMP_ECHO_RESPONSE + ) + assert ( + msg is not None + ), "Error: The DUT_ROUTER2 didn't forward ICMPv6 Echo Reply to SED1" msg.assertSentToNode(self.nodes[SED1]) - # 6 DUT_ROUTER2: Power off ROUTER3 and wait 580s to alow LEADER to expire its Router ID + # 6 DUT_ROUTER2: Power off ROUTER3 and wait 580s to alow LEADER to + # expire its Router ID self.nodes[ROUTER3].stop() self.simulator.go(580) @@ -176,9 +196,12 @@ class Cert_5_3_09_AddressQuery(unittest.TestCase): # Verify DUT_ROUTER2 sent an Address Query Request dut_router2_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_router2_messages.next_coap_message('0.02', '/a/aq') - msg.assertSentToDestinationAddress(config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + msg.assertSentToDestinationAddress( + config.REALM_LOCAL_ALL_ROUTERS_ADDRESS + ) - # 7 SED1: Power off SED1 and wait to allow DUT_ROUTER2 to timeout the child + # 7 SED1: Power off SED1 and wait to allow DUT_ROUTER2 to timeout the + # child self.nodes[SED1].stop() self.simulator.go(5) @@ -189,7 +212,10 @@ class Cert_5_3_09_AddressQuery(unittest.TestCase): # Verify DUT_ROUTER2 didn't generate an Address Notification message dut_router2_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_router2_messages.next_coap_message('0.02', '/a/an', False) - assert msg is None, "Error: The DUT_ROUTER2 sent an unexpected Address Notification message" + assert ( + msg is None + ), "Error: The DUT_ROUTER2 sent an unexpected Address Notification message" + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_10_AddressQuery.py b/tests/scripts/thread-cert/Cert_5_3_10_AddressQuery.py index 379206850..fb576cd87 100755 --- a/tests/scripts/thread-cert/Cert_5_3_10_AddressQuery.py +++ b/tests/scripts/thread-cert/Cert_5_3_10_AddressQuery.py @@ -28,14 +28,11 @@ # import copy -import ipaddress -import time import unittest import command import config import ipv6 -import network_layer import node LEADER = 1 @@ -44,6 +41,7 @@ ROUTER1 = 3 DUT_ROUTER2 = 4 MED1 = 5 + class Cert_5_3_10_AddressQuery(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() @@ -86,9 +84,9 @@ class Cert_5_3_10_AddressQuery(unittest.TestCase): self.nodes[MED1].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -123,7 +121,8 @@ class Cert_5_3_10_AddressQuery(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[MED1].get_state(), 'child') - # 3 MED1: MED1 sends an ICMPv6 Echo Request to Router1 using GUA 2003:: address + # 3 MED1: MED1 sends an ICMPv6 Echo Request to Router1 using GUA 2003:: + # address router1_addr = self.nodes[ROUTER1].get_addr("2003::/64") self.assertTrue(router1_addr is not None) self.assertTrue(self.nodes[MED1].ping(router1_addr)) @@ -134,14 +133,21 @@ class Cert_5_3_10_AddressQuery(unittest.TestCase): # Verify DUT_ROUTER2 sent an Address Query Request dut_router2_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_router2_messages.next_coap_message('0.02', '/a/aq') - command.check_address_query(msg, self.nodes[DUT_ROUTER2], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + command.check_address_query( + msg, + self.nodes[DUT_ROUTER2], + config.REALM_LOCAL_ALL_ROUTERS_ADDRESS, + ) # Verify the DUT_ROUTER2 forwarded ICMPv6 Echo Request to ROUTER1 msg = dut_router2_messages.get_icmp_message(ipv6.ICMP_ECHO_REQUEST) - assert msg is not None, "Error: The DUT_ROUTER2 didn't forward ICMPv6 Echo Request to ROUTER1" + assert ( + msg is not None + ), "Error: The DUT_ROUTER2 didn't forward ICMPv6 Echo Request to ROUTER1" msg.assertSentToNode(self.nodes[ROUTER1]) - # 4 BR: BR sends an ICMPv6 Echo Request to MED1 using GUA 2003:: address + # 4 BR: BR sends an ICMPv6 Echo Request to MED1 using GUA 2003:: + # address med1_addr = self.nodes[MED1].get_addr("2003::/64") self.assertTrue(med1_addr is not None) self.assertTrue(self.nodes[BR].ping(med1_addr)) @@ -152,9 +158,12 @@ class Cert_5_3_10_AddressQuery(unittest.TestCase): # Verify DUT_ROUTER2 sent an Address Notification message dut_router2_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_router2_messages.next_coap_message('0.02', '/a/an') - command.check_address_notification(msg, self.nodes[DUT_ROUTER2], self.nodes[BR]) + command.check_address_notification( + msg, self.nodes[DUT_ROUTER2], self.nodes[BR] + ) - # 5 MED1: MED1 sends an ICMPv6 Echo Request to ROUTER1 using GUA 2003:: address + # 5 MED1: MED1 sends an ICMPv6 Echo Request to ROUTER1 using GUA 2003:: + # address addr = self.nodes[ROUTER1].get_addr("2003::/64") self.assertTrue(addr is not None) self.assertTrue(self.nodes[MED1].ping(addr)) @@ -166,14 +175,21 @@ class Cert_5_3_10_AddressQuery(unittest.TestCase): dut_router2_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) dut_router2_messages_temp = copy.deepcopy(dut_router2_messages) msg = dut_router2_messages.next_coap_message('0.02', '/a/aq', False) - assert msg is None, "Error: The DUT_ROUTER2 sent an unexpected Address Query Request" + assert ( + msg is None + ), "Error: The DUT_ROUTER2 sent an unexpected Address Query Request" # Verify DUT_ROUTER2 forwarded ICMPv6 Echo Reply to MED1 - msg = dut_router2_messages_temp.get_icmp_message(ipv6.ICMP_ECHO_RESPONSE) - assert msg is not None, "Error: The DUT_ROUTER2 didn't forward ICMPv6 Echo Reply to MED1" + msg = dut_router2_messages_temp.get_icmp_message( + ipv6.ICMP_ECHO_RESPONSE + ) + assert ( + msg is not None + ), "Error: The DUT_ROUTER2 didn't forward ICMPv6 Echo Reply to MED1" msg.assertSentToNode(self.nodes[MED1]) - # 6 DUT_ROUTER2: Power off ROUTER1 and wait 580 seconds to allow the LEADER to expire its Router ID + # 6 DUT_ROUTER2: Power off ROUTER1 and wait 580 seconds to allow the + # LEADER to expire its Router ID router1_id = self.nodes[ROUTER1].get_router_id() self.nodes[ROUTER1].stop() self.simulator.go(580) @@ -181,15 +197,21 @@ class Cert_5_3_10_AddressQuery(unittest.TestCase): # Send an ICMPv6 Echo Request from MED1 to ROUTER1 GUA 2003:: address self.assertFalse(self.nodes[MED1].ping(router1_addr)) - # Verify the DUT_ROUTER2 has removed all entries based on ROUTER1's Router ID - command.check_router_id_cached(self.nodes[DUT_ROUTER2], router1_id, False) + # Verify the DUT_ROUTER2 has removed all entries based on ROUTER1's + # Router ID + command.check_router_id_cached( + self.nodes[DUT_ROUTER2], router1_id, False + ) # Verify DUT_ROUTER2 sent an Address Query Request dut_router2_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_router2_messages.next_coap_message('0.02', '/a/aq') - msg.assertSentToDestinationAddress(config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + msg.assertSentToDestinationAddress( + config.REALM_LOCAL_ALL_ROUTERS_ADDRESS + ) - # 7 MED1: Power off MED1 and wait to allow DUT_ROUTER2 to timeout the child + # 7 MED1: Power off MED1 and wait to allow DUT_ROUTER2 to timeout the + # child self.nodes[MED1].stop() self.simulator.go(config.MLE_END_DEVICE_TIMEOUT) @@ -200,7 +222,10 @@ class Cert_5_3_10_AddressQuery(unittest.TestCase): # Verify DUT_ROUTER2 didn't generate an Address Notification message dut_router2_messages = self.simulator.get_messages_sent_by(DUT_ROUTER2) msg = dut_router2_messages.next_coap_message('0.02', '/a/an/', False) - assert msg is None, "Error: The DUT_ROUTER2 sent an unexpected Address Notification message" + assert ( + msg is None + ), "Error: The DUT_ROUTER2 sent an unexpected Address Notification message" + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_3_11_AddressQueryTimeoutIntervals.py b/tests/scripts/thread-cert/Cert_5_3_11_AddressQueryTimeoutIntervals.py index 4a9314ffd..5db66395d 100755 --- a/tests/scripts/thread-cert/Cert_5_3_11_AddressQueryTimeoutIntervals.py +++ b/tests/scripts/thread-cert/Cert_5_3_11_AddressQueryTimeoutIntervals.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import command @@ -38,13 +37,14 @@ LEADER = 1 DUT_ROUTER1 = 2 MED1 = 3 + class Cert_5_3_11_AddressQueryTimeoutIntervals(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} for i in range(1, 4): - self.nodes[i] = node.Node(i, (i == MED1), simulator = self.simulator) + self.nodes[i] = node.Node(i, (i == MED1), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) self.nodes[LEADER].set_mode('rsdn') @@ -64,9 +64,9 @@ class Cert_5_3_11_AddressQueryTimeoutIntervals(unittest.TestCase): self.nodes[MED1].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -83,7 +83,8 @@ class Cert_5_3_11_AddressQueryTimeoutIntervals(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[MED1].get_state(), 'child') - # 2 MED1: MED1 sends an ICMPv6 Echo Request to a non-existent mesh-local address X + # 2 MED1: MED1 sends an ICMPv6 Echo Request to a non-existent + # mesh-local address X X = "fdde:ad00:beef:0000:aa55:aa55:aa55:aa55" self.assertFalse(self.nodes[MED1].ping(X)) @@ -92,9 +93,14 @@ class Cert_5_3_11_AddressQueryTimeoutIntervals(unittest.TestCase): # Verify DUT_ROUTER1 sent an Address Query Request message dut_router1_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) msg = dut_router1_messages.next_coap_message('0.02', '/a/aq') - command.check_address_query(msg, self.nodes[DUT_ROUTER1], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + command.check_address_query( + msg, + self.nodes[DUT_ROUTER1], + config.REALM_LOCAL_ALL_ROUTERS_ADDRESS, + ) - # Verify DUT_ROUTER1 didn't receive an Address Query Notification message + # Verify DUT_ROUTER1 didn't receive an Address Query Notification + # message dut_router1_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) msg = dut_router1_messages.next_coap_message('0.02', '/a/an', False) self.assertTrue(msg is None) @@ -117,7 +123,12 @@ class Cert_5_3_11_AddressQueryTimeoutIntervals(unittest.TestCase): # Verify DUT_ROUTER1 sent an Address Query Request message dut_router1_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) msg = dut_router1_messages.next_coap_message('0.02', '/a/aq') - command.check_address_query(msg, self.nodes[DUT_ROUTER1], config.REALM_LOCAL_ALL_ROUTERS_ADDRESS) + command.check_address_query( + msg, + self.nodes[DUT_ROUTER1], + config.REALM_LOCAL_ALL_ROUTERS_ADDRESS, + ) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_5_01_LeaderReboot.py b/tests/scripts/thread-cert/Cert_5_5_01_LeaderReboot.py index 5ed43257d..d6bf2a51d 100755 --- a/tests/scripts/thread-cert/Cert_5_5_01_LeaderReboot.py +++ b/tests/scripts/thread-cert/Cert_5_5_01_LeaderReboot.py @@ -28,7 +28,6 @@ # import copy -import time import unittest import command @@ -39,13 +38,14 @@ import node DUT_LEADER = 1 DUT_ROUTER1 = 2 + class Cert_5_5_1_LeaderReboot(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): - self.nodes[i] = node.Node(i, simulator = self.simulator) + for i in range(1, 3): + self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[DUT_LEADER].set_panid(0xface) self.nodes[DUT_LEADER].set_mode('rsdn') @@ -53,18 +53,22 @@ class Cert_5_5_1_LeaderReboot(unittest.TestCase): self.nodes[DUT_ROUTER1].set_panid(0xface) self.nodes[DUT_ROUTER1].set_mode('rsdn') - self.nodes[DUT_ROUTER1].add_whitelist(self.nodes[DUT_LEADER].get_addr64()) + self.nodes[DUT_ROUTER1].add_whitelist( + self.nodes[DUT_LEADER].get_addr64() + ) self.nodes[DUT_ROUTER1].enable_whitelist() self.nodes[DUT_ROUTER1].set_router_selection_jitter(1) def _setUpLeader(self): - self.nodes[DUT_LEADER].add_whitelist(self.nodes[DUT_ROUTER1].get_addr64()) + self.nodes[DUT_LEADER].add_whitelist( + self.nodes[DUT_ROUTER1].get_addr64() + ) self.nodes[DUT_LEADER].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -77,7 +81,8 @@ class Cert_5_5_1_LeaderReboot(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[DUT_ROUTER1].get_state(), 'router') - # 2 DUT_LEADER, DUT_ROUTER1: Verify both DUT_LEADER and DUT_ROUTER1 send MLE Advertisement message + # 2 DUT_LEADER, DUT_ROUTER1: Verify both DUT_LEADER and DUT_ROUTER1 + # send MLE Advertisement message leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) msg = leader_messages.next_mle_message(mle.CommandType.ADVERTISEMENT) command.check_mle_advertisement(msg) @@ -87,10 +92,14 @@ class Cert_5_5_1_LeaderReboot(unittest.TestCase): command.check_mle_advertisement(msg) # Send a harness helper ping to the DUT - router1_rloc = self.nodes[DUT_ROUTER1].get_ip6_address(config.ADDRESS_TYPE.RLOC) + router1_rloc = self.nodes[DUT_ROUTER1].get_ip6_address( + config.ADDRESS_TYPE.RLOC + ) self.assertTrue(self.nodes[DUT_LEADER].ping(router1_rloc)) - leader_rloc = self.nodes[DUT_LEADER].get_ip6_address(config.ADDRESS_TYPE.RLOC) + leader_rloc = self.nodes[DUT_LEADER].get_ip6_address( + config.ADDRESS_TYPE.RLOC + ) self.assertTrue(self.nodes[DUT_ROUTER1].ping(leader_rloc)) # 3 DUT_LEADER: Reset DUT_LEADER @@ -107,7 +116,9 @@ class Cert_5_5_1_LeaderReboot(unittest.TestCase): # Verify DUT_LEADER didn't send MLE Advertisement messages leader_messages = self.simulator.get_messages_sent_by(DUT_LEADER) - msg = leader_messages.next_mle_message(mle.CommandType.ADVERTISEMENT, False) + msg = leader_messages.next_mle_message( + mle.CommandType.ADVERTISEMENT, False + ) self.assertTrue(msg is None) self.nodes[DUT_LEADER].start() @@ -122,30 +133,53 @@ class Cert_5_5_1_LeaderReboot(unittest.TestCase): leader_messages_temp = copy.deepcopy(leader_messages) msg = leader_messages.next_mle_message(mle.CommandType.LINK_REQUEST) - command.check_link_request(msg, tlv_request_address16 = command.CheckType.CONTAIN, \ - tlv_request_route64 = command.CheckType.CONTAIN) + command.check_link_request( + msg, + tlv_request_address16=command.CheckType.CONTAIN, + tlv_request_route64=command.CheckType.CONTAIN, + ) # 5 DUT_ROUTER1: Verify DUT_ROUTER1 replied with Link Accept message router1_messages = self.simulator.get_messages_sent_by(DUT_ROUTER1) router1_messages_temp = copy.deepcopy(router1_messages) msg = router1_messages.next_mle_message(mle.CommandType.LINK_ACCEPT) if msg is not None: - command.check_link_accept(msg, self.nodes[DUT_LEADER], address16 = command.CheckType.CONTAIN, \ - leader_data = command.CheckType.CONTAIN, route64 = command.CheckType.CONTAIN) + command.check_link_accept( + msg, + self.nodes[DUT_LEADER], + address16=command.CheckType.CONTAIN, + leader_data=command.CheckType.CONTAIN, + route64=command.CheckType.CONTAIN, + ) else: - msg = router1_messages_temp.next_mle_message(mle.CommandType.LINK_ACCEPT_AND_REQUEST) - self.assertTrue(msg is not None) - command.check_link_accept(msg, self.nodes[DUT_LEADER], address16 = command.CheckType.CONTAIN, \ - leader_data = command.CheckType.CONTAIN, route64 = command.CheckType.CONTAIN, \ - challenge = command.CheckType.CONTAIN) + msg = router1_messages_temp.next_mle_message( + mle.CommandType.LINK_ACCEPT_AND_REQUEST + ) + self.assertTrue(msg is not None) + command.check_link_accept( + msg, + self.nodes[DUT_LEADER], + address16=command.CheckType.CONTAIN, + leader_data=command.CheckType.CONTAIN, + route64=command.CheckType.CONTAIN, + challenge=command.CheckType.CONTAIN, + ) # 6 DUT_LEADER: Verify DUT_LEADER didn't send a Parent Request message - msg = leader_messages_temp.next_mle_message(mle.CommandType.PARENT_REQUEST, False) + msg = leader_messages_temp.next_mle_message( + mle.CommandType.PARENT_REQUEST, False + ) self.assertTrue(msg is None) - # 7 ALL: Verify connectivity by sending an ICMPv6 Echo Request from DUT_LEADER to DUT_ROUTER1 link local address - router1_link_local_address = self.nodes[DUT_ROUTER1].get_ip6_address(config.ADDRESS_TYPE.LINK_LOCAL) - self.assertTrue(self.nodes[DUT_LEADER].ping(router1_link_local_address)) + # 7 ALL: Verify connectivity by sending an ICMPv6 Echo Request from + # DUT_LEADER to DUT_ROUTER1 link local address + router1_link_local_address = self.nodes[DUT_ROUTER1].get_ip6_address( + config.ADDRESS_TYPE.LINK_LOCAL + ) + self.assertTrue( + self.nodes[DUT_LEADER].ping(router1_link_local_address) + ) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_5_02_LeaderReboot.py b/tests/scripts/thread-cert/Cert_5_5_02_LeaderReboot.py index 5e526992a..863562963 100755 --- a/tests/scripts/thread-cert/Cert_5_5_02_LeaderReboot.py +++ b/tests/scripts/thread-cert/Cert_5_5_02_LeaderReboot.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,12 +36,13 @@ LEADER = 1 ROUTER = 2 ED = 3 + class Cert_5_5_2_LeaderReboot(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -64,12 +64,12 @@ class Cert_5_5_2_LeaderReboot(unittest.TestCase): def _setUpLeader(self): self.nodes[LEADER].add_whitelist(self.nodes[ROUTER].get_addr64()) self.nodes[LEADER].enable_whitelist() - self.nodes[LEADER].set_router_selection_jitter(1) + self.nodes[LEADER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -98,5 +98,6 @@ class Cert_5_5_2_LeaderReboot(unittest.TestCase): for addr in addrs: self.assertTrue(self.nodes[ROUTER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_5_03_SplitMergeChildren.py b/tests/scripts/thread-cert/Cert_5_5_03_SplitMergeChildren.py index 2e4ecd96f..8582a5f84 100755 --- a/tests/scripts/thread-cert/Cert_5_5_03_SplitMergeChildren.py +++ b/tests/scripts/thread-cert/Cert_5_5_03_SplitMergeChildren.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -42,12 +41,13 @@ ED3 = 6 MTDS = [ED1, ED2, ED3] + class Cert_5_5_3_SplitMergeChildren(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,7): + for i in range(1, 7): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -91,9 +91,9 @@ class Cert_5_5_3_SplitMergeChildren(unittest.TestCase): self.nodes[LEADER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -142,5 +142,6 @@ class Cert_5_5_3_SplitMergeChildren(unittest.TestCase): if addr[0:4] != 'fe80': self.assertTrue(self.nodes[ROUTER2].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_5_04_SplitMergeRouters.py b/tests/scripts/thread-cert/Cert_5_5_04_SplitMergeRouters.py index c31a0d36a..e9f081ab5 100755 --- a/tests/scripts/thread-cert/Cert_5_5_04_SplitMergeRouters.py +++ b/tests/scripts/thread-cert/Cert_5_5_04_SplitMergeRouters.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -39,12 +38,13 @@ ROUTER2 = 3 ROUTER3 = 4 ROUTER4 = 5 + class Cert_5_5_4_SplitMergeRouters(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -81,12 +81,12 @@ class Cert_5_5_4_SplitMergeRouters(unittest.TestCase): self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[LEADER].add_whitelist(self.nodes[ROUTER2].get_addr64()) self.nodes[LEADER].enable_whitelist() - self.nodes[LEADER].set_router_selection_jitter(1) + self.nodes[LEADER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -124,5 +124,6 @@ class Cert_5_5_4_SplitMergeRouters(unittest.TestCase): if addr[0:4] != 'fe80': self.assertTrue(self.nodes[ROUTER3].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_5_05_SplitMergeREED.py b/tests/scripts/thread-cert/Cert_5_5_05_SplitMergeREED.py index b8f1a17c4..38e5c27c5 100755 --- a/tests/scripts/thread-cert/Cert_5_5_05_SplitMergeREED.py +++ b/tests/scripts/thread-cert/Cert_5_5_05_SplitMergeREED.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,21 +39,22 @@ ROUTER3 = 4 ROUTER15 = 16 REED1 = 17 + class Cert_5_5_5_SplitMergeREED(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,18): + for i in range(1, 18): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) self.nodes[LEADER].set_mode('rsdn') - for i in range(ROUTER2, ROUTER15+1): + for i in range(ROUTER2, ROUTER15 + 1): self.nodes[LEADER].add_whitelist(self.nodes[i].get_addr64()) self.nodes[LEADER].enable_whitelist() - for i in range(ROUTER2, ROUTER15+1): + for i in range(ROUTER2, ROUTER15 + 1): self.nodes[i].set_panid(0xface) self.nodes[i].set_mode('rsdn') self.nodes[i].add_whitelist(self.nodes[LEADER].get_addr64()) @@ -76,9 +76,9 @@ class Cert_5_5_5_SplitMergeREED(unittest.TestCase): self.nodes[REED1].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -86,7 +86,7 @@ class Cert_5_5_5_SplitMergeREED(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[LEADER].get_state(), 'leader') - for i in range(ROUTER2, ROUTER15+1): + for i in range(ROUTER2, ROUTER15 + 1): self.nodes[i].start() self.simulator.go(5) self.assertEqual(self.nodes[i].get_state(), 'router') @@ -113,5 +113,6 @@ class Cert_5_5_5_SplitMergeREED(unittest.TestCase): if addr[0:4] != 'fe80': self.assertTrue(self.nodes[ROUTER1].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_5_07_SplitMergeThreeWay.py b/tests/scripts/thread-cert/Cert_5_5_07_SplitMergeThreeWay.py index 204de9063..18c2636bc 100755 --- a/tests/scripts/thread-cert/Cert_5_5_07_SplitMergeThreeWay.py +++ b/tests/scripts/thread-cert/Cert_5_5_07_SplitMergeThreeWay.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -38,12 +37,13 @@ ROUTER1 = 2 ROUTER2 = 3 ROUTER3 = 4 + class Cert_5_5_7_SplitMergeThreeWay(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER1].set_panid(0xface) @@ -76,9 +76,9 @@ class Cert_5_5_7_SplitMergeThreeWay(unittest.TestCase): self.nodes[LEADER1].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -120,5 +120,6 @@ class Cert_5_5_7_SplitMergeThreeWay(unittest.TestCase): if addr[0:4] != 'fe80': self.assertTrue(self.nodes[ROUTER1].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_5_08_SplitRoutersLostLeader.py b/tests/scripts/thread-cert/Cert_5_5_08_SplitRoutersLostLeader.py index 24c44fde6..f5b92964e 100755 --- a/tests/scripts/thread-cert/Cert_5_5_08_SplitRoutersLostLeader.py +++ b/tests/scripts/thread-cert/Cert_5_5_08_SplitRoutersLostLeader.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -39,12 +38,13 @@ ROUTER2 = 3 ROUTER3 = 4 ED1 = 5 + class Cert_5_5_8_SplitRoutersLostLeader(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i == ED1), simulator=self.simulator) self.nodes[LEADER1].set_panid(0xface) @@ -85,9 +85,9 @@ class Cert_5_5_8_SplitRoutersLostLeader(unittest.TestCase): self.nodes[ROUTER3].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() def test(self): self.nodes[LEADER1].start() @@ -119,7 +119,7 @@ class Cert_5_5_8_SplitRoutersLostLeader(unittest.TestCase): self._setUpRouter3() self.simulator.go(140) - self.nodes[ROUTER3].start() + self.nodes[ROUTER3].start() self.simulator.go(60) addrs = self.nodes[ED1].get_addrs() @@ -127,5 +127,6 @@ class Cert_5_5_8_SplitRoutersLostLeader(unittest.TestCase): if addr[0:4] != 'fe80': self.assertTrue(self.nodes[LEADER1].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_6_01_NetworkDataRegisterBeforeAttachLeader.py b/tests/scripts/thread-cert/Cert_5_6_01_NetworkDataRegisterBeforeAttachLeader.py index 051121da1..9a261d5a8 100755 --- a/tests/scripts/thread-cert/Cert_5_6_01_NetworkDataRegisterBeforeAttachLeader.py +++ b/tests/scripts/thread-cert/Cert_5_6_01_NetworkDataRegisterBeforeAttachLeader.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,12 +39,13 @@ SED1 = 4 MTDS = [ED1, SED1] + class Cert_5_6_1_NetworkDataLeaderAsBr(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -73,9 +73,9 @@ class Cert_5_6_1_NetworkDataLeaderAsBr(unittest.TestCase): self.nodes[SED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -119,5 +119,6 @@ class Cert_5_6_1_NetworkDataLeaderAsBr(unittest.TestCase): if addr[0:10] == '2001:2:0:1' or addr[0:10] == '2001:2:0:2': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_6_02_NetworkDataRegisterBeforeAttachRouter.py b/tests/scripts/thread-cert/Cert_5_6_02_NetworkDataRegisterBeforeAttachRouter.py index 41ca4b0b7..27b1856cc 100755 --- a/tests/scripts/thread-cert/Cert_5_6_02_NetworkDataRegisterBeforeAttachRouter.py +++ b/tests/scripts/thread-cert/Cert_5_6_02_NetworkDataRegisterBeforeAttachRouter.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,12 +39,13 @@ SED1 = 4 MTDS = [ED1, SED1] + class Cert_5_6_2_NetworkDataRouterAsBr(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -73,9 +73,9 @@ class Cert_5_6_2_NetworkDataRouterAsBr(unittest.TestCase): self.nodes[SED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -117,5 +117,6 @@ class Cert_5_6_2_NetworkDataRouterAsBr(unittest.TestCase): if addr[0:10] == '2001:2:0:1' or addr[0:10] == '2001:2:0:2': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_6_03_NetworkDataRegisterAfterAttachLeader.py b/tests/scripts/thread-cert/Cert_5_6_03_NetworkDataRegisterAfterAttachLeader.py index 29652d385..e75b18276 100755 --- a/tests/scripts/thread-cert/Cert_5_6_03_NetworkDataRegisterAfterAttachLeader.py +++ b/tests/scripts/thread-cert/Cert_5_6_03_NetworkDataRegisterAfterAttachLeader.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,12 +39,13 @@ SED1 = 4 MTDS = [ED1, SED1] + class Cert_5_6_3_NetworkDataRegisterAfterAttachLeader(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -73,9 +73,9 @@ class Cert_5_6_3_NetworkDataRegisterAfterAttachLeader(unittest.TestCase): self.nodes[SED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -119,5 +119,6 @@ class Cert_5_6_3_NetworkDataRegisterAfterAttachLeader(unittest.TestCase): if addr[0:10] == '2001:2:0:1' or addr[0:10] == '2001:2:0:2': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_6_04_NetworkDataRegisterAfterAttachRouter.py b/tests/scripts/thread-cert/Cert_5_6_04_NetworkDataRegisterAfterAttachRouter.py index 93127e6c6..c6816d4f2 100755 --- a/tests/scripts/thread-cert/Cert_5_6_04_NetworkDataRegisterAfterAttachRouter.py +++ b/tests/scripts/thread-cert/Cert_5_6_04_NetworkDataRegisterAfterAttachRouter.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,12 +39,13 @@ SED1 = 4 MTDS = [ED1, SED1] + class Cert_5_6_4_NetworkDataRegisterAfterAttachRouter(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -73,9 +73,9 @@ class Cert_5_6_4_NetworkDataRegisterAfterAttachRouter(unittest.TestCase): self.nodes[SED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -119,5 +119,6 @@ class Cert_5_6_4_NetworkDataRegisterAfterAttachRouter(unittest.TestCase): if addr[0:10] == '2001:2:0:1' or addr[0:10] == '2001:2:0:2': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_6_05_NetworkDataRegisterAfterAttachRouter.py b/tests/scripts/thread-cert/Cert_5_6_05_NetworkDataRegisterAfterAttachRouter.py index f13cab085..f868a56fe 100755 --- a/tests/scripts/thread-cert/Cert_5_6_05_NetworkDataRegisterAfterAttachRouter.py +++ b/tests/scripts/thread-cert/Cert_5_6_05_NetworkDataRegisterAfterAttachRouter.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,12 +39,13 @@ SED1 = 4 MTDS = [ED1, SED1] + class Cert_5_6_5_NetworkDataRegisterAfterAttachRouter(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -73,9 +73,9 @@ class Cert_5_6_5_NetworkDataRegisterAfterAttachRouter(unittest.TestCase): self.nodes[SED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -143,5 +143,6 @@ class Cert_5_6_5_NetworkDataRegisterAfterAttachRouter(unittest.TestCase): if addr[0:3] == '200': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_6_06_NetworkDataExpiration.py b/tests/scripts/thread-cert/Cert_5_6_06_NetworkDataExpiration.py index bf1312436..340d88d34 100755 --- a/tests/scripts/thread-cert/Cert_5_6_06_NetworkDataExpiration.py +++ b/tests/scripts/thread-cert/Cert_5_6_06_NetworkDataExpiration.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,12 +39,13 @@ SED1 = 4 MTDS = [ED1, SED1] + class Cert_5_6_6_NetworkDataExpiration(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -73,9 +73,9 @@ class Cert_5_6_6_NetworkDataExpiration(unittest.TestCase): self.nodes[SED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -165,5 +165,6 @@ class Cert_5_6_6_NetworkDataExpiration(unittest.TestCase): self.nodes[ROUTER].stop() + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_6_07_NetworkDataRequestREED.py b/tests/scripts/thread-cert/Cert_5_6_07_NetworkDataRequestREED.py index 7d194bd76..03c333222 100755 --- a/tests/scripts/thread-cert/Cert_5_6_07_NetworkDataRequestREED.py +++ b/tests/scripts/thread-cert/Cert_5_6_07_NetworkDataRequestREED.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,12 +36,13 @@ LEADER = 1 ROUTER = 2 REED = 3 + class Cert_5_6_7_NetworkDataRequestREED(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -64,9 +64,9 @@ class Cert_5_6_7_NetworkDataRequestREED(unittest.TestCase): self.nodes[REED].set_router_upgrade_threshold(0) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -104,5 +104,6 @@ class Cert_5_6_7_NetworkDataRequestREED(unittest.TestCase): if addr[0:10] == '2001:2:0:3': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_6_08_ContextManagement.py b/tests/scripts/thread-cert/Cert_5_6_08_ContextManagement.py index 92ca50ecf..94f82caa4 100755 --- a/tests/scripts/thread-cert/Cert_5_6_08_ContextManagement.py +++ b/tests/scripts/thread-cert/Cert_5_6_08_ContextManagement.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,12 +36,13 @@ LEADER = 1 ROUTER = 2 ED = 3 + class Cert_5_6_8_ContextManagement(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -64,9 +64,9 @@ class Cert_5_6_8_ContextManagement(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -138,5 +138,6 @@ class Cert_5_6_8_ContextManagement(unittest.TestCase): if addr[0:3] == '200': self.assertTrue(self.nodes[ED].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_6_09_NetworkDataForwarding.py b/tests/scripts/thread-cert/Cert_5_6_09_NetworkDataForwarding.py index f7a6552e3..c907b7d00 100755 --- a/tests/scripts/thread-cert/Cert_5_6_09_NetworkDataForwarding.py +++ b/tests/scripts/thread-cert/Cert_5_6_09_NetworkDataForwarding.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -41,12 +40,13 @@ SED = 5 MTDS = [ED, SED] + class Cert_5_6_9_NetworkDataForwarding(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -81,9 +81,9 @@ class Cert_5_6_9_NetworkDataForwarding(unittest.TestCase): self.nodes[SED].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -139,5 +139,6 @@ class Cert_5_6_9_NetworkDataForwarding(unittest.TestCase): self.assertFalse(self.nodes[SED].ping('2007::1')) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_8_01_KeySynchronization.py b/tests/scripts/thread-cert/Cert_5_8_01_KeySynchronization.py index ffa5735e8..4eada6a35 100755 --- a/tests/scripts/thread-cert/Cert_5_8_01_KeySynchronization.py +++ b/tests/scripts/thread-cert/Cert_5_8_01_KeySynchronization.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,12 +35,13 @@ import node LEADER = 1 ED = 2 + class Cert_5_8_1_KeySynchronization(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -57,9 +57,9 @@ class Cert_5_8_1_KeySynchronization(unittest.TestCase): self.nodes[ED].set_key_switch_guardtime(0) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -84,5 +84,6 @@ class Cert_5_8_1_KeySynchronization(unittest.TestCase): if 'ff:fe00' not in addr: self.assertFalse(self.nodes[ED].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_8_02_KeyIncrement.py b/tests/scripts/thread-cert/Cert_5_8_02_KeyIncrement.py index cb8f2c59b..457a000a0 100755 --- a/tests/scripts/thread-cert/Cert_5_8_02_KeyIncrement.py +++ b/tests/scripts/thread-cert/Cert_5_8_02_KeyIncrement.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,12 +35,13 @@ import node LEADER = 1 ROUTER = 2 + class Cert_5_8_2_KeyIncrement(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -58,9 +58,9 @@ class Cert_5_8_2_KeyIncrement(unittest.TestCase): self.nodes[ROUTER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -83,5 +83,6 @@ class Cert_5_8_2_KeyIncrement(unittest.TestCase): for addr in addrs: self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_5_8_03_KeyIncrementRollOver.py b/tests/scripts/thread-cert/Cert_5_8_03_KeyIncrementRollOver.py index 43b180908..b97fdfdc4 100755 --- a/tests/scripts/thread-cert/Cert_5_8_03_KeyIncrementRollOver.py +++ b/tests/scripts/thread-cert/Cert_5_8_03_KeyIncrementRollOver.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,12 +35,13 @@ import node LEADER = 1 ROUTER = 2 + class Cert_5_8_3_KeyIncrementRollOver(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -59,9 +59,9 @@ class Cert_5_8_3_KeyIncrementRollOver(unittest.TestCase): self.nodes[ROUTER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -84,5 +84,6 @@ class Cert_5_8_3_KeyIncrementRollOver(unittest.TestCase): for addr in addrs: self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_1_01_RouterAttach.py b/tests/scripts/thread-cert/Cert_6_1_01_RouterAttach.py index fc179ab97..b5a85fc4e 100755 --- a/tests/scripts/thread-cert/Cert_6_1_01_RouterAttach.py +++ b/tests/scripts/thread-cert/Cert_6_1_01_RouterAttach.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,12 +36,13 @@ import node LEADER = 1 ED = 2 + class Cert_6_1_1_RouterAttach(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -56,9 +56,9 @@ class Cert_6_1_1_RouterAttach(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -108,7 +108,9 @@ class Cert_6_1_1_RouterAttach(unittest.TestCase): msg.assertMleMessageContainsOptionalTlv(mle.MleFrameCounter) # 5 - leader - msg = leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) + msg = leader_messages.next_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ) msg.assertSentToNode(self.nodes[ED]) # 6 - leader @@ -117,5 +119,6 @@ class Cert_6_1_1_RouterAttach(unittest.TestCase): if addr[0:4] != 'fe80': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_1_02_REEDAttach_MED.py b/tests/scripts/thread-cert/Cert_6_1_02_REEDAttach_MED.py index 8c07faf3b..347a4bece 100755 --- a/tests/scripts/thread-cert/Cert_6_1_02_REEDAttach_MED.py +++ b/tests/scripts/thread-cert/Cert_6_1_02_REEDAttach_MED.py @@ -41,12 +41,13 @@ LEADER = 1 REED = 2 MED = 3 + class Cert_6_1_2_REEDAttach_MED(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, (i == MED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -68,9 +69,9 @@ class Cert_6_1_2_REEDAttach_MED(unittest.TestCase): self.nodes[MED].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -98,18 +99,31 @@ class Cert_6_1_2_REEDAttach_MED(unittest.TestCase): check_parent_request(msg, is_first_request=False) # Step 6 - DUT sends Child ID Request - msg = med_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST, sent_to_node=self.nodes[REED]) - check_child_id_request(msg, address_registration=CheckType.CONTAIN, - tlv_request=CheckType.CONTAIN, mle_frame_counter=CheckType.OPTIONAL, - route64=CheckType.OPTIONAL) + msg = med_messages.next_mle_message( + mle.CommandType.CHILD_ID_REQUEST, sent_to_node=self.nodes[REED] + ) + check_child_id_request( + msg, + address_registration=CheckType.CONTAIN, + tlv_request=CheckType.CONTAIN, + mle_frame_counter=CheckType.OPTIONAL, + route64=CheckType.OPTIONAL, + ) - # Wait additional DEFAULT_CHILD_TIMEOUT to ensure the keep-alive message (child update request from MED) happens. + # Wait additional DEFAULT_CHILD_TIMEOUT to ensure the keep-alive + # message (child update request from MED) happens. self.simulator.go(config.DEFAULT_CHILD_TIMEOUT) med_messages = self.simulator.get_messages_sent_by(MED) # Step 8 - DUT sends Child Update messages - msg = med_messages.next_mle_message(mle.CommandType.CHILD_UPDATE_REQUEST) - check_child_update_request_from_child(msg, source_address=CheckType.CONTAIN, leader_data=CheckType.CONTAIN) + msg = med_messages.next_mle_message( + mle.CommandType.CHILD_UPDATE_REQUEST + ) + check_child_update_request_from_child( + msg, + source_address=CheckType.CONTAIN, + leader_data=CheckType.CONTAIN, + ) # Step 10 - Leader sends ICMPv6 echo request, to DUT link local address med_addrs = self.nodes[MED].get_addrs() @@ -117,5 +131,6 @@ class Cert_6_1_2_REEDAttach_MED(unittest.TestCase): if addr[0:4] == 'fe80': self.assertTrue(self.nodes[REED].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_1_02_REEDAttach_SED.py b/tests/scripts/thread-cert/Cert_6_1_02_REEDAttach_SED.py index 9ddedb104..b3f47e8b6 100755 --- a/tests/scripts/thread-cert/Cert_6_1_02_REEDAttach_SED.py +++ b/tests/scripts/thread-cert/Cert_6_1_02_REEDAttach_SED.py @@ -42,12 +42,13 @@ LEADER = 1 REED = 2 SED = 3 + class Cert_6_1_2_REEDAttach_SED(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, (i == SED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -69,9 +70,9 @@ class Cert_6_1_2_REEDAttach_SED(unittest.TestCase): self.nodes[SED].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -84,7 +85,7 @@ class Cert_6_1_2_REEDAttach_SED(unittest.TestCase): self.assertEqual(self.nodes[REED].get_state(), 'child') self.nodes[SED].start() - self.simulator.go(5) + self.simulator.go(5) self.assertEqual(self.nodes[SED].get_state(), 'child') self.assertEqual(self.nodes[REED].get_state(), 'router') @@ -99,10 +100,16 @@ class Cert_6_1_2_REEDAttach_SED(unittest.TestCase): check_parent_request(msg, is_first_request=False) # Step 6 - DUT sends Child ID Request - msg = sed_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST, sent_to_node=self.nodes[REED]) - check_child_id_request(msg, address_registration=CheckType.CONTAIN, - tlv_request=CheckType.CONTAIN, mle_frame_counter=CheckType.OPTIONAL, - route64=CheckType.OPTIONAL) + msg = sed_messages.next_mle_message( + mle.CommandType.CHILD_ID_REQUEST, sent_to_node=self.nodes[REED] + ) + check_child_id_request( + msg, + address_registration=CheckType.CONTAIN, + tlv_request=CheckType.CONTAIN, + mle_frame_counter=CheckType.OPTIONAL, + route64=CheckType.OPTIONAL, + ) # Wait DEFAULT_CHILD_TIMEOUT seconds, # ensure SED has received the CHILD_ID_RESPONSE, @@ -112,9 +119,14 @@ class Cert_6_1_2_REEDAttach_SED(unittest.TestCase): # Step 11 - SED sends periodic 802.15.4 Data Request messages msg = sed_messages.next_message() - self.assertEqual(False, msg.isMacAddressTypeLong()) # Extra check, keep-alive messages are of short types of mac address + self.assertEqual( + False, msg.isMacAddressTypeLong() + ) # Extra check, keep-alive messages are of short types of mac address self.assertEqual(msg.type, message.MessageType.COMMAND) - self.assertEqual(msg.mac_header.command_type, mac802154.MacHeader.CommandIdentifier.DATA_REQUEST) + self.assertEqual( + msg.mac_header.command_type, + mac802154.MacHeader.CommandIdentifier.DATA_REQUEST, + ) # Step 12 - REED sends ICMPv6 echo request, to DUT link local address sed_addrs = self.nodes[SED].get_addrs() @@ -122,5 +134,6 @@ class Cert_6_1_2_REEDAttach_SED(unittest.TestCase): if addr[0:4] == 'fe80': self.assertTrue(self.nodes[REED].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_1_03_RouterAttachConnectivity.py b/tests/scripts/thread-cert/Cert_6_1_03_RouterAttachConnectivity.py index 06566facc..f0a61eb07 100755 --- a/tests/scripts/thread-cert/Cert_6_1_03_RouterAttachConnectivity.py +++ b/tests/scripts/thread-cert/Cert_6_1_03_RouterAttachConnectivity.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -39,12 +38,13 @@ ROUTER2 = 3 ROUTER3 = 4 ED = 5 + class Cert_6_1_3_RouterAttachConnectivity(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -83,9 +83,9 @@ class Cert_6_1_3_RouterAttachConnectivity(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -111,5 +111,6 @@ class Cert_6_1_3_RouterAttachConnectivity(unittest.TestCase): for addr in addrs: self.assertTrue(self.nodes[ROUTER3].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_1_04_REEDAttachConnectivity.py b/tests/scripts/thread-cert/Cert_6_1_04_REEDAttachConnectivity.py index 8fe8eee5a..2a7a6690a 100755 --- a/tests/scripts/thread-cert/Cert_6_1_04_REEDAttachConnectivity.py +++ b/tests/scripts/thread-cert/Cert_6_1_04_REEDAttachConnectivity.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -39,12 +38,13 @@ REED0 = 3 REED1 = 4 ED = 5 + class Cert_6_1_4_REEDAttachConnectivity(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -83,9 +83,9 @@ class Cert_6_1_4_REEDAttachConnectivity(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -112,5 +112,6 @@ class Cert_6_1_4_REEDAttachConnectivity(unittest.TestCase): self.assertEqual(self.nodes[ED].get_state(), 'child') self.assertEqual(self.nodes[REED1].get_state(), 'router') + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_1_05_RouterAttachLinkQuality.py b/tests/scripts/thread-cert/Cert_6_1_05_RouterAttachLinkQuality.py index 2dc323ff9..b9b812ca1 100755 --- a/tests/scripts/thread-cert/Cert_6_1_05_RouterAttachLinkQuality.py +++ b/tests/scripts/thread-cert/Cert_6_1_05_RouterAttachLinkQuality.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -38,12 +37,13 @@ ROUTER1 = 2 ROUTER2 = 3 ED = 4 + class Cert_6_1_5_RouterAttachLinkQuality(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -62,7 +62,9 @@ class Cert_6_1_5_RouterAttachLinkQuality(unittest.TestCase): self.nodes[ROUTER2].set_panid(0xface) self.nodes[ROUTER2].set_mode('rsdn') self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64()) - self.nodes[ROUTER2].add_whitelist(self.nodes[ED].get_addr64(), rssi=-85) + self.nodes[ROUTER2].add_whitelist( + self.nodes[ED].get_addr64(), rssi=-85 + ) self.nodes[ROUTER2].enable_whitelist() self.nodes[ROUTER2].set_router_selection_jitter(1) @@ -73,9 +75,9 @@ class Cert_6_1_5_RouterAttachLinkQuality(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -95,5 +97,6 @@ class Cert_6_1_5_RouterAttachLinkQuality(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[ED].get_state(), 'child') + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_1_06_REEDAttachLinkQuality_ED.py b/tests/scripts/thread-cert/Cert_6_1_06_REEDAttachLinkQuality_ED.py index b092e389a..86e930d3c 100755 --- a/tests/scripts/thread-cert/Cert_6_1_06_REEDAttachLinkQuality_ED.py +++ b/tests/scripts/thread-cert/Cert_6_1_06_REEDAttachLinkQuality_ED.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -39,12 +38,13 @@ REED = 2 ROUTER2 = 3 ED = 4 + class Cert_6_1_6_REEDAttachLinkQuality_ED(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -63,7 +63,9 @@ class Cert_6_1_6_REEDAttachLinkQuality_ED(unittest.TestCase): self.nodes[ROUTER2].set_panid(0xface) self.nodes[ROUTER2].set_mode('rsdn') self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64()) - self.nodes[ROUTER2].add_whitelist(self.nodes[ED].get_addr64(), rssi=-85) + self.nodes[ROUTER2].add_whitelist( + self.nodes[ED].get_addr64(), rssi=-85 + ) self.nodes[ROUTER2].enable_whitelist() self.nodes[ROUTER2].set_router_selection_jitter(1) @@ -74,9 +76,9 @@ class Cert_6_1_6_REEDAttachLinkQuality_ED(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -138,7 +140,9 @@ class Cert_6_1_6_REEDAttachLinkQuality_ED(unittest.TestCase): self.assertEqual(0, scan_mask_tlv.end_device) # 4 - Router2 - msg = router2_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router2_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[ED]) # 5 - ED @@ -155,7 +159,9 @@ class Cert_6_1_6_REEDAttachLinkQuality_ED(unittest.TestCase): self.assertEqual(1, scan_mask_tlv.end_device) # 6 - REED - msg = router2_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router2_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[ED]) msg = reed_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) @@ -176,5 +182,6 @@ class Cert_6_1_6_REEDAttachLinkQuality_ED(unittest.TestCase): msg = reed_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) msg.assertSentToNode(self.nodes[ED]) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_1_06_REEDAttachLinkQuality_SED.py b/tests/scripts/thread-cert/Cert_6_1_06_REEDAttachLinkQuality_SED.py index af442575c..21dee6866 100755 --- a/tests/scripts/thread-cert/Cert_6_1_06_REEDAttachLinkQuality_SED.py +++ b/tests/scripts/thread-cert/Cert_6_1_06_REEDAttachLinkQuality_SED.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -39,12 +38,13 @@ REED = 2 ROUTER2 = 3 SED = 4 + class Cert_6_1_6_REEDAttachLinkQuality_SED(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i == SED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -63,7 +63,9 @@ class Cert_6_1_6_REEDAttachLinkQuality_SED(unittest.TestCase): self.nodes[ROUTER2].set_panid(0xface) self.nodes[ROUTER2].set_mode('rsdn') self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64()) - self.nodes[ROUTER2].add_whitelist(self.nodes[SED].get_addr64(), rssi=-85) + self.nodes[ROUTER2].add_whitelist( + self.nodes[SED].get_addr64(), rssi=-85 + ) self.nodes[ROUTER2].enable_whitelist() self.nodes[ROUTER2].set_router_selection_jitter(1) @@ -75,9 +77,9 @@ class Cert_6_1_6_REEDAttachLinkQuality_SED(unittest.TestCase): self.nodes[SED].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -139,7 +141,9 @@ class Cert_6_1_6_REEDAttachLinkQuality_SED(unittest.TestCase): self.assertEqual(0, scan_mask_tlv.end_device) # 4 - Router2 - msg = router2_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router2_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[SED]) # 5 - SED @@ -156,7 +160,9 @@ class Cert_6_1_6_REEDAttachLinkQuality_SED(unittest.TestCase): self.assertEqual(1, scan_mask_tlv.end_device) # 6 - REED - msg = router2_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) + msg = router2_messages.next_mle_message( + mle.CommandType.PARENT_RESPONSE + ) msg.assertSentToNode(self.nodes[SED]) msg = reed_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) @@ -177,5 +183,6 @@ class Cert_6_1_6_REEDAttachLinkQuality_SED(unittest.TestCase): msg = reed_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) msg.assertSentToNode(self.nodes[SED]) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_1_07_EDSynchronization.py b/tests/scripts/thread-cert/Cert_6_1_07_EDSynchronization.py index bcbbd14f5..69ea8b0d2 100755 --- a/tests/scripts/thread-cert/Cert_6_1_07_EDSynchronization.py +++ b/tests/scripts/thread-cert/Cert_6_1_07_EDSynchronization.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -39,12 +38,13 @@ ED = 3 ROUTER2 = 4 ROUTER3 = 5 + class Cert_6_1_7_EDSynchronization(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -87,9 +87,9 @@ class Cert_6_1_7_EDSynchronization(unittest.TestCase): self.nodes[ROUTER3].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -113,5 +113,6 @@ class Cert_6_1_7_EDSynchronization(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[ROUTER3].get_state(), 'router') + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_2_01_NewPartition.py b/tests/scripts/thread-cert/Cert_6_2_01_NewPartition.py index 8899626f5..631f02150 100755 --- a/tests/scripts/thread-cert/Cert_6_2_01_NewPartition.py +++ b/tests/scripts/thread-cert/Cert_6_2_01_NewPartition.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,12 +36,13 @@ LEADER = 1 ROUTER1 = 2 ED = 3 + class Cert_6_2_1_NewPartition(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -63,9 +63,9 @@ class Cert_6_2_1_NewPartition(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -90,5 +90,6 @@ class Cert_6_2_1_NewPartition(unittest.TestCase): for addr in addrs: self.assertTrue(self.nodes[ROUTER1].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_2_02_NewPartition.py b/tests/scripts/thread-cert/Cert_6_2_02_NewPartition.py index 823cfb917..c7337d1b9 100755 --- a/tests/scripts/thread-cert/Cert_6_2_02_NewPartition.py +++ b/tests/scripts/thread-cert/Cert_6_2_02_NewPartition.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -38,12 +37,13 @@ ROUTER1 = 2 ROUTER2 = 3 ED = 4 + class Cert_6_2_2_NewPartition(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -74,9 +74,9 @@ class Cert_6_2_2_NewPartition(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -106,5 +106,6 @@ class Cert_6_2_2_NewPartition(unittest.TestCase): for addr in addrs: self.assertTrue(self.nodes[ROUTER1].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_3_01_OrphanReattach.py b/tests/scripts/thread-cert/Cert_6_3_01_OrphanReattach.py index 7e4de0e5f..c3a8e6617 100755 --- a/tests/scripts/thread-cert/Cert_6_3_01_OrphanReattach.py +++ b/tests/scripts/thread-cert/Cert_6_3_01_OrphanReattach.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,12 +36,13 @@ LEADER = 1 ROUTER = 2 ED = 3 + class Cert_6_3_1_OrphanReattach(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -64,9 +64,9 @@ class Cert_6_3_1_OrphanReattach(unittest.TestCase): self.nodes[ED].set_timeout(10) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -93,5 +93,6 @@ class Cert_6_3_1_OrphanReattach(unittest.TestCase): for addr in addrs: self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_3_02_NetworkDataUpdate.py b/tests/scripts/thread-cert/Cert_6_3_02_NetworkDataUpdate.py index a2b5a69d0..d51bfa63f 100755 --- a/tests/scripts/thread-cert/Cert_6_3_02_NetworkDataUpdate.py +++ b/tests/scripts/thread-cert/Cert_6_3_02_NetworkDataUpdate.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,12 +35,13 @@ import node LEADER = 1 ED = 2 + class Cert_6_3_2_NetworkDataUpdate(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -56,9 +56,9 @@ class Cert_6_3_2_NetworkDataUpdate(unittest.TestCase): self.nodes[ED].set_timeout(10) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -106,5 +106,6 @@ class Cert_6_3_2_NetworkDataUpdate(unittest.TestCase): if addr[0:10] == '2001:2:0:1' or addr[0:10] == '2001:2:0:2': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_4_01_LinkLocal.py b/tests/scripts/thread-cert/Cert_6_4_01_LinkLocal.py index f0495820a..f759d07e9 100755 --- a/tests/scripts/thread-cert/Cert_6_4_01_LinkLocal.py +++ b/tests/scripts/thread-cert/Cert_6_4_01_LinkLocal.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,12 +35,13 @@ import node LEADER = 1 ED = 2 + class Cert_6_4_1_LinkLocal(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -55,9 +55,9 @@ class Cert_6_4_1_LinkLocal(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -78,5 +78,6 @@ class Cert_6_4_1_LinkLocal(unittest.TestCase): self.assertTrue(self.nodes[LEADER].ping('ff02::1', size=256)) self.assertTrue(self.nodes[LEADER].ping('ff02::1')) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_4_02_RealmLocal.py b/tests/scripts/thread-cert/Cert_6_4_02_RealmLocal.py index 4e7edef7c..254704ae3 100755 --- a/tests/scripts/thread-cert/Cert_6_4_02_RealmLocal.py +++ b/tests/scripts/thread-cert/Cert_6_4_02_RealmLocal.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,12 +36,13 @@ LEADER = 1 ROUTER = 2 ED = 3 + class Cert_5_3_2_RealmLocal(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -63,9 +63,9 @@ class Cert_5_3_2_RealmLocal(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -87,11 +87,22 @@ class Cert_5_3_2_RealmLocal(unittest.TestCase): self.assertTrue(self.nodes[LEADER].ping(addr, size=256)) self.assertTrue(self.nodes[LEADER].ping(addr)) - self.assertTrue(self.nodes[LEADER].ping('ff03::1', num_responses=2, size=256)) + self.assertTrue( + self.nodes[LEADER].ping('ff03::1', num_responses=2, size=256) + ) self.assertTrue(self.nodes[LEADER].ping('ff03::1', num_responses=2)) - self.assertTrue(self.nodes[LEADER].ping('ff33:0040:fdde:ad00:beef:0:0:1', num_responses=2, size=256)) - self.assertTrue(self.nodes[LEADER].ping('ff33:0040:fdde:ad00:beef:0:0:1', num_responses=2)) + self.assertTrue( + self.nodes[LEADER].ping( + 'ff33:0040:fdde:ad00:beef:0:0:1', num_responses=2, size=256 + ) + ) + self.assertTrue( + self.nodes[LEADER].ping( + 'ff33:0040:fdde:ad00:beef:0:0:1', num_responses=2 + ) + ) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_5_01_ChildResetSynchronize.py b/tests/scripts/thread-cert/Cert_6_5_01_ChildResetSynchronize.py index dac8036f0..01cc5446d 100755 --- a/tests/scripts/thread-cert/Cert_6_5_01_ChildResetSynchronize.py +++ b/tests/scripts/thread-cert/Cert_6_5_01_ChildResetSynchronize.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,12 +35,13 @@ import node LEADER = 1 ED = 2 + class Cert_6_5_1_ChildResetSynchronize(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -59,9 +59,9 @@ class Cert_6_5_1_ChildResetSynchronize(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -95,5 +95,6 @@ class Cert_6_5_1_ChildResetSynchronize(unittest.TestCase): if addr[0:4] == 'fe80': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_5_02_ChildResetReattach.py b/tests/scripts/thread-cert/Cert_6_5_02_ChildResetReattach.py index e90077768..2985fc08e 100755 --- a/tests/scripts/thread-cert/Cert_6_5_02_ChildResetReattach.py +++ b/tests/scripts/thread-cert/Cert_6_5_02_ChildResetReattach.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,12 +35,13 @@ import node LEADER = 1 ED = 2 + class Cert_6_5_2_ChildResetReattach(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -58,9 +58,9 @@ class Cert_6_5_2_ChildResetReattach(unittest.TestCase): self.nodes[ED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -90,5 +90,6 @@ class Cert_6_5_2_ChildResetReattach(unittest.TestCase): if addr[0:4] == 'fe80': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_6_01_KeyIncrement.py b/tests/scripts/thread-cert/Cert_6_6_01_KeyIncrement.py index 0fa6ae1eb..5325b66de 100755 --- a/tests/scripts/thread-cert/Cert_6_6_01_KeyIncrement.py +++ b/tests/scripts/thread-cert/Cert_6_6_01_KeyIncrement.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,12 +35,13 @@ import node LEADER = 1 ED = 2 + class Cert_6_6_1_KeyIncrement(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -57,9 +57,9 @@ class Cert_6_6_1_KeyIncrement(unittest.TestCase): self.nodes[ED].set_key_switch_guardtime(0) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -82,5 +82,6 @@ class Cert_6_6_1_KeyIncrement(unittest.TestCase): for addr in addrs: self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_6_6_02_KeyIncrementRollOver.py b/tests/scripts/thread-cert/Cert_6_6_02_KeyIncrementRollOver.py index 3b17eb6e4..72ed80a85 100755 --- a/tests/scripts/thread-cert/Cert_6_6_02_KeyIncrementRollOver.py +++ b/tests/scripts/thread-cert/Cert_6_6_02_KeyIncrementRollOver.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,12 +35,13 @@ import node LEADER = 1 ED = 2 + class Cert_6_6_2_KeyIncrement1(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -58,9 +58,9 @@ class Cert_6_6_2_KeyIncrement1(unittest.TestCase): self.nodes[ED].set_key_switch_guardtime(0) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -83,5 +83,6 @@ class Cert_6_6_2_KeyIncrement1(unittest.TestCase): for addr in addrs: self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_7_1_01_BorderRouterAsLeader.py b/tests/scripts/thread-cert/Cert_7_1_01_BorderRouterAsLeader.py index 64a6715e0..e31b06225 100755 --- a/tests/scripts/thread-cert/Cert_7_1_01_BorderRouterAsLeader.py +++ b/tests/scripts/thread-cert/Cert_7_1_01_BorderRouterAsLeader.py @@ -27,18 +27,19 @@ # POSSIBILITY OF SUCH DAMAGE. # -import functools -import time import unittest -from command import check_child_id_response, check_child_update_response, check_child_update_request_from_child, check_data_response +from command import ( + check_child_id_response, + check_child_update_response, + check_child_update_request_from_child, + check_data_response, +) from command import CheckType -from command import CommissioningDataCheck, NetworkDataCheck, PrefixesCheck, SinglePrefixCheck -from command import NetworkDataCheckType +from command import NetworkDataCheck, PrefixesCheck, SinglePrefixCheck import config import mle -import network_data import node LEADER = 1 @@ -48,12 +49,13 @@ MED1 = 4 MTDS = [SED1, MED1] + class Cert_7_1_1_BorderRouterAsLeader(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -81,9 +83,9 @@ class Cert_7_1_1_BorderRouterAsLeader(unittest.TestCase): self.nodes[MED1].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -134,49 +136,89 @@ class Cert_7_1_1_BorderRouterAsLeader(unittest.TestCase): # Step 2 - DUT creates network data msg = leader_messages.next_mle_message(mle.CommandType.DATA_RESPONSE) - check_data_response(msg, + check_data_response( + msg, network_data_check=NetworkDataCheck( - prefixes_check=PrefixesCheck(prefix_check_list=[ SinglePrefixCheck(prefix=b'2001000200000001'), SinglePrefixCheck(prefix=b'2001000200000002') ]) - ) + prefixes_check=PrefixesCheck( + prefix_check_list=[ + SinglePrefixCheck(prefix=b'2001000200000001'), + SinglePrefixCheck(prefix=b'2001000200000002'), + ] + ) + ), ) # Step 4 - DUT sends a MLE Child ID Response to Router1 - msg = leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) - check_child_id_response(msg, + msg = leader_messages.next_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ) + check_child_id_response( + msg, network_data_check=NetworkDataCheck( prefixes_check=PrefixesCheck(prefix_cnt=2) - ) + ), ) # Step 6 - DUT sends a MLE Child ID Response to SED1 - msg = leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) - check_child_id_response(msg, + msg = leader_messages.next_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ) + check_child_id_response( + msg, network_data_check=NetworkDataCheck( - prefixes_check=PrefixesCheck(prefix_check_list=[ SinglePrefixCheck(border_router_16=0xFFFE) ]) - ) + prefixes_check=PrefixesCheck( + prefix_check_list=[ + SinglePrefixCheck(border_router_16=0xfffe) + ] + ) + ), ) # For Step 10 - msg_chd_upd_res_to_sed = leader_messages.next_mle_message(mle.CommandType.CHILD_UPDATE_RESPONSE) + msg_chd_upd_res_to_sed = leader_messages.next_mle_message( + mle.CommandType.CHILD_UPDATE_RESPONSE + ) # Step 8 - DUT sends a MLE Child ID Response to MED1 - msg = leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) - check_child_id_response(msg, + msg = leader_messages.next_mle_message( + mle.CommandType.CHILD_ID_RESPONSE + ) + check_child_id_response( + msg, network_data_check=NetworkDataCheck( prefixes_check=PrefixesCheck(prefix_cnt=2) - ) + ), ) # Step 10 - DUT sends Child Update Response - msg_chd_upd_res_to_med = leader_messages.next_mle_message(mle.CommandType.CHILD_UPDATE_RESPONSE) - msg = med1_messages.next_mle_message(mle.CommandType.CHILD_UPDATE_REQUEST) - check_child_update_request_from_child(msg, address_registration=CheckType.CONTAIN, CIDs=[0, 1, 2]) + msg_chd_upd_res_to_med = leader_messages.next_mle_message( + mle.CommandType.CHILD_UPDATE_RESPONSE + ) + msg = med1_messages.next_mle_message( + mle.CommandType.CHILD_UPDATE_REQUEST + ) + check_child_update_request_from_child( + msg, address_registration=CheckType.CONTAIN, CIDs=[0, 1, 2] + ) - check_child_update_response(msg_chd_upd_res_to_med, address_registration=CheckType.CONTAIN, CIDs=[1, 2]) + check_child_update_response( + msg_chd_upd_res_to_med, + address_registration=CheckType.CONTAIN, + CIDs=[1, 2], + ) + + msg = sed1_messages.next_mle_message( + mle.CommandType.CHILD_UPDATE_REQUEST + ) + check_child_update_request_from_child( + msg, address_registration=CheckType.CONTAIN, CIDs=[0, 1] + ) + check_child_update_response( + msg_chd_upd_res_to_sed, + address_registration=CheckType.CONTAIN, + CIDs=[1], + ) - msg = sed1_messages.next_mle_message(mle.CommandType.CHILD_UPDATE_REQUEST) - check_child_update_request_from_child(msg, address_registration=CheckType.CONTAIN, CIDs=[0, 1]) - check_child_update_response(msg_chd_upd_res_to_sed, address_registration=CheckType.CONTAIN, CIDs=[1]) if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_7_1_02_BorderRouterAsRouter.py b/tests/scripts/thread-cert/Cert_7_1_02_BorderRouterAsRouter.py index d2bc9a6fc..da4518bca 100755 --- a/tests/scripts/thread-cert/Cert_7_1_02_BorderRouterAsRouter.py +++ b/tests/scripts/thread-cert/Cert_7_1_02_BorderRouterAsRouter.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,12 +39,13 @@ SED2 = 4 MTDS = [ED2, SED2] + class Cert_7_1_2_BorderRouterAsRouter(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -73,9 +73,9 @@ class Cert_7_1_2_BorderRouterAsRouter(unittest.TestCase): self.nodes[SED2].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -117,5 +117,6 @@ class Cert_7_1_2_BorderRouterAsRouter(unittest.TestCase): if addr[0:10] == '2001:2:0:1' or addr[0:10] == '2001:2:0:2': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_7_1_03_BorderRouterAsLeader.py b/tests/scripts/thread-cert/Cert_7_1_03_BorderRouterAsLeader.py index 469687faa..17333ca30 100755 --- a/tests/scripts/thread-cert/Cert_7_1_03_BorderRouterAsLeader.py +++ b/tests/scripts/thread-cert/Cert_7_1_03_BorderRouterAsLeader.py @@ -27,17 +27,19 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest -from command import check_child_update_request_from_child, check_child_update_request_from_parent, check_child_update_response, check_data_response +from command import ( + check_child_update_request_from_child, + check_child_update_request_from_parent, + check_child_update_response, + check_data_response, +) from command import CheckType from command import NetworkDataCheck, PrefixesCheck, SinglePrefixCheck -from command import NetworkDataCheckType import config import mle -import network_data import node LEADER = 1 @@ -47,12 +49,13 @@ MED1 = 4 MTDS = [SED1, MED1] + class Cert_7_1_3_BorderRouterAsLeader(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -80,9 +83,9 @@ class Cert_7_1_3_BorderRouterAsLeader(unittest.TestCase): self.nodes[MED1].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -138,40 +141,74 @@ class Cert_7_1_3_BorderRouterAsLeader(unittest.TestCase): # 3 - Leader msg = leader_messages.next_mle_message(mle.CommandType.DATA_RESPONSE) - check_data_response(msg, + check_data_response( + msg, network_data_check=NetworkDataCheck( - prefixes_check=PrefixesCheck(prefix_check_list=[ SinglePrefixCheck(b'2001000200000001'), SinglePrefixCheck(b'2001000200000002')]) - ) + prefixes_check=PrefixesCheck( + prefix_check_list=[ + SinglePrefixCheck(b'2001000200000001'), + SinglePrefixCheck(b'2001000200000002'), + ] + ) + ), ) # 4 - N/A # Get addresses registered by MED1 - msg = med1_messages.next_mle_message(mle.CommandType.CHILD_UPDATE_REQUEST) - check_child_update_request_from_child(msg, address_registration=CheckType.CONTAIN, CIDs=[0, 1, 2]) + msg = med1_messages.next_mle_message( + mle.CommandType.CHILD_UPDATE_REQUEST + ) + check_child_update_request_from_child( + msg, address_registration=CheckType.CONTAIN, CIDs=[0, 1, 2] + ) # 5 - Leader - # Make a copy of leader's messages to ensure that we don't miss messages to SED1 + # Make a copy of leader's messages to ensure that we don't miss + # messages to SED1 leader_messages_copy = leader_messages.clone() - msg = leader_messages_copy.next_mle_message(mle.CommandType.CHILD_UPDATE_RESPONSE, sent_to_node=self.nodes[MED1]) - check_child_update_response(msg, address_registration=CheckType.CONTAIN, CIDs=[1, 2]) + msg = leader_messages_copy.next_mle_message( + mle.CommandType.CHILD_UPDATE_RESPONSE, + sent_to_node=self.nodes[MED1], + ) + check_child_update_response( + msg, address_registration=CheckType.CONTAIN, CIDs=[1, 2] + ) # 6A & 6B - Leader if config.LEADER_NOTIFY_SED_BY_CHILD_UPDATE_REQUEST: - msg = leader_messages.next_mle_message(mle.CommandType.CHILD_UPDATE_REQUEST, sent_to_node=self.nodes[SED1]) - check_child_update_request_from_parent(msg, - leader_data=CheckType.CONTAIN, network_data=CheckType.CONTAIN, active_timestamp=CheckType.CONTAIN) + msg = leader_messages.next_mle_message( + mle.CommandType.CHILD_UPDATE_REQUEST, + sent_to_node=self.nodes[SED1], + ) + check_child_update_request_from_parent( + msg, + leader_data=CheckType.CONTAIN, + network_data=CheckType.CONTAIN, + active_timestamp=CheckType.CONTAIN, + ) else: - msg = leader_messages.next_mle_message(mle.CommandType.DATA_RESPONSE, sent_to_node=self.nodes[SED1]) - check_data_response(msg, network_data_check=command.NetworkDataCheck()) + msg = leader_messages.next_mle_message( + mle.CommandType.DATA_RESPONSE, sent_to_node=self.nodes[SED1] + ) + check_data_response(msg, network_data_check=NetworkDataCheck()) # 7 - N/A # Get addresses registered by SED1 - msg = sed1_messages.next_mle_message(mle.CommandType.CHILD_UPDATE_REQUEST) - check_child_update_request_from_child(msg, address_registration=CheckType.CONTAIN, CIDs=[0, 1]) + msg = sed1_messages.next_mle_message( + mle.CommandType.CHILD_UPDATE_REQUEST + ) + check_child_update_request_from_child( + msg, address_registration=CheckType.CONTAIN, CIDs=[0, 1] + ) # 8 - Leader - msg = leader_messages.next_mle_message(mle.CommandType.CHILD_UPDATE_RESPONSE, sent_to_node=self.nodes[SED1]) - check_child_update_response(msg, address_registration=CheckType.CONTAIN, CIDs=[1]) + msg = leader_messages.next_mle_message( + mle.CommandType.CHILD_UPDATE_RESPONSE, + sent_to_node=self.nodes[SED1], + ) + check_child_update_response( + msg, address_registration=CheckType.CONTAIN, CIDs=[1] + ) if __name__ == '__main__': diff --git a/tests/scripts/thread-cert/Cert_7_1_04_BorderRouterAsRouter.py b/tests/scripts/thread-cert/Cert_7_1_04_BorderRouterAsRouter.py index 67288b805..4d5205b72 100755 --- a/tests/scripts/thread-cert/Cert_7_1_04_BorderRouterAsRouter.py +++ b/tests/scripts/thread-cert/Cert_7_1_04_BorderRouterAsRouter.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,12 +39,13 @@ SED2 = 4 MTDS = [SED2, ED2] + class Cert_7_1_4_BorderRouterAsRouter(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -73,9 +73,9 @@ class Cert_7_1_4_BorderRouterAsRouter(unittest.TestCase): self.nodes[SED2].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -118,5 +118,6 @@ class Cert_7_1_4_BorderRouterAsRouter(unittest.TestCase): if addr[0:10] == '2001:2:0:1' or addr[0:10] == '2001:2:0:2': self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_7_1_05_BorderRouterAsRouter.py b/tests/scripts/thread-cert/Cert_7_1_05_BorderRouterAsRouter.py index 962ce8307..fef529939 100755 --- a/tests/scripts/thread-cert/Cert_7_1_05_BorderRouterAsRouter.py +++ b/tests/scripts/thread-cert/Cert_7_1_05_BorderRouterAsRouter.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -40,12 +39,13 @@ SED2 = 4 MTDS = [ED2, SED2] + class Cert_7_1_5_BorderRouterAsRouter(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -73,9 +73,9 @@ class Cert_7_1_5_BorderRouterAsRouter(unittest.TestCase): self.nodes[SED2].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -127,7 +127,11 @@ class Cert_7_1_5_BorderRouterAsRouter(unittest.TestCase): self.assertTrue(any('2001:2:0:2' in addr[0:10] for addr in addrs)) self.assertTrue(any('2001:2:0:3' in addr[0:10] for addr in addrs)) for addr in addrs: - if addr[0:10] == '2001:2:0:1' or addr[0:10] == '2001:2:0:2' or addr[0:10] == '2001:2:0:3': + if ( + addr[0:10] == '2001:2:0:1' + or addr[0:10] == '2001:2:0:2' + or addr[0:10] == '2001:2:0:3' + ): self.assertTrue(self.nodes[LEADER].ping(addr)) addrs = self.nodes[SED2].get_addrs() @@ -135,8 +139,13 @@ class Cert_7_1_5_BorderRouterAsRouter(unittest.TestCase): self.assertFalse(any('2001:2:0:2' in addr[0:10] for addr in addrs)) self.assertTrue(any('2001:2:0:3' in addr[0:10] for addr in addrs)) for addr in addrs: - if addr[0:10] == '2001:2:0:1' or addr[0:10] == '2001:2:0:2' or addr[0:10] == '2001:2:0:3': + if ( + addr[0:10] == '2001:2:0:1' + or addr[0:10] == '2001:2:0:2' + or addr[0:10] == '2001:2:0:3' + ): self.assertTrue(self.nodes[LEADER].ping(addr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_8_1_01_Commissioning.py b/tests/scripts/thread-cert/Cert_8_1_01_Commissioning.py index a494a8676..7a9486307 100755 --- a/tests/scripts/thread-cert/Cert_8_1_01_Commissioning.py +++ b/tests/scripts/thread-cert/Cert_8_1_01_Commissioning.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import command @@ -41,26 +40,29 @@ from command import CheckType COMMISSIONER = 1 JOINER = 2 + class Cert_8_1_01_Commissioning(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[COMMISSIONER].set_panid(0xface) self.nodes[COMMISSIONER].set_mode('rsdn') - self.nodes[COMMISSIONER].set_masterkey('00112233445566778899aabbccddeeff') + self.nodes[COMMISSIONER].set_masterkey( + '00112233445566778899aabbccddeeff' + ) self.nodes[JOINER].set_mode('rsdn') self.nodes[JOINER].set_masterkey('deadbeefdeadbeefdeadbeefdeadbeef') self.nodes[JOINER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -70,67 +72,109 @@ class Cert_8_1_01_Commissioning(unittest.TestCase): self.assertEqual(self.nodes[COMMISSIONER].get_state(), 'leader') self.nodes[COMMISSIONER].commissioner_start() self.simulator.go(3) - self.nodes[COMMISSIONER].commissioner_add_joiner(self.nodes[JOINER].get_eui64(), 'OPENTHREAD') + self.nodes[COMMISSIONER].commissioner_add_joiner( + self.nodes[JOINER].get_eui64(), 'OPENTHREAD' + ) self.nodes[JOINER].interface_up() self.nodes[JOINER].joiner_start('OPENTHREAD') self.simulator.go(10) - self.simulator.read_cert_messages_in_commissioning_log([COMMISSIONER,JOINER]) - self.assertEqual(self.nodes[JOINER].get_masterkey(), self.nodes[COMMISSIONER].get_masterkey()) + self.simulator.read_cert_messages_in_commissioning_log( + [COMMISSIONER, JOINER] + ) + self.assertEqual( + self.nodes[JOINER].get_masterkey(), + self.nodes[COMMISSIONER].get_masterkey(), + ) joiner_messages = self.simulator.get_messages_sent_by(JOINER) - commissioner_messages = self.simulator.get_messages_sent_by(COMMISSIONER) + commissioner_messages = self.simulator.get_messages_sent_by( + COMMISSIONER + ) # 2 - N/A # 3 - Joiner_1 - msg = joiner_messages.next_mle_message(mle.CommandType.DISCOVERY_REQUEST) + msg = joiner_messages.next_mle_message( + mle.CommandType.DISCOVERY_REQUEST + ) command.check_discovery_request(msg) request_src_addr = msg.mac_header.src_address # 4 - Commissioner - msg = commissioner_messages.next_mle_message(mle.CommandType.DISCOVERY_RESPONSE) - command.check_discovery_response(msg, request_src_addr, steering_data=CheckType.CONTAIN) - udp_port_set_by_commissioner = command.get_joiner_udp_port_in_discovery_response(msg) + msg = commissioner_messages.next_mle_message( + mle.CommandType.DISCOVERY_RESPONSE + ) + command.check_discovery_response( + msg, request_src_addr, steering_data=CheckType.CONTAIN + ) + udp_port_set_by_commissioner = command.get_joiner_udp_port_in_discovery_response( + msg) # 5.2 - Joiner_1 - msg = joiner_messages.next_dtls_message(dtls.ContentType.HANDSHAKE, dtls.HandshakeType.CLIENT_HELLO) + msg = joiner_messages.next_dtls_message( + dtls.ContentType.HANDSHAKE, dtls.HandshakeType.CLIENT_HELLO + ) self.assertEqual(msg.get_dst_udp_port(), udp_port_set_by_commissioner) # 5.3 - Commissioner - msg = commissioner_messages.next_dtls_message(dtls.ContentType.HANDSHAKE, dtls.HandshakeType.HELLO_VERIFY_REQUEST) + msg = commissioner_messages.next_dtls_message( + dtls.ContentType.HANDSHAKE, dtls.HandshakeType.HELLO_VERIFY_REQUEST + ) commissioner_cookie = msg.dtls.body.cookie # 5.4 - Joiner_1 - msg = joiner_messages.next_dtls_message(dtls.ContentType.HANDSHAKE, dtls.HandshakeType.CLIENT_HELLO) + msg = joiner_messages.next_dtls_message( + dtls.ContentType.HANDSHAKE, dtls.HandshakeType.CLIENT_HELLO + ) self.assertEqual(commissioner_cookie, msg.dtls.body.cookie) self.assertEqual(msg.get_dst_udp_port(), udp_port_set_by_commissioner) # 5.5 - Commissioner - commissioner_messages.next_dtls_message(dtls.ContentType.HANDSHAKE, dtls.HandshakeType.SERVER_HELLO) - commissioner_messages.next_dtls_message(dtls.ContentType.HANDSHAKE, dtls.HandshakeType.SERVER_KEY_EXCHANGE) - commissioner_messages.next_dtls_message(dtls.ContentType.HANDSHAKE, dtls.HandshakeType.SERVER_HELLO_DONE) + commissioner_messages.next_dtls_message( + dtls.ContentType.HANDSHAKE, dtls.HandshakeType.SERVER_HELLO + ) + commissioner_messages.next_dtls_message( + dtls.ContentType.HANDSHAKE, dtls.HandshakeType.SERVER_KEY_EXCHANGE + ) + commissioner_messages.next_dtls_message( + dtls.ContentType.HANDSHAKE, dtls.HandshakeType.SERVER_HELLO_DONE + ) # 5.6 - Joiner_1 - msg = joiner_messages.next_dtls_message(dtls.ContentType.HANDSHAKE, dtls.HandshakeType.CLIENT_KEY_EXCHANGE) + msg = joiner_messages.next_dtls_message( + dtls.ContentType.HANDSHAKE, dtls.HandshakeType.CLIENT_KEY_EXCHANGE + ) self.assertEqual(msg.get_dst_udp_port(), udp_port_set_by_commissioner) - msg = joiner_messages.next_dtls_message(dtls.ContentType.CHANGE_CIPHER_SPEC) + msg = joiner_messages.next_dtls_message( + dtls.ContentType.CHANGE_CIPHER_SPEC + ) self.assertEqual(msg.get_dst_udp_port(), udp_port_set_by_commissioner) - # TODO(wgtdkp): It's required to verify DTLS FINISHED message here. Currently not handled as it is encrypted. + # TODO(wgtdkp): It's required to verify DTLS FINISHED message here. + # Currently not handled as it is encrypted. # 5.7 - Commissioner - commissioner_messages.next_dtls_message(dtls.ContentType.CHANGE_CIPHER_SPEC) + commissioner_messages.next_dtls_message( + dtls.ContentType.CHANGE_CIPHER_SPEC + ) - # TODO(wgtdkp): It's required to verify DTLS FINISHED message here. Currently not handled as it is encrypted. + # TODO(wgtdkp): It's required to verify DTLS FINISHED message here. + # Currently not handled as it is encrypted. # 5.8,9,10,11 # - Joiner_1 - command.check_joiner_commissioning_messages(joiner_messages.commissioning_messages) + command.check_joiner_commissioning_messages( + joiner_messages.commissioning_messages + ) # - Commissioner - command.check_commissioner_commissioning_messages(commissioner_messages.commissioning_messages) + command.check_commissioner_commissioning_messages( + commissioner_messages.commissioning_messages + ) # As commissioner is also joiner router - command.check_joiner_router_commissioning_messages(commissioner_messages.commissioning_messages) + command.check_joiner_router_commissioning_messages( + commissioner_messages.commissioning_messages + ) self.nodes[JOINER].thread_start() self.simulator.go(5) diff --git a/tests/scripts/thread-cert/Cert_8_1_02_Commissioning.py b/tests/scripts/thread-cert/Cert_8_1_02_Commissioning.py index 019dada46..781746595 100755 --- a/tests/scripts/thread-cert/Cert_8_1_02_Commissioning.py +++ b/tests/scripts/thread-cert/Cert_8_1_02_Commissioning.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,26 +35,29 @@ import node COMMISSIONER = 1 JOINER = 2 + class Cert_8_1_02_Commissioning(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[COMMISSIONER].set_panid(0xface) self.nodes[COMMISSIONER].set_mode('rsdn') - self.nodes[COMMISSIONER].set_masterkey('deadbeefdeadbeefdeadbeefdeadbeef') + self.nodes[COMMISSIONER].set_masterkey( + 'deadbeefdeadbeefdeadbeefdeadbeef' + ) self.nodes[JOINER].set_mode('rsdn') self.nodes[JOINER].set_masterkey('00112233445566778899aabbccddeeff') self.nodes[JOINER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -65,12 +67,18 @@ class Cert_8_1_02_Commissioning(unittest.TestCase): self.assertEqual(self.nodes[COMMISSIONER].get_state(), 'leader') self.nodes[COMMISSIONER].commissioner_start() self.simulator.go(3) - self.nodes[COMMISSIONER].commissioner_add_joiner(self.nodes[JOINER].get_eui64(), 'OPENTHREAD') + self.nodes[COMMISSIONER].commissioner_add_joiner( + self.nodes[JOINER].get_eui64(), 'OPENTHREAD' + ) self.nodes[JOINER].interface_up() self.nodes[JOINER].joiner_start('DAERHTNEPO') self.simulator.go(10) - self.assertNotEqual(self.nodes[JOINER].get_masterkey(), self.nodes[COMMISSIONER].get_masterkey()) + self.assertNotEqual( + self.nodes[JOINER].get_masterkey(), + self.nodes[COMMISSIONER].get_masterkey(), + ) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_8_2_01_JoinerRouter.py b/tests/scripts/thread-cert/Cert_8_2_01_JoinerRouter.py index 8a8570083..0b4b6f5a9 100755 --- a/tests/scripts/thread-cert/Cert_8_2_01_JoinerRouter.py +++ b/tests/scripts/thread-cert/Cert_8_2_01_JoinerRouter.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,22 +36,27 @@ COMMISSIONER = 1 JOINER_ROUTER = 2 JOINER = 3 + class Cert_8_2_01_JoinerRouter(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[COMMISSIONER].set_panid(0xface) self.nodes[COMMISSIONER].set_mode('rsdn') - self.nodes[COMMISSIONER].set_masterkey('deadbeefdeadbeefdeadbeefdeadbeef') + self.nodes[COMMISSIONER].set_masterkey( + 'deadbeefdeadbeefdeadbeefdeadbeef' + ) self.nodes[COMMISSIONER].enable_whitelist() self.nodes[COMMISSIONER].set_router_selection_jitter(1) self.nodes[JOINER_ROUTER].set_mode('rsdn') - self.nodes[JOINER_ROUTER].set_masterkey('00112233445566778899aabbccddeeff') + self.nodes[JOINER_ROUTER].set_masterkey( + '00112233445566778899aabbccddeeff' + ) self.nodes[JOINER_ROUTER].enable_whitelist() self.nodes[JOINER_ROUTER].set_router_selection_jitter(1) @@ -62,9 +66,9 @@ class Cert_8_2_01_JoinerRouter(unittest.TestCase): self.nodes[JOINER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -75,37 +79,60 @@ class Cert_8_2_01_JoinerRouter(unittest.TestCase): self.nodes[COMMISSIONER].commissioner_start() self.simulator.go(5) - self.nodes[COMMISSIONER].commissioner_add_joiner(self.nodes[JOINER_ROUTER].get_eui64(), 'OPENTHREAD') - self.nodes[COMMISSIONER].commissioner_add_joiner(self.nodes[JOINER].get_eui64(), 'OPENTHREAD2') + self.nodes[COMMISSIONER].commissioner_add_joiner( + self.nodes[JOINER_ROUTER].get_eui64(), 'OPENTHREAD' + ) + self.nodes[COMMISSIONER].commissioner_add_joiner( + self.nodes[JOINER].get_eui64(), 'OPENTHREAD2' + ) self.simulator.go(5) - self.nodes[COMMISSIONER].add_whitelist(self.nodes[JOINER_ROUTER].get_joiner_id()) - self.nodes[JOINER_ROUTER].add_whitelist(self.nodes[COMMISSIONER].get_addr64()) + self.nodes[COMMISSIONER].add_whitelist( + self.nodes[JOINER_ROUTER].get_joiner_id() + ) + self.nodes[JOINER_ROUTER].add_whitelist( + self.nodes[COMMISSIONER].get_addr64() + ) self.nodes[JOINER_ROUTER].interface_up() self.nodes[JOINER_ROUTER].joiner_start('OPENTHREAD') self.simulator.go(10) - self.assertEqual(self.nodes[JOINER_ROUTER].get_masterkey(), self.nodes[COMMISSIONER].get_masterkey()) + self.assertEqual( + self.nodes[JOINER_ROUTER].get_masterkey(), + self.nodes[COMMISSIONER].get_masterkey(), + ) - self.nodes[COMMISSIONER].add_whitelist(self.nodes[JOINER_ROUTER].get_addr64()) + self.nodes[COMMISSIONER].add_whitelist( + self.nodes[JOINER_ROUTER].get_addr64() + ) self.nodes[JOINER_ROUTER].thread_start() self.simulator.go(5) self.assertEqual(self.nodes[JOINER_ROUTER].get_state(), 'router') - self.nodes[JOINER_ROUTER].add_whitelist(self.nodes[JOINER].get_joiner_id()) - self.nodes[JOINER].add_whitelist(self.nodes[JOINER_ROUTER].get_addr64()) + self.nodes[JOINER_ROUTER].add_whitelist( + self.nodes[JOINER].get_joiner_id() + ) + self.nodes[JOINER].add_whitelist( + self.nodes[JOINER_ROUTER].get_addr64() + ) self.nodes[JOINER].interface_up() self.nodes[JOINER].joiner_start('OPENTHREAD2') self.simulator.go(10) - self.assertEqual(self.nodes[JOINER].get_masterkey(), self.nodes[COMMISSIONER].get_masterkey()) + self.assertEqual( + self.nodes[JOINER].get_masterkey(), + self.nodes[COMMISSIONER].get_masterkey(), + ) - self.nodes[JOINER_ROUTER].add_whitelist(self.nodes[JOINER].get_addr64()) + self.nodes[JOINER_ROUTER].add_whitelist( + self.nodes[JOINER].get_addr64() + ) self.nodes[JOINER].thread_start() self.simulator.go(5) self.assertEqual(self.nodes[JOINER].get_state(), 'router') + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_8_2_02_JoinerRouter.py b/tests/scripts/thread-cert/Cert_8_2_02_JoinerRouter.py index 4be8d8e1b..a3851f3cf 100755 --- a/tests/scripts/thread-cert/Cert_8_2_02_JoinerRouter.py +++ b/tests/scripts/thread-cert/Cert_8_2_02_JoinerRouter.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -37,22 +36,27 @@ COMMISSIONER = 1 JOINER_ROUTER = 2 JOINER = 3 + class Cert_8_2_02_JoinerRouter(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[COMMISSIONER].set_panid(0xface) self.nodes[COMMISSIONER].set_mode('rsdn') - self.nodes[COMMISSIONER].set_masterkey('deadbeefdeadbeefdeadbeefdeadbeef') + self.nodes[COMMISSIONER].set_masterkey( + 'deadbeefdeadbeefdeadbeefdeadbeef' + ) self.nodes[COMMISSIONER].enable_whitelist() self.nodes[COMMISSIONER].set_router_selection_jitter(1) self.nodes[JOINER_ROUTER].set_mode('rsdn') - self.nodes[JOINER_ROUTER].set_masterkey('00112233445566778899aabbccddeeff') + self.nodes[JOINER_ROUTER].set_masterkey( + '00112233445566778899aabbccddeeff' + ) self.nodes[JOINER_ROUTER].enable_whitelist() self.nodes[JOINER_ROUTER].set_router_selection_jitter(1) @@ -62,9 +66,9 @@ class Cert_8_2_02_JoinerRouter(unittest.TestCase): self.nodes[JOINER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -75,31 +79,52 @@ class Cert_8_2_02_JoinerRouter(unittest.TestCase): self.nodes[COMMISSIONER].commissioner_start() self.simulator.go(5) - self.nodes[COMMISSIONER].commissioner_add_joiner(self.nodes[JOINER_ROUTER].get_eui64(), 'OPENTHREAD') - self.nodes[COMMISSIONER].commissioner_add_joiner(self.nodes[JOINER].get_eui64(), 'OPENTHREAD2') + self.nodes[COMMISSIONER].commissioner_add_joiner( + self.nodes[JOINER_ROUTER].get_eui64(), 'OPENTHREAD' + ) + self.nodes[COMMISSIONER].commissioner_add_joiner( + self.nodes[JOINER].get_eui64(), 'OPENTHREAD2' + ) self.simulator.go(5) - self.nodes[COMMISSIONER].add_whitelist(self.nodes[JOINER_ROUTER].get_joiner_id()) - self.nodes[JOINER_ROUTER].add_whitelist(self.nodes[COMMISSIONER].get_addr64()) + self.nodes[COMMISSIONER].add_whitelist( + self.nodes[JOINER_ROUTER].get_joiner_id() + ) + self.nodes[JOINER_ROUTER].add_whitelist( + self.nodes[COMMISSIONER].get_addr64() + ) self.nodes[JOINER_ROUTER].interface_up() self.nodes[JOINER_ROUTER].joiner_start('OPENTHREAD') self.simulator.go(10) - self.assertEqual(self.nodes[JOINER_ROUTER].get_masterkey(), self.nodes[COMMISSIONER].get_masterkey()) + self.assertEqual( + self.nodes[JOINER_ROUTER].get_masterkey(), + self.nodes[COMMISSIONER].get_masterkey(), + ) - self.nodes[COMMISSIONER].add_whitelist(self.nodes[JOINER_ROUTER].get_addr64()) + self.nodes[COMMISSIONER].add_whitelist( + self.nodes[JOINER_ROUTER].get_addr64() + ) self.nodes[JOINER_ROUTER].thread_start() self.simulator.go(5) self.assertEqual(self.nodes[JOINER_ROUTER].get_state(), 'router') - self.nodes[JOINER_ROUTER].add_whitelist(self.nodes[JOINER].get_joiner_id()) - self.nodes[JOINER].add_whitelist(self.nodes[JOINER_ROUTER].get_addr64()) + self.nodes[JOINER_ROUTER].add_whitelist( + self.nodes[JOINER].get_joiner_id() + ) + self.nodes[JOINER].add_whitelist( + self.nodes[JOINER_ROUTER].get_addr64() + ) self.nodes[JOINER].interface_up() self.nodes[JOINER].joiner_start('2DAERHTNEPO') self.simulator.go(10) - self.assertNotEqual(self.nodes[JOINER].get_masterkey(), self.nodes[COMMISSIONER].get_masterkey()) + self.assertNotEqual( + self.nodes[JOINER].get_masterkey(), + self.nodes[COMMISSIONER].get_masterkey(), + ) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_02_MGMTCommissionerSet.py b/tests/scripts/thread-cert/Cert_9_2_02_MGMTCommissionerSet.py index 5ab114699..2d7b19c28 100755 --- a/tests/scripts/thread-cert/Cert_9_2_02_MGMTCommissionerSet.py +++ b/tests/scripts/thread-cert/Cert_9_2_02_MGMTCommissionerSet.py @@ -30,8 +30,6 @@ from ipaddress import ip_address import unittest -from mle import NetworkData -from network_data import CommissioningData import command import config import mesh_cop @@ -43,12 +41,11 @@ LEADER = 2 class Cert_9_2_02_MGMTCommissionerSet(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[COMMISSIONER].set_panid(0xface) @@ -64,9 +61,9 @@ class Cert_9_2_02_MGMTCommissionerSet(unittest.TestCase): self.nodes[LEADER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -85,83 +82,142 @@ class Cert_9_2_02_MGMTCommissionerSet(unittest.TestCase): # Commissioner start self.nodes[COMMISSIONER].commissioner_start() self.simulator.go(3) - self.simulator.get_messages_sent_by(COMMISSIONER) # Skip LEAD_PET.req + self.simulator.get_messages_sent_by(COMMISSIONER) # Skip LEAD_PET.req # Get CommissionerSesssionId from LEAD_PET.rsp leader_messages = self.simulator.get_messages_sent_by(LEADER) msg = leader_messages.next_coap_message('2.04', assert_enabled=True) - commissioner_session_id_tlv = command.get_sub_tlv(msg.coap.payload, mesh_cop.CommissionerSessionId) + commissioner_session_id_tlv = command.get_sub_tlv( + msg.coap.payload, mesh_cop.CommissionerSessionId + ) - # Step 2 - Harness instructs commissioner to send MGMT_COMMISSIONER_SET.req to Leader - steering_data_tlv = mesh_cop.SteeringData(bytes([0xFF])) - self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs([steering_data_tlv]) + # Step 2 - Harness instructs commissioner to send + # MGMT_COMMISSIONER_SET.req to Leader + steering_data_tlv = mesh_cop.SteeringData(bytes([0xff])) + self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs( + [steering_data_tlv] + ) self.simulator.go(5) - # Step 3 - Leader responds to MGMT_COMMISSIONER_SET.req with MGMT_COMMISSIONER_SET.rsp + # Step 3 - Leader responds to MGMT_COMMISSIONER_SET.req with + # MGMT_COMMISSIONER_SET.rsp leader_messages = self.simulator.get_messages_sent_by(LEADER) msg = leader_messages.next_coap_message('2.04') - command.check_coap_message(msg, [mesh_cop.State(mesh_cop.MeshCopState.REJECT)]) # (mesh_cop.State(mesh_cop.MeshCopState.REJECT),) <- this a tuple, don't delete the comma - self.simulator.get_messages_sent_by(COMMISSIONER) # Skip LEAD_PET.req + # (mesh_cop.State(mesh_cop.MeshCopState.REJECT),) <- this a tuple, don't delete the comma + command.check_coap_message( + msg, [mesh_cop.State(mesh_cop.MeshCopState.REJECT)] + ) + self.simulator.get_messages_sent_by(COMMISSIONER) # Skip LEAD_PET.req - # Step 4 - Harness instructs commissioner to send MGMT_COMMISSIONER_SET.req to Leader - self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs([steering_data_tlv, commissioner_session_id_tlv]) + # Step 4 - Harness instructs commissioner to send + # MGMT_COMMISSIONER_SET.req to Leader + self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs( + [steering_data_tlv, commissioner_session_id_tlv] + ) self.simulator.go(5) - commissioner_messages = self.simulator.get_messages_sent_by(COMMISSIONER) + commissioner_messages = self.simulator.get_messages_sent_by( + COMMISSIONER + ) msg = commissioner_messages.next_coap_message('0.02', uri_path='/c/cs') rloc = ip_address(self.nodes[LEADER].get_addr_rloc()) leader_aloc = ip_address(self.nodes[LEADER].get_addr_leader_aloc()) - command.check_coap_message(msg, [steering_data_tlv, commissioner_session_id_tlv], dest_addrs=[rloc, leader_aloc]) + command.check_coap_message( + msg, + [steering_data_tlv, commissioner_session_id_tlv], + dest_addrs=[rloc, leader_aloc], + ) # Step 5 - Leader sends MGMT_COMMISSIONER_SET.rsp to commissioner leader_messages = self.simulator.get_messages_sent_by(LEADER) msg = leader_messages.next_coap_message('2.04') - command.check_coap_message(msg, [mesh_cop.State(mesh_cop.MeshCopState.ACCEPT)]) + command.check_coap_message( + msg, [mesh_cop.State(mesh_cop.MeshCopState.ACCEPT)] + ) # Step 6 - Leader sends a multicast MLE Data Response msg = leader_messages.next_mle_message(mle.CommandType.DATA_RESPONSE) - command.check_data_response(msg, command.NetworkDataCheck( - commissioning_data_check=command.CommissioningDataCheck(stable=0, sub_tlv_type_list=[mesh_cop.CommissionerSessionId, mesh_cop.SteeringData, mesh_cop.BorderAgentLocator]))) + command.check_data_response( + msg, + command.NetworkDataCheck( + commissioning_data_check=command.CommissioningDataCheck( + stable=0, + sub_tlv_type_list=[ + mesh_cop.CommissionerSessionId, + mesh_cop.SteeringData, + mesh_cop.BorderAgentLocator, + ], + ) + ), + ) - # Step 7 - Harness instructs commissioner to send MGMT_COMMISSIONER_SET.req to Leader + # Step 7 - Harness instructs commissioner to send + # MGMT_COMMISSIONER_SET.req to Leader border_agent_locator_tlv = mesh_cop.BorderAgentLocator(0x0400) self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs( - [commissioner_session_id_tlv, border_agent_locator_tlv]) + [commissioner_session_id_tlv, border_agent_locator_tlv] + ) self.simulator.go(5) - # Step 8 - Leader responds to MGMT_COMMISSIONER_SET.req with MGMT_COMMISSIONER_SET.rsp + # Step 8 - Leader responds to MGMT_COMMISSIONER_SET.req with + # MGMT_COMMISSIONER_SET.rsp leader_messages = self.simulator.get_messages_sent_by(LEADER) msg = leader_messages.next_coap_message('2.04') - command.check_coap_message(msg, [mesh_cop.State(mesh_cop.MeshCopState.REJECT)]) + command.check_coap_message( + msg, [mesh_cop.State(mesh_cop.MeshCopState.REJECT)] + ) - # Step 9 - Harness instructs commissioner to send MGMT_COMMISSIONER_SET.req to Leader + # Step 9 - Harness instructs commissioner to send + # MGMT_COMMISSIONER_SET.req to Leader self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs( - [steering_data_tlv, commissioner_session_id_tlv, border_agent_locator_tlv]) + [ + steering_data_tlv, + commissioner_session_id_tlv, + border_agent_locator_tlv, + ] + ) self.simulator.go(5) - # Step 10 - Leader responds to MGMT_COMMISSIONER_SET.req with MGMT_COMMISSIONER_SET.rsp + # Step 10 - Leader responds to MGMT_COMMISSIONER_SET.req with + # MGMT_COMMISSIONER_SET.rsp leader_messages = self.simulator.get_messages_sent_by(LEADER) msg = leader_messages.next_coap_message('2.04') - command.check_coap_message(msg, [mesh_cop.State(mesh_cop.MeshCopState.REJECT)]) + command.check_coap_message( + msg, [mesh_cop.State(mesh_cop.MeshCopState.REJECT)] + ) - # Step 11 - Harness instructs commissioner to send MGMT_COMMISSIONER_SET.req to Leader + # Step 11 - Harness instructs commissioner to send + # MGMT_COMMISSIONER_SET.req to Leader self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs( - [mesh_cop.CommissionerSessionId(0xFFFF), steering_data_tlv]) + [mesh_cop.CommissionerSessionId(0xffff), steering_data_tlv] + ) self.simulator.go(5) - # Step 12 - Leader responds to MGMT_COMMISSIONER_SET.req with MGMT_COMMISSIONER_SET.rsp + # Step 12 - Leader responds to MGMT_COMMISSIONER_SET.req with + # MGMT_COMMISSIONER_SET.rsp leader_messages = self.simulator.get_messages_sent_by(LEADER) msg = leader_messages.next_coap_message('2.04') - command.check_coap_message(msg, [mesh_cop.State(mesh_cop.MeshCopState.REJECT)]) + command.check_coap_message( + msg, [mesh_cop.State(mesh_cop.MeshCopState.REJECT)] + ) - # Step 13 - Harness instructs commissioner to send MGMT_COMMISSIONER_SET.req to Leader + # Step 13 - Harness instructs commissioner to send + # MGMT_COMMISSIONER_SET.req to Leader self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs( - [commissioner_session_id_tlv, steering_data_tlv, mesh_cop.Channel(0x0, 0x0)]) + [ + commissioner_session_id_tlv, + steering_data_tlv, + mesh_cop.Channel(0x0, 0x0), + ] + ) self.simulator.go(5) - # Step 14 - Leader responds to MGMT_COMMISSIONER_SET.req with MGMT_COMMISSIONER_SET.rsp + # Step 14 - Leader responds to MGMT_COMMISSIONER_SET.req with + # MGMT_COMMISSIONER_SET.rsp leader_messages = self.simulator.get_messages_sent_by(LEADER) msg = leader_messages.next_coap_message('2.04') - command.check_coap_message(msg, [mesh_cop.State(mesh_cop.MeshCopState.ACCEPT)]) + command.check_coap_message( + msg, [mesh_cop.State(mesh_cop.MeshCopState.ACCEPT)] + ) # Step 15 - Send ICMPv6 Echo Request to Leader leader_rloc = self.nodes[LEADER].get_addr_rloc() diff --git a/tests/scripts/thread-cert/Cert_9_2_04_ActiveDataset.py b/tests/scripts/thread-cert/Cert_9_2_04_ActiveDataset.py index b1a2c0d6f..99245685b 100755 --- a/tests/scripts/thread-cert/Cert_9_2_04_ActiveDataset.py +++ b/tests/scripts/thread-cert/Cert_9_2_04_ActiveDataset.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -36,26 +35,31 @@ import node COMMISSIONER = 1 LEADER = 2 + class Cert_9_2_04_ActiveDataset(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i, simulator=self.simulator) - self.nodes[COMMISSIONER].set_active_dataset(10, panid=0xface, master_key='000102030405060708090a0b0c0d0e0f') + self.nodes[COMMISSIONER].set_active_dataset( + 10, panid=0xface, master_key='000102030405060708090a0b0c0d0e0f' + ) self.nodes[COMMISSIONER].set_mode('rsdn') self.nodes[COMMISSIONER].set_router_selection_jitter(1) - self.nodes[LEADER].set_active_dataset(10, panid=0xface, master_key='000102030405060708090a0b0c0d0e0f') + self.nodes[LEADER].set_active_dataset( + 10, panid=0xface, master_key='000102030405060708090a0b0c0d0e0f' + ) self.nodes[LEADER].set_mode('rsdn') self.nodes[LEADER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -70,92 +74,110 @@ class Cert_9_2_04_ActiveDataset(unittest.TestCase): self.nodes[COMMISSIONER].commissioner_start() self.simulator.go(3) - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=101, - channel_mask=0x001fffe0, - extended_panid='000db70000000000', - network_name='GRL') + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=101, + channel_mask=0x001fffe0, + extended_panid='000db70000000000', + network_name='GRL', + ) self.simulator.go(3) self.assertEqual(self.nodes[LEADER].get_network_name(), 'GRL') # Step 6 # Attempt to set Channel TLV - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=102, - channel=18, - channel_mask=0x001fffe0, - extended_panid='000db70000000001', - network_name='threadcert') + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=102, + channel=18, + channel_mask=0x001fffe0, + extended_panid='000db70000000001', + network_name='threadcert', + ) self.simulator.go(3) self.assertEqual(self.nodes[LEADER].get_network_name(), 'GRL') # Step 8 # Attempt to set Mesh Local Prefix TLV - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=103, - channel_mask=0x001ffee0, - extended_panid='000db70000000000', - mesh_local='fd00:0db7::', - network_name='UL') + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=103, + channel_mask=0x001ffee0, + extended_panid='000db70000000000', + mesh_local='fd00:0db7::', + network_name='UL', + ) self.simulator.go(3) self.assertEqual(self.nodes[LEADER].get_network_name(), 'GRL') # Step 10 # Attempt to set Network Master Key TLV - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=104, - channel_mask=0x001fffe0, - extended_panid='000db70000000000', - master_key='00112233445566778899aabbccddeeff', - mesh_local='fd00:0db7::', - network_name='UL') + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=104, + channel_mask=0x001fffe0, + extended_panid='000db70000000000', + master_key='00112233445566778899aabbccddeeff', + mesh_local='fd00:0db7::', + network_name='UL', + ) self.simulator.go(3) self.assertEqual(self.nodes[LEADER].get_network_name(), 'GRL') # Step 12 # Attempt to set PAN ID TLV - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=105, - channel_mask=0x001fffe0, - extended_panid='000db70000000000', - master_key='00112233445566778899aabbccddeeff', - mesh_local='fd00:0db7::', - network_name='UL', - panid=0xafce) + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=105, + channel_mask=0x001fffe0, + extended_panid='000db70000000000', + master_key='00112233445566778899aabbccddeeff', + mesh_local='fd00:0db7::', + network_name='UL', + panid=0xafce, + ) self.simulator.go(3) self.assertEqual(self.nodes[LEADER].get_network_name(), 'GRL') # Step 14 # Invalid Commissioner Session ID - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=106, - channel_mask=0x001fffe0, - extended_panid='000db70000000000', - network_name='UL', - binary='0b02abcd') + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=106, + channel_mask=0x001fffe0, + extended_panid='000db70000000000', + network_name='UL', + binary='0b02abcd', + ) self.simulator.go(3) self.assertEqual(self.nodes[LEADER].get_network_name(), 'GRL') # Step 16 # Old Active Timestamp - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=101, - channel_mask=0x001fffe0, - extended_panid='000db70000000000', - network_name='UL') + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=101, + channel_mask=0x001fffe0, + extended_panid='000db70000000000', + network_name='UL', + ) self.simulator.go(3) self.assertEqual(self.nodes[LEADER].get_network_name(), 'GRL') # Step 18 # Unexpected Steering Data TLV - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=107, - channel_mask=0x001fffe0, - extended_panid='000db70000000000', - network_name='UL', - binary='0806113320440000') + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=107, + channel_mask=0x001fffe0, + extended_panid='000db70000000000', + network_name='UL', + binary='0806113320440000', + ) self.simulator.go(3) self.assertEqual(self.nodes[LEADER].get_network_name(), 'UL') # Step 20 # Undefined TLV - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=108, - channel_mask=0x001fffe0, - extended_panid='000db70000000000', - network_name='GRL', - binary='8202aa55') + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=108, + channel_mask=0x001fffe0, + extended_panid='000db70000000000', + network_name='GRL', + binary='8202aa55', + ) self.simulator.go(3) self.assertEqual(self.nodes[LEADER].get_network_name(), 'GRL') @@ -163,5 +185,6 @@ class Cert_9_2_04_ActiveDataset(unittest.TestCase): for ipaddr in ipaddrs: self.assertTrue(self.nodes[LEADER].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_07_DelayTimer.py b/tests/scripts/thread-cert/Cert_9_2_07_DelayTimer.py index bfc9fb000..9a028a58f 100755 --- a/tests/scripts/thread-cert/Cert_9_2_07_DelayTimer.py +++ b/tests/scripts/thread-cert/Cert_9_2_07_DelayTimer.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -47,12 +46,13 @@ ROUTER_PENDING_ACTIVE_TIMESTAMP = 25 COMMISSIONER_PENDING_CHANNEL = 20 COMMISSIONER_PENDING_PANID = 0xafce + class Cert_9_2_7_DelayTimer(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[COMMISSIONER].set_active_dataset(LEADER_ACTIVE_TIMESTAMP) @@ -70,7 +70,9 @@ class Cert_9_2_7_DelayTimer(unittest.TestCase): self.nodes[LEADER].set_router_selection_jitter(1) self.nodes[ROUTER].set_active_dataset(ROUTER_ACTIVE_TIMESTAMP) - self.nodes[ROUTER].set_pending_dataset(ROUTER_PENDING_TIMESTAMP, ROUTER_PENDING_ACTIVE_TIMESTAMP) + self.nodes[ROUTER].set_pending_dataset( + ROUTER_PENDING_TIMESTAMP, ROUTER_PENDING_ACTIVE_TIMESTAMP + ) self.nodes[ROUTER].set_mode('rsdn') self.nodes[ROUTER].set_panid(PANID_INIT) self.nodes[ROUTER].set_partition_id(0x1) @@ -78,9 +80,9 @@ class Cert_9_2_7_DelayTimer(unittest.TestCase): self.nodes[ROUTER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -112,19 +114,34 @@ class Cert_9_2_7_DelayTimer(unittest.TestCase): break self.assertTrue(self.nodes[LEADER].ping(ipaddr)) - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=40, - active_timestamp=80, - delay_timer=10000, - channel=COMMISSIONER_PENDING_CHANNEL, - panid=COMMISSIONER_PENDING_PANID) + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=40, + active_timestamp=80, + delay_timer=10000, + channel=COMMISSIONER_PENDING_CHANNEL, + panid=COMMISSIONER_PENDING_PANID, + ) self.simulator.go(40) - self.assertEqual(self.nodes[LEADER].get_panid(), COMMISSIONER_PENDING_PANID) - self.assertEqual(self.nodes[COMMISSIONER].get_panid(), COMMISSIONER_PENDING_PANID) - self.assertEqual(self.nodes[ROUTER].get_panid(), COMMISSIONER_PENDING_PANID) + self.assertEqual( + self.nodes[LEADER].get_panid(), COMMISSIONER_PENDING_PANID + ) + self.assertEqual( + self.nodes[COMMISSIONER].get_panid(), COMMISSIONER_PENDING_PANID + ) + self.assertEqual( + self.nodes[ROUTER].get_panid(), COMMISSIONER_PENDING_PANID + ) - self.assertEqual(self.nodes[LEADER].get_channel(), COMMISSIONER_PENDING_CHANNEL) - self.assertEqual(self.nodes[COMMISSIONER].get_channel(), COMMISSIONER_PENDING_CHANNEL) - self.assertEqual(self.nodes[ROUTER].get_channel(), COMMISSIONER_PENDING_CHANNEL) + self.assertEqual( + self.nodes[LEADER].get_channel(), COMMISSIONER_PENDING_CHANNEL + ) + self.assertEqual( + self.nodes[COMMISSIONER].get_channel(), + COMMISSIONER_PENDING_CHANNEL, + ) + self.assertEqual( + self.nodes[ROUTER].get_channel(), COMMISSIONER_PENDING_CHANNEL + ) ipaddrs = self.nodes[ROUTER].get_addrs() for ipaddr in ipaddrs: @@ -132,5 +149,6 @@ class Cert_9_2_7_DelayTimer(unittest.TestCase): break self.assertTrue(self.nodes[LEADER].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_08_PersistentDatasets.py b/tests/scripts/thread-cert/Cert_9_2_08_PersistentDatasets.py index f07e8bff1..80591c02a 100755 --- a/tests/scripts/thread-cert/Cert_9_2_08_PersistentDatasets.py +++ b/tests/scripts/thread-cert/Cert_9_2_08_PersistentDatasets.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -48,21 +47,26 @@ COMMISSIONER_PENDING_PANID = 0xafce MTDS = [ED, SED] + class Cert_9_2_8_PersistentDatasets(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) - self.nodes[COMMISSIONER].set_active_dataset(LEADER_ACTIVE_TIMESTAMP, panid=PANID_INIT, channel=CHANNEL_INIT) + self.nodes[COMMISSIONER].set_active_dataset( + LEADER_ACTIVE_TIMESTAMP, panid=PANID_INIT, channel=CHANNEL_INIT + ) self.nodes[COMMISSIONER].set_mode('rsdn') self.nodes[COMMISSIONER].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[COMMISSIONER].enable_whitelist() self.nodes[COMMISSIONER].set_router_selection_jitter(1) - self.nodes[LEADER].set_active_dataset(LEADER_ACTIVE_TIMESTAMP, panid=PANID_INIT, channel=CHANNEL_INIT) + self.nodes[LEADER].set_active_dataset( + LEADER_ACTIVE_TIMESTAMP, panid=PANID_INIT, channel=CHANNEL_INIT + ) self.nodes[LEADER].set_mode('rsdn') self.nodes[LEADER].add_whitelist(self.nodes[COMMISSIONER].get_addr64()) self.nodes[LEADER].add_whitelist(self.nodes[ROUTER].get_addr64()) @@ -70,7 +74,9 @@ class Cert_9_2_8_PersistentDatasets(unittest.TestCase): self.nodes[LEADER].add_whitelist(self.nodes[SED].get_addr64()) self.nodes[LEADER].enable_whitelist() - self.nodes[ROUTER].set_active_dataset(LEADER_ACTIVE_TIMESTAMP, panid=PANID_INIT, channel=CHANNEL_INIT) + self.nodes[ROUTER].set_active_dataset( + LEADER_ACTIVE_TIMESTAMP, panid=PANID_INIT, channel=CHANNEL_INIT + ) self.nodes[ROUTER].set_mode('rsdn') self._setUpRouter() @@ -100,9 +106,9 @@ class Cert_9_2_8_PersistentDatasets(unittest.TestCase): self.nodes[SED].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() def test(self): self.nodes[LEADER].start() @@ -128,11 +134,13 @@ class Cert_9_2_8_PersistentDatasets(unittest.TestCase): self.nodes[COMMISSIONER].commissioner_start() self.simulator.go(3) - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=10, - active_timestamp=70, - delay_timer=60000, - channel=COMMISSIONER_PENDING_CHANNEL, - panid=COMMISSIONER_PENDING_PANID) + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=10, + active_timestamp=70, + delay_timer=60000, + channel=COMMISSIONER_PENDING_CHANNEL, + panid=COMMISSIONER_PENDING_PANID, + ) self.simulator.go(5) self.nodes[ROUTER].reset() @@ -141,13 +149,23 @@ class Cert_9_2_8_PersistentDatasets(unittest.TestCase): self.simulator.go(60) - self.assertEqual(self.nodes[LEADER].get_panid(), COMMISSIONER_PENDING_PANID) - self.assertEqual(self.nodes[COMMISSIONER].get_panid(), COMMISSIONER_PENDING_PANID) + self.assertEqual( + self.nodes[LEADER].get_panid(), COMMISSIONER_PENDING_PANID + ) + self.assertEqual( + self.nodes[COMMISSIONER].get_panid(), COMMISSIONER_PENDING_PANID + ) - self.assertEqual(self.nodes[LEADER].get_channel(), COMMISSIONER_PENDING_CHANNEL) - self.assertEqual(self.nodes[COMMISSIONER].get_channel(), COMMISSIONER_PENDING_CHANNEL) - - # reset the devices here again to simulate the fact that the devices were disabled the entire time + self.assertEqual( + self.nodes[LEADER].get_channel(), COMMISSIONER_PENDING_CHANNEL + ) + self.assertEqual( + self.nodes[COMMISSIONER].get_channel(), + COMMISSIONER_PENDING_CHANNEL, + ) + + # reset the devices here again to simulate the fact that the devices + # were disabled the entire time self.nodes[ROUTER].reset() self._setUpRouter() self.nodes[ROUTER].start() @@ -168,13 +186,25 @@ class Cert_9_2_8_PersistentDatasets(unittest.TestCase): self.simulator.go(10) - self.assertEqual(self.nodes[ROUTER].get_panid(), COMMISSIONER_PENDING_PANID) - self.assertEqual(self.nodes[ED].get_panid(), COMMISSIONER_PENDING_PANID) - self.assertEqual(self.nodes[SED].get_panid(), COMMISSIONER_PENDING_PANID) + self.assertEqual( + self.nodes[ROUTER].get_panid(), COMMISSIONER_PENDING_PANID + ) + self.assertEqual( + self.nodes[ED].get_panid(), COMMISSIONER_PENDING_PANID + ) + self.assertEqual( + self.nodes[SED].get_panid(), COMMISSIONER_PENDING_PANID + ) - self.assertEqual(self.nodes[ROUTER].get_channel(), COMMISSIONER_PENDING_CHANNEL) - self.assertEqual(self.nodes[ED].get_channel(), COMMISSIONER_PENDING_CHANNEL) - self.assertEqual(self.nodes[SED].get_channel(), COMMISSIONER_PENDING_CHANNEL) + self.assertEqual( + self.nodes[ROUTER].get_channel(), COMMISSIONER_PENDING_CHANNEL + ) + self.assertEqual( + self.nodes[ED].get_channel(), COMMISSIONER_PENDING_CHANNEL + ) + self.assertEqual( + self.nodes[SED].get_channel(), COMMISSIONER_PENDING_CHANNEL + ) self.simulator.go(5) @@ -182,7 +212,7 @@ class Cert_9_2_8_PersistentDatasets(unittest.TestCase): for ipaddr in ipaddrs: if ipaddr[0:4] != 'fe80': self.assertTrue(self.nodes[LEADER].ping(ipaddr)) - + ipaddrs = self.nodes[ED].get_addrs() for ipaddr in ipaddrs: if ipaddr[0:4] != 'fe80': @@ -193,5 +223,6 @@ class Cert_9_2_8_PersistentDatasets(unittest.TestCase): if ipaddr[0:4] != 'fe80': self.assertTrue(self.nodes[LEADER].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_09_PendingPartition.py b/tests/scripts/thread-cert/Cert_9_2_09_PendingPartition.py index a5736635e..0b444a42b 100755 --- a/tests/scripts/thread-cert/Cert_9_2_09_PendingPartition.py +++ b/tests/scripts/thread-cert/Cert_9_2_09_PendingPartition.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -44,21 +43,26 @@ LEADER = 2 ROUTER1 = 3 ROUTER2 = 4 + class Cert_9_2_09_PendingPartition(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, simulator=self.simulator) - self.nodes[COMMISSIONER].set_active_dataset(10, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[COMMISSIONER].set_active_dataset( + 10, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[COMMISSIONER].set_mode('rsdn') self.nodes[COMMISSIONER].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[COMMISSIONER].enable_whitelist() self.nodes[COMMISSIONER].set_router_selection_jitter(1) - self.nodes[LEADER].set_active_dataset(10, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[LEADER].set_active_dataset( + 10, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[LEADER].set_mode('rsdn') self.nodes[LEADER].set_partition_id(0xffffffff) self.nodes[LEADER].add_whitelist(self.nodes[COMMISSIONER].get_addr64()) @@ -66,14 +70,18 @@ class Cert_9_2_09_PendingPartition(unittest.TestCase): self.nodes[LEADER].enable_whitelist() self.nodes[LEADER].set_router_selection_jitter(1) - self.nodes[ROUTER1].set_active_dataset(10, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[ROUTER1].set_active_dataset( + 10, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[ROUTER1].set_mode('rsdn') self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[ROUTER1].add_whitelist(self.nodes[ROUTER2].get_addr64()) self.nodes[ROUTER1].enable_whitelist() self.nodes[ROUTER1].set_router_selection_jitter(1) - self.nodes[ROUTER2].set_active_dataset(10, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[ROUTER2].set_active_dataset( + 10, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[ROUTER2].set_mode('rsdn') self.nodes[ROUTER2].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[ROUTER2].enable_whitelist() @@ -81,9 +89,9 @@ class Cert_9_2_09_PendingPartition(unittest.TestCase): self.nodes[ROUTER2].set_network_id_timeout(100) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -105,11 +113,13 @@ class Cert_9_2_09_PendingPartition(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[ROUTER2].get_state(), 'router') - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=30, - active_timestamp=210, - delay_timer=500000, - channel=20, - panid=0xafce) + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=30, + active_timestamp=210, + delay_timer=500000, + channel=20, + panid=0xafce, + ) self.simulator.go(5) self.nodes[LEADER].remove_whitelist(self.nodes[ROUTER1].get_addr64()) @@ -119,11 +129,13 @@ class Cert_9_2_09_PendingPartition(unittest.TestCase): self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') self.assertEqual(self.nodes[ROUTER2].get_state(), 'leader') - self.nodes[ROUTER2].send_mgmt_pending_set(pending_timestamp=50, - active_timestamp=410, - delay_timer=200000, - channel=CHANNEL_FINAL, - panid=PANID_FINAL) + self.nodes[ROUTER2].send_mgmt_pending_set( + pending_timestamp=50, + active_timestamp=410, + delay_timer=200000, + channel=CHANNEL_FINAL, + panid=PANID_FINAL, + ) self.simulator.go(5) self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64()) @@ -150,5 +162,6 @@ class Cert_9_2_09_PendingPartition(unittest.TestCase): self.assertTrue(self.nodes[LEADER].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_10_PendingPartition.py b/tests/scripts/thread-cert/Cert_9_2_10_PendingPartition.py index 557fbac14..46868e1f2 100755 --- a/tests/scripts/thread-cert/Cert_9_2_10_PendingPartition.py +++ b/tests/scripts/thread-cert/Cert_9_2_10_PendingPartition.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -47,21 +46,26 @@ SED1 = 5 MTDS = [ED1, SED1] + class Cert_9_2_10_PendingPartition(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) - self.nodes[COMMISSIONER].set_active_dataset(15, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[COMMISSIONER].set_active_dataset( + 15, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[COMMISSIONER].set_mode('rsdn') self.nodes[COMMISSIONER].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[COMMISSIONER].enable_whitelist() self.nodes[COMMISSIONER].set_router_selection_jitter(1) - self.nodes[LEADER].set_active_dataset(15, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[LEADER].set_active_dataset( + 15, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[LEADER].set_mode('rsdn') self.nodes[LEADER].set_partition_id(0xffffffff) self.nodes[LEADER].add_whitelist(self.nodes[COMMISSIONER].get_addr64()) @@ -69,7 +73,9 @@ class Cert_9_2_10_PendingPartition(unittest.TestCase): self.nodes[LEADER].enable_whitelist() self.nodes[LEADER].set_router_selection_jitter(1) - self.nodes[ROUTER1].set_active_dataset(15, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[ROUTER1].set_active_dataset( + 15, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[ROUTER1].set_mode('rsdn') self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[ROUTER1].add_whitelist(self.nodes[ED1].get_addr64()) @@ -91,9 +97,9 @@ class Cert_9_2_10_PendingPartition(unittest.TestCase): self.nodes[SED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -119,11 +125,13 @@ class Cert_9_2_10_PendingPartition(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[SED1].get_state(), 'child') - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=30, - active_timestamp=165, - delay_timer=150000, - channel=CHANNEL_FINAL, - panid=PANID_FINAL) + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=30, + active_timestamp=165, + delay_timer=150000, + channel=CHANNEL_FINAL, + panid=PANID_FINAL, + ) self.simulator.go(5) print(self.nodes[COMMISSIONER].get_channel()) @@ -171,5 +179,6 @@ class Cert_9_2_10_PendingPartition(unittest.TestCase): self.assertTrue(self.nodes[LEADER].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_11_MasterKey.py b/tests/scripts/thread-cert/Cert_9_2_11_MasterKey.py index 3eb9eb3e5..e09dad29d 100755 --- a/tests/scripts/thread-cert/Cert_9_2_11_MasterKey.py +++ b/tests/scripts/thread-cert/Cert_9_2_11_MasterKey.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -47,28 +46,35 @@ SED1 = 5 MTDS = [ED1, SED1] + class Cert_9_2_11_MasterKey(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) - self.nodes[COMMISSIONER].set_active_dataset(10, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1) + self.nodes[COMMISSIONER].set_active_dataset( + 10, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1 + ) self.nodes[COMMISSIONER].set_mode('rsdn') self.nodes[COMMISSIONER].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[COMMISSIONER].enable_whitelist() self.nodes[COMMISSIONER].set_router_selection_jitter(1) - self.nodes[LEADER].set_active_dataset(10, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1) + self.nodes[LEADER].set_active_dataset( + 10, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1 + ) self.nodes[LEADER].set_mode('rsdn') self.nodes[LEADER].add_whitelist(self.nodes[COMMISSIONER].get_addr64()) self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[LEADER].enable_whitelist() self.nodes[LEADER].set_router_selection_jitter(1) - self.nodes[ROUTER1].set_active_dataset(10, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1) + self.nodes[ROUTER1].set_active_dataset( + 10, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1 + ) self.nodes[ROUTER1].set_mode('rsdn') self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[ROUTER1].add_whitelist(self.nodes[ED1].get_addr64()) @@ -92,9 +98,9 @@ class Cert_9_2_11_MasterKey(unittest.TestCase): self.nodes[SED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -120,10 +126,12 @@ class Cert_9_2_11_MasterKey(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[SED1].get_state(), 'child') - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=10, - active_timestamp=70, - delay_timer=10000, - master_key=KEY2) + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=10, + active_timestamp=70, + delay_timer=10000, + master_key=KEY2, + ) self.simulator.go(310) print(self.nodes[COMMISSIONER].get_masterkey()) @@ -143,10 +151,12 @@ class Cert_9_2_11_MasterKey(unittest.TestCase): if ipaddr[0:4] != 'fe80': self.assertTrue(self.nodes[LEADER].ping(ipaddr)) - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=20, - active_timestamp=30, - delay_timer=10000, - master_key=KEY1) + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=20, + active_timestamp=30, + delay_timer=10000, + master_key=KEY1, + ) self.simulator.go(310) print(self.nodes[COMMISSIONER].get_masterkey()) @@ -166,5 +176,6 @@ class Cert_9_2_11_MasterKey(unittest.TestCase): if ipaddr[0:4] != 'fe80': self.assertTrue(self.nodes[LEADER].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_12_Announce.py b/tests/scripts/thread-cert/Cert_9_2_12_Announce.py index bd29c483a..feb50b6b9 100755 --- a/tests/scripts/thread-cert/Cert_9_2_12_Announce.py +++ b/tests/scripts/thread-cert/Cert_9_2_12_Announce.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -47,34 +46,43 @@ DATASET2_TIMESTAMP = 10 DATASET2_CHANNEL = 12 DATASET2_PANID = 0xafce + class Cert_9_2_12_Announce(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,6): + for i in range(1, 6): self.nodes[i] = node.Node(i, (i == MED), simulator=self.simulator) - self.nodes[LEADER1].set_active_dataset(DATASET1_TIMESTAMP, channel=DATASET1_CHANNEL, panid=DATASET1_PANID) + self.nodes[LEADER1].set_active_dataset( + DATASET1_TIMESTAMP, channel=DATASET1_CHANNEL, panid=DATASET1_PANID + ) self.nodes[LEADER1].set_mode('rsdn') self.nodes[LEADER1].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[LEADER1].enable_whitelist() - self.nodes[ROUTER1].set_active_dataset(DATASET1_TIMESTAMP, channel=DATASET1_CHANNEL, panid=DATASET1_PANID) + self.nodes[ROUTER1].set_active_dataset( + DATASET1_TIMESTAMP, channel=DATASET1_CHANNEL, panid=DATASET1_PANID + ) self.nodes[ROUTER1].set_mode('rsdn') self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER1].get_addr64()) self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER2].get_addr64()) self.nodes[ROUTER1].enable_whitelist() self.nodes[ROUTER1].set_router_selection_jitter(1) - self.nodes[LEADER2].set_active_dataset(DATASET2_TIMESTAMP, channel=DATASET2_CHANNEL, panid=DATASET2_PANID) + self.nodes[LEADER2].set_active_dataset( + DATASET2_TIMESTAMP, channel=DATASET2_CHANNEL, panid=DATASET2_PANID + ) self.nodes[LEADER2].set_mode('rsdn') self.nodes[LEADER2].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[LEADER2].add_whitelist(self.nodes[ROUTER2].get_addr64()) self.nodes[LEADER2].enable_whitelist() self.nodes[LEADER2].set_router_selection_jitter(1) - self.nodes[ROUTER2].set_active_dataset(DATASET2_TIMESTAMP, channel=DATASET2_CHANNEL, panid=DATASET2_PANID) + self.nodes[ROUTER2].set_active_dataset( + DATASET2_TIMESTAMP, channel=DATASET2_CHANNEL, panid=DATASET2_PANID + ) self.nodes[ROUTER2].set_mode('rsdn') self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER2].get_addr64()) self.nodes[ROUTER2].add_whitelist(self.nodes[MED].get_addr64()) @@ -88,9 +96,9 @@ class Cert_9_2_12_Announce(unittest.TestCase): self.nodes[MED].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -132,5 +140,6 @@ class Cert_9_2_12_Announce(unittest.TestCase): if ipaddr[0:4] != 'fe80': self.assertTrue(self.nodes[LEADER1].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_13_EnergyScan.py b/tests/scripts/thread-cert/Cert_9_2_13_EnergyScan.py index 31ee6fd99..d57989015 100755 --- a/tests/scripts/thread-cert/Cert_9_2_13_EnergyScan.py +++ b/tests/scripts/thread-cert/Cert_9_2_13_EnergyScan.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -38,12 +37,13 @@ LEADER = 2 ROUTER1 = 3 ED1 = 4 + class Cert_9_2_13_EnergyScan(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, (i == ED1), simulator=self.simulator) self.nodes[COMMISSIONER].set_panid(0xface) @@ -71,9 +71,9 @@ class Cert_9_2_13_EnergyScan(unittest.TestCase): self.nodes[ED1].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -101,7 +101,9 @@ class Cert_9_2_13_EnergyScan(unittest.TestCase): break self.assertTrue(self.nodes[COMMISSIONER].ping(ipaddr)) - self.nodes[COMMISSIONER].energy_scan(0x50000, 0x02, 0x20, 0x3e8, ipaddr) + self.nodes[COMMISSIONER].energy_scan( + 0x50000, 0x02, 0x20, 0x3E8, ipaddr + ) ipaddrs = self.nodes[ED1].get_addrs() for ipaddr in ipaddrs: @@ -109,11 +111,16 @@ class Cert_9_2_13_EnergyScan(unittest.TestCase): break self.assertTrue(self.nodes[COMMISSIONER].ping(ipaddr)) - self.nodes[COMMISSIONER].energy_scan(0x50000, 0x02, 0x20, 0x3e8, ipaddr) + self.nodes[COMMISSIONER].energy_scan( + 0x50000, 0x02, 0x20, 0x3E8, ipaddr + ) - self.nodes[COMMISSIONER].energy_scan(0x50000, 0x02, 0x20, 0x3e8, 'ff33:0040:fdde:ad00:beef:0:0:1') + self.nodes[COMMISSIONER].energy_scan( + 0x50000, 0x02, 0x20, 0x3E8, 'ff33:0040:fdde:ad00:beef:0:0:1' + ) self.assertTrue(self.nodes[COMMISSIONER].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_14_PanIdQuery.py b/tests/scripts/thread-cert/Cert_9_2_14_PanIdQuery.py index da9fe9291..be2b14646 100755 --- a/tests/scripts/thread-cert/Cert_9_2_14_PanIdQuery.py +++ b/tests/scripts/thread-cert/Cert_9_2_14_PanIdQuery.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -38,23 +37,28 @@ LEADER1 = 2 ROUTER1 = 3 LEADER2 = 4 + class Cert_9_2_14_PanIdQuery(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[COMMISSIONER].set_panid(0xface) self.nodes[COMMISSIONER].set_mode('rsdn') - self.nodes[COMMISSIONER].add_whitelist(self.nodes[LEADER1].get_addr64()) + self.nodes[COMMISSIONER].add_whitelist( + self.nodes[LEADER1].get_addr64() + ) self.nodes[COMMISSIONER].enable_whitelist() self.nodes[COMMISSIONER].set_router_selection_jitter(1) self.nodes[LEADER1].set_panid(0xface) self.nodes[LEADER1].set_mode('rsdn') - self.nodes[LEADER1].add_whitelist(self.nodes[COMMISSIONER].get_addr64()) + self.nodes[LEADER1].add_whitelist( + self.nodes[COMMISSIONER].get_addr64() + ) self.nodes[LEADER1].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[LEADER1].enable_whitelist() @@ -71,9 +75,9 @@ class Cert_9_2_14_PanIdQuery(unittest.TestCase): self.nodes[LEADER2].enable_whitelist() def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -102,9 +106,12 @@ class Cert_9_2_14_PanIdQuery(unittest.TestCase): self.nodes[COMMISSIONER].panid_query(0xdead, 0xffffffff, ipaddr) - self.nodes[COMMISSIONER].panid_query(0xdead, 0xffffffff, 'ff33:0040:fdde:ad00:beef:0:0:1') + self.nodes[COMMISSIONER].panid_query( + 0xdead, 0xffffffff, 'ff33:0040:fdde:ad00:beef:0:0:1' + ) self.assertTrue(self.nodes[COMMISSIONER].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_15_PendingPartition.py b/tests/scripts/thread-cert/Cert_9_2_15_PendingPartition.py index 87a38070e..7883de373 100755 --- a/tests/scripts/thread-cert/Cert_9_2_15_PendingPartition.py +++ b/tests/scripts/thread-cert/Cert_9_2_15_PendingPartition.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -43,21 +42,26 @@ LEADER = 2 ROUTER1 = 3 ROUTER2 = 4 + class Cert_9_2_15_PendingPartition(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, simulator=self.simulator) - self.nodes[COMMISSIONER].set_active_dataset(15, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[COMMISSIONER].set_active_dataset( + 15, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[COMMISSIONER].set_mode('rsdn') self.nodes[COMMISSIONER].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[COMMISSIONER].enable_whitelist() self.nodes[COMMISSIONER].set_router_selection_jitter(1) - self.nodes[LEADER].set_active_dataset(15, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[LEADER].set_active_dataset( + 15, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[LEADER].set_mode('rsdn') self.nodes[LEADER].set_partition_id(0xffffffff) self.nodes[LEADER].add_whitelist(self.nodes[COMMISSIONER].get_addr64()) @@ -65,14 +69,18 @@ class Cert_9_2_15_PendingPartition(unittest.TestCase): self.nodes[LEADER].enable_whitelist() self.nodes[LEADER].set_router_selection_jitter(1) - self.nodes[ROUTER1].set_active_dataset(15, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[ROUTER1].set_active_dataset( + 15, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[ROUTER1].set_mode('rsdn') self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[ROUTER1].add_whitelist(self.nodes[ROUTER2].get_addr64()) self.nodes[ROUTER1].enable_whitelist() self.nodes[ROUTER1].set_router_selection_jitter(1) - self.nodes[ROUTER2].set_active_dataset(15, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[ROUTER2].set_active_dataset( + 15, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[ROUTER2].set_mode('rsdn') self._setUpRouter2() @@ -82,9 +90,9 @@ class Cert_9_2_15_PendingPartition(unittest.TestCase): self.nodes[ROUTER2].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -102,10 +110,12 @@ class Cert_9_2_15_PendingPartition(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=10, - active_timestamp=70, - delay_timer=600000, - mesh_local='fd00:0db9::') + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=10, + active_timestamp=70, + delay_timer=600000, + mesh_local='fd00:0db9::', + ) self.simulator.go(5) self.nodes[ROUTER2].start() @@ -115,11 +125,13 @@ class Cert_9_2_15_PendingPartition(unittest.TestCase): self.nodes[ROUTER2].reset() self._setUpRouter2() - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=20, - active_timestamp=80, - delay_timer=200000, - mesh_local='fd00:0db7::', - panid=PANID_FINAL) + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=20, + active_timestamp=80, + delay_timer=200000, + mesh_local='fd00:0db7::', + panid=PANID_FINAL, + ) self.simulator.go(100) self.nodes[ROUTER2].start() @@ -138,5 +150,6 @@ class Cert_9_2_15_PendingPartition(unittest.TestCase): break self.assertTrue(self.nodes[LEADER].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_16_ActivePendingPartition.py b/tests/scripts/thread-cert/Cert_9_2_16_ActivePendingPartition.py index 0bf1c6fa6..e791cefce 100755 --- a/tests/scripts/thread-cert/Cert_9_2_16_ActivePendingPartition.py +++ b/tests/scripts/thread-cert/Cert_9_2_16_ActivePendingPartition.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -44,21 +43,26 @@ LEADER = 2 ROUTER1 = 3 ROUTER2 = 4 + class Cert_9_2_16_ActivePendingPartition(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,5): + for i in range(1, 5): self.nodes[i] = node.Node(i, simulator=self.simulator) - self.nodes[COMMISSIONER].set_active_dataset(1, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[COMMISSIONER].set_active_dataset( + 1, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[COMMISSIONER].set_mode('rsdn') self.nodes[COMMISSIONER].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[COMMISSIONER].enable_whitelist() self.nodes[COMMISSIONER].set_router_selection_jitter(1) - self.nodes[LEADER].set_active_dataset(1, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[LEADER].set_active_dataset( + 1, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[LEADER].set_mode('rsdn') self.nodes[LEADER].set_partition_id(0xffffffff) self.nodes[LEADER].add_whitelist(self.nodes[COMMISSIONER].get_addr64()) @@ -66,14 +70,18 @@ class Cert_9_2_16_ActivePendingPartition(unittest.TestCase): self.nodes[LEADER].enable_whitelist() self.nodes[LEADER].set_router_selection_jitter(1) - self.nodes[ROUTER1].set_active_dataset(1, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[ROUTER1].set_active_dataset( + 1, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[ROUTER1].set_mode('rsdn') self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[ROUTER1].add_whitelist(self.nodes[ROUTER2].get_addr64()) self.nodes[ROUTER1].enable_whitelist() self.nodes[ROUTER1].set_router_selection_jitter(1) - self.nodes[ROUTER2].set_active_dataset(1, channel=CHANNEL_INIT, panid=PANID_INIT) + self.nodes[ROUTER2].set_active_dataset( + 1, channel=CHANNEL_INIT, panid=PANID_INIT + ) self.nodes[ROUTER2].set_mode('rsdn') self._setUpRouter2() @@ -83,9 +91,9 @@ class Cert_9_2_16_ActivePendingPartition(unittest.TestCase): self.nodes[ROUTER2].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -103,10 +111,12 @@ class Cert_9_2_16_ActivePendingPartition(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=10, - active_timestamp=10, - delay_timer=600000, - mesh_local='fd00:0db9::') + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=10, + active_timestamp=10, + delay_timer=600000, + mesh_local='fd00:0db9::', + ) self.simulator.go(5) self.nodes[ROUTER2].start() @@ -116,25 +126,36 @@ class Cert_9_2_16_ActivePendingPartition(unittest.TestCase): self.nodes[ROUTER2].reset() self._setUpRouter2() - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=20, - active_timestamp=20, - delay_timer=200000, - mesh_local='fd00:0db7::', - panid=PANID_FINAL) + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=20, + active_timestamp=20, + delay_timer=200000, + mesh_local='fd00:0db7::', + panid=PANID_FINAL, + ) self.simulator.go(5) - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=15, - network_name='threadCert') + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=15, network_name='threadCert' + ) self.simulator.go(100) self.nodes[ROUTER2].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER2].get_state(), 'router') - self.assertEqual(self.nodes[COMMISSIONER].get_network_name(), NETWORK_NAME_FINAL) - self.assertEqual(self.nodes[LEADER].get_network_name(), NETWORK_NAME_FINAL) - self.assertEqual(self.nodes[ROUTER1].get_network_name(), NETWORK_NAME_FINAL) - self.assertEqual(self.nodes[ROUTER2].get_network_name(), NETWORK_NAME_FINAL) + self.assertEqual( + self.nodes[COMMISSIONER].get_network_name(), NETWORK_NAME_FINAL + ) + self.assertEqual( + self.nodes[LEADER].get_network_name(), NETWORK_NAME_FINAL + ) + self.assertEqual( + self.nodes[ROUTER1].get_network_name(), NETWORK_NAME_FINAL + ) + self.assertEqual( + self.nodes[ROUTER2].get_network_name(), NETWORK_NAME_FINAL + ) self.simulator.go(100) @@ -149,5 +170,6 @@ class Cert_9_2_16_ActivePendingPartition(unittest.TestCase): break self.assertTrue(self.nodes[LEADER].ping(ipaddr)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_17_Orphan.py b/tests/scripts/thread-cert/Cert_9_2_17_Orphan.py index d41199113..a5cba0789 100755 --- a/tests/scripts/thread-cert/Cert_9_2_17_Orphan.py +++ b/tests/scripts/thread-cert/Cert_9_2_17_Orphan.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -42,21 +41,26 @@ LEADER1 = 1 LEADER2 = 2 ED1 = 3 + class Cert_9_2_17_Orphan(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, (i == ED1), simulator=self.simulator) - self.nodes[LEADER1].set_active_dataset(10, channel=CHANNEL1, panid=PANID_INIT, channel_mask=CHANNEL_MASK) + self.nodes[LEADER1].set_active_dataset( + 10, channel=CHANNEL1, panid=PANID_INIT, channel_mask=CHANNEL_MASK + ) self.nodes[LEADER1].set_mode('rsdn') self.nodes[LEADER1].add_whitelist(self.nodes[ED1].get_addr64()) self.nodes[LEADER1].enable_whitelist() self.nodes[LEADER1].set_router_selection_jitter(1) - self.nodes[LEADER2].set_active_dataset(20, channel=CHANNEL2, panid=PANID_INIT, channel_mask=CHANNEL_MASK) + self.nodes[LEADER2].set_active_dataset( + 20, channel=CHANNEL2, panid=PANID_INIT, channel_mask=CHANNEL_MASK + ) self.nodes[LEADER2].set_mode('rsdn') self.nodes[LEADER2].enable_whitelist() self.nodes[LEADER2].set_router_selection_jitter(1) @@ -69,9 +73,9 @@ class Cert_9_2_17_Orphan(unittest.TestCase): self.nodes[ED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -95,5 +99,6 @@ class Cert_9_2_17_Orphan(unittest.TestCase): self.assertEqual(self.nodes[ED1].get_state(), 'child') self.assertEqual(self.nodes[ED1].get_channel(), CHANNEL2) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Cert_9_2_18_RollBackActiveTimestamp.py b/tests/scripts/thread-cert/Cert_9_2_18_RollBackActiveTimestamp.py index 873140247..7292d2baf 100755 --- a/tests/scripts/thread-cert/Cert_9_2_18_RollBackActiveTimestamp.py +++ b/tests/scripts/thread-cert/Cert_9_2_18_RollBackActiveTimestamp.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config @@ -48,21 +47,26 @@ SED1 = 6 MTDS = [ED1, SED1] + class Cert_9_2_18_RollBackActiveTimestamp(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,7): + for i in range(1, 7): self.nodes[i] = node.Node(i, (i in MTDS), simulator=self.simulator) - self.nodes[COMMISSIONER].set_active_dataset(1, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1) + self.nodes[COMMISSIONER].set_active_dataset( + 1, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1 + ) self.nodes[COMMISSIONER].set_mode('rsdn') self.nodes[COMMISSIONER].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[COMMISSIONER].enable_whitelist() self.nodes[COMMISSIONER].set_router_selection_jitter(1) - self.nodes[LEADER].set_active_dataset(1, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1) + self.nodes[LEADER].set_active_dataset( + 1, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1 + ) self.nodes[LEADER].set_mode('rsdn') self.nodes[LEADER].set_partition_id(0xffffffff) self.nodes[LEADER].add_whitelist(self.nodes[COMMISSIONER].get_addr64()) @@ -70,7 +74,9 @@ class Cert_9_2_18_RollBackActiveTimestamp(unittest.TestCase): self.nodes[LEADER].enable_whitelist() self.nodes[LEADER].set_router_selection_jitter(1) - self.nodes[ROUTER1].set_active_dataset(1, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1) + self.nodes[ROUTER1].set_active_dataset( + 1, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1 + ) self.nodes[ROUTER1].set_mode('rsdn') self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[ROUTER1].add_whitelist(self.nodes[ROUTER2].get_addr64()) @@ -79,7 +85,9 @@ class Cert_9_2_18_RollBackActiveTimestamp(unittest.TestCase): self.nodes[ROUTER1].enable_whitelist() self.nodes[ROUTER1].set_router_selection_jitter(1) - self.nodes[ROUTER2].set_active_dataset(1, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1) + self.nodes[ROUTER2].set_active_dataset( + 1, channel=CHANNEL_INIT, panid=PANID_INIT, master_key=KEY1 + ) self.nodes[ROUTER2].set_mode('rsdn') self.nodes[ROUTER2].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[ROUTER2].enable_whitelist() @@ -101,9 +109,9 @@ class Cert_9_2_18_RollBackActiveTimestamp(unittest.TestCase): self.nodes[SED1].set_timeout(config.DEFAULT_CHILD_TIMEOUT) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() def test(self): self.nodes[LEADER].start() @@ -128,21 +136,26 @@ class Cert_9_2_18_RollBackActiveTimestamp(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[SED1].get_state(), 'child') - self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=20000, - network_name='GRL') + self.nodes[COMMISSIONER].send_mgmt_active_set( + active_timestamp=20000, network_name='GRL' + ) self.simulator.go(5) - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=20, - active_timestamp=20, - delay_timer=20000, - network_name='Shouldnotbe') + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=20, + active_timestamp=20, + delay_timer=20000, + network_name='Shouldnotbe', + ) self.simulator.go(5) - self.nodes[COMMISSIONER].send_mgmt_pending_set(pending_timestamp=20, - active_timestamp=20, - delay_timer=20000, - network_name='MyHouse', - master_key=KEY2) + self.nodes[COMMISSIONER].send_mgmt_pending_set( + pending_timestamp=20, + active_timestamp=20, + delay_timer=20000, + network_name='MyHouse', + master_key=KEY2, + ) self.simulator.go(310) self.assertEqual(self.nodes[COMMISSIONER].get_masterkey(), KEY2) @@ -156,5 +169,6 @@ class Cert_9_2_18_RollBackActiveTimestamp(unittest.TestCase): self.simulator.go(5) self.assertEqual(self.nodes[ROUTER2].get_state(), 'leader') + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Test_Cli.py b/tests/scripts/thread-cert/Test_Cli.py index 368754827..50d214a38 100755 --- a/tests/scripts/thread-cert/Test_Cli.py +++ b/tests/scripts/thread-cert/Test_Cli.py @@ -27,22 +27,22 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import node LEADER = 1 + class Cert_Cli(unittest.TestCase): def setUp(self): self.nodes = {} self.nodes[LEADER] = node.Node(LEADER) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() def test(self): commands = self.nodes[LEADER].get_commands() @@ -51,5 +51,6 @@ class Cert_Cli(unittest.TestCase): self.nodes[LEADER].send_command(command + ' -h') self.nodes[LEADER].pexpect.expect('Done') + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/Test_MacScan.py b/tests/scripts/thread-cert/Test_MacScan.py index 2adfc207a..0b68c0b54 100755 --- a/tests/scripts/thread-cert/Test_MacScan.py +++ b/tests/scripts/thread-cert/Test_MacScan.py @@ -35,10 +35,11 @@ import node LEADER = 1 ROUTER = 2 + class Test_MacScan(unittest.TestCase): def setUp(self): self.nodes = {} - for i in range(1,3): + for i in range(1, 3): self.nodes[i] = node.Node(i) self.nodes[LEADER].set_panid(0xface) @@ -56,9 +57,9 @@ class Test_MacScan(unittest.TestCase): self.nodes[ROUTER].set_network_name('OpenThread') def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() def test(self): self.nodes[LEADER].start() @@ -72,5 +73,6 @@ class Test_MacScan(unittest.TestCase): results = self.nodes[LEADER].scan() self.assertEqual(len(results), 16) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/__init__.py b/tests/scripts/thread-cert/__init__.py index 90156456c..81888632e 100755 --- a/tests/scripts/thread-cert/__init__.py +++ b/tests/scripts/thread-cert/__init__.py @@ -26,4 +26,3 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # - diff --git a/tests/scripts/thread-cert/coap.py b/tests/scripts/thread-cert/coap.py index 43e46b67f..ea926b59c 100644 --- a/tests/scripts/thread-cert/coap.py +++ b/tests/scripts/thread-cert/coap.py @@ -78,7 +78,7 @@ class CoapOptionHeader(object): @property def is_payload_marker(self): - return self.delta == 0xf and self.length == 0xf + return self.delta == 0xF and self.length == 0xF @classmethod def _read_extended_value(cls, data, value): @@ -94,8 +94,8 @@ class CoapOptionHeader(object): def from_bytes(cls, data): initial_byte = ord(data.read(1)) - delta = (initial_byte >> 4) & 0xf - length = initial_byte & 0xf + delta = (initial_byte >> 4) & 0xF + length = initial_byte & 0xF delta = cls._read_extended_value(data, delta) length = cls._read_extended_value(data, length) @@ -120,7 +120,9 @@ class CoapOption(object): return self._value def __repr__(self): - return "CoapOption(type={}, value={})".format(self.type, hexlify(self.value)) + return "CoapOption(type={}, value={})".format( + self.type, hexlify(self.value) + ) class CoapOptionsFactory(object): @@ -162,11 +164,11 @@ class CoapCode(object): @property def detail(self): - return self.code & 0x1f + return self.code & 0x1F @classmethod def from_class_and_detail(cls, _class, detail): - return cls(((_class & 0x7) << 5) | (detail & 0x1f)) + return cls(((_class & 0x7) << 5) | (detail & 0x1F)) @classmethod def from_dotted(cls, dotted_str): @@ -179,7 +181,9 @@ class CoapCode(object): @property def dotted(self): - return ".".join(["{:01d}".format(self._class), "{:02d}".format(self.detail)]) + return ".".join( + ["{:01d}".format(self._class), "{:02d}".format(self.detail)] + ) def __eq__(self, other): if isinstance(other, int): @@ -192,7 +196,9 @@ class CoapCode(object): return self.code == other.code else: - raise TypeError("Could not compare {} and {}".format(type(self), type(other))) + raise TypeError( + "Could not compare {} and {}".format(type(self), type(other)) + ) def __repr__(self): return self.dotted @@ -202,7 +208,17 @@ class CoapMessage(object): """ Class representing CoAP message. """ - def __init__(self, version, _type, code, message_id, token, options, payload, uri_path=None): + def __init__( + self, + version, + _type, + code, + message_id, + token, + options, + payload, + uri_path=None, + ): self._version = version self._type = _type self._code = code @@ -250,9 +266,17 @@ class CoapMessage(object): def __repr__(self): options_str = ", ".join([repr(opt) for opt in self.options]) - return "CoapMessage(version={}, type={}, code={}, message_id={}, token={}, options=[{}], payload={}, uri-path='{}')".format( - self.version, CoapMessageType.name[self.type], self.code, self.message_id, hexlify(self.token), - options_str, self.payload, self.uri_path) + return ("CoapMessage(version={}, type={}, code={}, message_id={}, token={}, options=[{}], payload={},", + "uri-path='{}')").format( + self.version, + CoapMessageType.name[self.type], + self.code, + self.message_id, + hexlify(self.token), + options_str, + self.payload, + self.uri_path, + ) class CoapMessageProxy(object): @@ -264,11 +288,19 @@ class CoapMessageProxy(object): to get URI path to get proper payload parser. """ - def __init__(self, coap_message, message_info, mid_to_uri_path_binder, uri_path_based_payload_factories): + def __init__( + self, + coap_message, + message_info, + mid_to_uri_path_binder, + uri_path_based_payload_factories, + ): self._coap_message = coap_message self._message_info = message_info self._mid_to_uri_path_binder = mid_to_uri_path_binder - self._uri_path_based_payload_factories = uri_path_based_payload_factories + self._uri_path_based_payload_factories = ( + uri_path_based_payload_factories + ) @property def version(self): @@ -301,11 +333,15 @@ class CoapMessageProxy(object): @property def payload(self): try: - binded_uri_path = self._mid_to_uri_path_binder.get_uri_path_for(self.message_id, self.token) + binded_uri_path = self._mid_to_uri_path_binder.get_uri_path_for( + self.message_id, self.token + ) factory = self._uri_path_based_payload_factories[binded_uri_path] - return factory.parse(io.BytesIO(self._coap_message.payload), self._message_info) + return factory.parse( + io.BytesIO(self._coap_message.payload), self._message_info + ) except RuntimeError: return self._coap_message.payload @@ -316,9 +352,10 @@ class CoapMessageProxy(object): def __repr__(self): options_str = ", ".join([repr(opt) for opt in self.options]) - return "CoapMessageProxy(version={}, type={}, code={}, message_id={}, token={}, options=[{}], payload={}, uri-path='{}')".format( - self.version, self.type, self.code, self.message_id, hexlify(self.token), - options_str, self.payload, self.uri_path) + return ("CoapMessageProxy(version={}, type={}, code={}, message_id={}, token={}, options=[{}], payload={},", + "uri-path='{}')").format( + self.version, self.type, self.code, self.message_id, hexlify(self.token), options_str, self.payload, + self.uri_path, ) class CoapMessageIdToUriPathBinder: @@ -335,17 +372,25 @@ class CoapMessageIdToUriPathBinder: try: return self._uri_path_binds[message_id][hexlify(token)] except KeyError: - raise RuntimeError("Could not find URI PATH for message_id: {} and token: {}".format( - message_id, hexlify(token))) + raise RuntimeError( + "Could not find URI PATH for message_id: {} and token: {}".format( + message_id, hexlify(token))) class CoapMessageFactory(object): """ Factory that produces CoAP messages. """ - def __init__(self, options_factory, uri_path_based_payload_factories, message_id_to_uri_path_binder): + def __init__( + self, + options_factory, + uri_path_based_payload_factories, + message_id_to_uri_path_binder, + ): self._options_factory = options_factory - self._uri_path_based_payload_factories = uri_path_based_payload_factories + self._uri_path_based_payload_factories = ( + uri_path_based_payload_factories + ) self._mid_to_uri_path_binder = message_id_to_uri_path_binder def _uri_path_from(self, options): @@ -365,12 +410,14 @@ class CoapMessageFactory(object): version = (initial_byte >> 6) & 0x3 _type = CoapMessageType((initial_byte >> 4) & 0x3) - token_length = initial_byte & 0xf + token_length = initial_byte & 0xF return version, _type, token_length def parse(self, data, message_info): - version, _type, token_length = self._parse_initial_byte(data, message_info) + version, _type, token_length = self._parse_initial_byte( + data, message_info + ) code = CoapCode(ord(data.read(1))) message_id = struct.unpack(">H", data.read(2))[0] @@ -380,8 +427,24 @@ class CoapMessageFactory(object): uri_path = self._uri_path_from(options) if uri_path is not None: - self._mid_to_uri_path_binder.add_uri_path_for(message_id, token, uri_path) + self._mid_to_uri_path_binder.add_uri_path_for( + message_id, token, uri_path + ) - coap_message = CoapMessage(version, _type, code, message_id, token, options, data.read(), uri_path) + coap_message = CoapMessage( + version, + _type, + code, + message_id, + token, + options, + data.read(), + uri_path, + ) - return CoapMessageProxy(coap_message, message_info, self._mid_to_uri_path_binder, self._uri_path_based_payload_factories) + return CoapMessageProxy( + coap_message, + message_info, + self._mid_to_uri_path_binder, + self._uri_path_based_payload_factories, + ) diff --git a/tests/scripts/thread-cert/command.py b/tests/scripts/thread-cert/command.py index d986acf94..043dfe61e 100644 --- a/tests/scripts/thread-cert/command.py +++ b/tests/scripts/thread-cert/command.py @@ -38,36 +38,46 @@ import config import mesh_cop import mle -from collections import Counter from enum import IntEnum -from network_data import Prefix, BorderRouter, LowpanId + class CheckType(IntEnum): CONTAIN = 0 NOT_CONTAIN = 1 OPTIONAL = 2 + class NetworkDataCheckType: PREFIX_CNT = 1 PREFIX_CONTENT = 2 + def check_address_query(command_msg, source_node, destination_address): """Verify source_node sent a properly formatted Address Query Request message to the destination_address. """ command_msg.assertCoapMessageContainsTlv(network_layer.TargetEid) source_rloc = source_node.get_ip6_address(config.ADDRESS_TYPE.RLOC) - assert ipv6.ip_address(source_rloc) == command_msg.ipv6_packet.ipv6_header.source_address, \ - "Error: The IPv6 source address is not the RLOC of the originator. The source node's rloc is: " \ - + str(ipv6.ip_address(source_rloc)) + ", but the source_address in command msg is: " \ - + str(command_msg.ipv6_packet.ipv6_header.source_address) + assert ( + ipv6.ip_address(source_rloc) + == command_msg.ipv6_packet.ipv6_header.source_address + ), ( + "Error: The IPv6 source address is not the RLOC of the originator. The source node's rloc is: " + + str(ipv6.ip_address(source_rloc)) + + ", but the source_address in command msg is: " + + str(command_msg.ipv6_packet.ipv6_header.source_address) + ) if isinstance(destination_address, bytearray): destination_address = bytes(destination_address) elif isinstance(destination_address, str) and sys.version_info[0] == 2: destination_address = destination_address.decode("utf-8") - assert ipv6.ip_address(destination_address) == command_msg.ipv6_packet.ipv6_header.destination_address, "Error: The IPv6 destination address is not expected." + assert ( + ipv6.ip_address(destination_address) + == command_msg.ipv6_packet.ipv6_header.destination_address + ), "Error: The IPv6 destination address is not expected." + def check_address_notification(command_msg, source_node, destination_node): """Verify source_node sent a properly formatted Address Notification command message to destination_node. @@ -78,12 +88,23 @@ def check_address_notification(command_msg, source_node, destination_node): command_msg.assertCoapMessageContainsTlv(network_layer.MlEid) source_rloc = source_node.get_ip6_address(config.ADDRESS_TYPE.RLOC) - assert ipv6.ip_address(source_rloc) == command_msg.ipv6_packet.ipv6_header.source_address, "Error: The IPv6 source address is not the RLOC of the originator." + assert ( + ipv6.ip_address(source_rloc) + == command_msg.ipv6_packet.ipv6_header.source_address + ), "Error: The IPv6 source address is not the RLOC of the originator." - destination_rloc = destination_node.get_ip6_address(config.ADDRESS_TYPE.RLOC) - assert ipv6.ip_address(destination_rloc) == command_msg.ipv6_packet.ipv6_header.destination_address, "Error: The IPv6 destination address is not the RLOC of the destination." + destination_rloc = destination_node.get_ip6_address( + config.ADDRESS_TYPE.RLOC + ) + assert ( + ipv6.ip_address(destination_rloc) + == command_msg.ipv6_packet.ipv6_header.destination_address + ), "Error: The IPv6 destination address is not the RLOC of the destination." -def check_address_error_notification(command_msg, source_node, destination_address): + +def check_address_error_notification( + command_msg, source_node, destination_address +): """Verify source_node sent a properly formatted Address Error Notification command message to destination_address. """ command_msg.assertCoapMessageRequestUriPath('/a/ae') @@ -91,20 +112,31 @@ def check_address_error_notification(command_msg, source_node, destination_addre command_msg.assertCoapMessageContainsTlv(network_layer.MlEid) source_rloc = source_node.get_ip6_address(config.ADDRESS_TYPE.RLOC) - assert ipv6.ip_address(source_rloc) == command_msg.ipv6_packet.ipv6_header.source_address, \ - "Error: The IPv6 source address is not the RLOC of the originator. The source node's rloc is: " \ - + str(ipv6.ip_address(source_rloc)) + ", but the source_address in command msg is: " \ - + str(command_msg.ipv6_packet.ipv6_header.source_address) + assert ( + ipv6.ip_address(source_rloc) + == command_msg.ipv6_packet.ipv6_header.source_address + ), ( + "Error: The IPv6 source address is not the RLOC of the originator. The source node's rloc is: " + + str(ipv6.ip_address(source_rloc)) + + ", but the source_address in command msg is: " + + str(command_msg.ipv6_packet.ipv6_header.source_address) + ) if isinstance(destination_address, bytearray): destination_address = bytes(destination_address) elif isinstance(destination_address, str) and sys.version_info[0] == 2: destination_address = destination_address.decode("utf-8") - assert ipv6.ip_address(destination_address) == command_msg.ipv6_packet.ipv6_header.destination_address, \ - "Error: The IPv6 destination address is not expected. The destination node's rloc is: " \ - + str(ipv6.ip_address(destination_address)) + ", but the destination_address in command msg is: " \ - + str(command_msg.ipv6_packet.ipv6_header.destination_address) + assert ( + ipv6.ip_address(destination_address) + == command_msg.ipv6_packet.ipv6_header.destination_address + ), ( + "Error: The IPv6 destination address is not expected. The destination node's rloc is: " + + str(ipv6.ip_address(destination_address)) + + ", but the destination_address in command msg is: " + + str(command_msg.ipv6_packet.ipv6_header.destination_address) + ) + def check_address_solicit(command_msg, was_router): command_msg.assertCoapMessageRequestUriPath('/a/as') @@ -115,6 +147,7 @@ def check_address_solicit(command_msg, was_router): else: command_msg.assertMleMessageDoesNotContainTlv(network_layer.Rloc16) + def check_address_release(command_msg, destination_node): """Verify the message is a properly formatted address release destined to the given node. """ @@ -122,8 +155,14 @@ def check_address_release(command_msg, destination_node): command_msg.assertCoapMessageContainsTlv(network_layer.Rloc16) command_msg.assertCoapMessageContainsTlv(network_layer.MacExtendedAddress) - destination_rloc = destination_node.get_ip6_address(config.ADDRESS_TYPE.RLOC) - assert ipv6.ip_address(destination_rloc) == command_msg.ipv6_packet.ipv6_header.destination_address, "Error: The destination is not RLOC address" + destination_rloc = destination_node.get_ip6_address( + config.ADDRESS_TYPE.RLOC + ) + assert ( + ipv6.ip_address(destination_rloc) + == command_msg.ipv6_packet.ipv6_header.destination_address + ), "Error: The destination is not RLOC address" + def check_tlv_request_tlv(command_msg, check_type, tlv_id): """Verify if TLV Request TLV contains specified TLV ID @@ -131,29 +170,44 @@ def check_tlv_request_tlv(command_msg, check_type, tlv_id): tlv_request_tlv = command_msg.get_mle_message_tlv(mle.TlvRequest) if check_type == CheckType.CONTAIN: - assert tlv_request_tlv is not None, "Error: The msg doesn't contain TLV Request TLV" - assert any(tlv_id == tlv for tlv in tlv_request_tlv.tlvs), "Error: The msg doesn't contain TLV Request TLV ID: {}".format(tlv_id) + assert ( + tlv_request_tlv is not None + ), "Error: The msg doesn't contain TLV Request TLV" + assert any( + tlv_id == tlv for tlv in tlv_request_tlv.tlvs + ), "Error: The msg doesn't contain TLV Request TLV ID: {}".format( + tlv_id + ) elif check_type == CheckType.NOT_CONTAIN: if tlv_request_tlv is not None: - assert any(tlv_id == tlv for tlv in tlv_request_tlv.tlvs) is False, "Error: The msg contains TLV Request TLV ID: {}".format(tlv_id) + assert ( + any(tlv_id == tlv for tlv in tlv_request_tlv.tlvs) is False + ), "Error: The msg contains TLV Request TLV ID: {}".format(tlv_id) elif check_type == CheckType.OPTIONAL: if tlv_request_tlv is not None: if any(tlv_id == tlv for tlv in tlv_request_tlv.tlvs): print("TLV Request TLV contains TLV ID: {}".format(tlv_id)) else: - print("TLV Request TLV doesn't contain TLV ID: {}".format(tlv_id)) + print( + "TLV Request TLV doesn't contain TLV ID: {}".format(tlv_id) + ) else: print("The msg doesn't contain TLV Request TLV") else: raise ValueError("Invalid check type") -def check_link_request(command_msg, source_address = CheckType.OPTIONAL, leader_data = CheckType.OPTIONAL, \ - tlv_request_address16 = CheckType.OPTIONAL, tlv_request_route64 = CheckType.OPTIONAL, \ - tlv_request_link_margin = CheckType.OPTIONAL): +def check_link_request( + command_msg, + source_address=CheckType.OPTIONAL, + leader_data=CheckType.OPTIONAL, + tlv_request_address16=CheckType.OPTIONAL, + tlv_request_route64=CheckType.OPTIONAL, + tlv_request_link_margin=CheckType.OPTIONAL, +): """Verify a properly formatted Link Request command message. """ command_msg.assertMleMessageContainsTlv(mle.Challenge) @@ -162,14 +216,28 @@ def check_link_request(command_msg, source_address = CheckType.OPTIONAL, leader_ check_mle_optional_tlv(command_msg, source_address, mle.SourceAddress) check_mle_optional_tlv(command_msg, leader_data, mle.LeaderData) - check_tlv_request_tlv(command_msg, tlv_request_address16, mle.TlvType.ADDRESS16) - check_tlv_request_tlv(command_msg, tlv_request_route64, mle.TlvType.ROUTE64) - check_tlv_request_tlv(command_msg, tlv_request_link_margin, mle.TlvType.LINK_MARGIN) + check_tlv_request_tlv( + command_msg, tlv_request_address16, mle.TlvType.ADDRESS16 + ) + check_tlv_request_tlv( + command_msg, tlv_request_route64, mle.TlvType.ROUTE64 + ) + check_tlv_request_tlv( + command_msg, tlv_request_link_margin, mle.TlvType.LINK_MARGIN + ) -def check_link_accept(command_msg, destination_node, \ - leader_data = CheckType.OPTIONAL, link_margin = CheckType.OPTIONAL, mle_frame_counter = CheckType.OPTIONAL, \ - challenge = CheckType.OPTIONAL, address16 = CheckType.OPTIONAL, route64 = CheckType.OPTIONAL, \ - tlv_request_link_margin = CheckType.OPTIONAL): + +def check_link_accept( + command_msg, + destination_node, + leader_data=CheckType.OPTIONAL, + link_margin=CheckType.OPTIONAL, + mle_frame_counter=CheckType.OPTIONAL, + challenge=CheckType.OPTIONAL, + address16=CheckType.OPTIONAL, + route64=CheckType.OPTIONAL, + tlv_request_link_margin=CheckType.OPTIONAL, +): """verify a properly formatted link accept command message. """ command_msg.assertMleMessageContainsTlv(mle.LinkLayerFrameCounter) @@ -184,13 +252,20 @@ def check_link_accept(command_msg, destination_node, \ check_mle_optional_tlv(command_msg, address16, mle.Address16) check_mle_optional_tlv(command_msg, route64, mle.Route64) - check_tlv_request_tlv(command_msg, tlv_request_link_margin, mle.TlvType.LINK_MARGIN) + check_tlv_request_tlv( + command_msg, tlv_request_link_margin, mle.TlvType.LINK_MARGIN + ) - destination_link_local = destination_node.get_ip6_address(config.ADDRESS_TYPE.LINK_LOCAL) - assert ipv6.ip_address(destination_link_local) == command_msg.ipv6_packet.ipv6_header.destination_address, \ - "Error: The destination is unexpected" + destination_link_local = destination_node.get_ip6_address( + config.ADDRESS_TYPE.LINK_LOCAL + ) + assert ( + ipv6.ip_address(destination_link_local) + == command_msg.ipv6_packet.ipv6_header.destination_address + ), "Error: The destination is unexpected" -def check_icmp_path(sniffer, path, nodes, icmp_type = ipv6.ICMP_ECHO_REQUEST): + +def check_icmp_path(sniffer, path, nodes, icmp_type=ipv6.ICMP_ECHO_REQUEST): """Verify icmp message is forwarded along the path. """ len_path = len(path) @@ -203,17 +278,21 @@ def check_icmp_path(sniffer, path, nodes, icmp_type = ipv6.ICMP_ECHO_REQUEST): if i < len_path - 1: next_node = nodes[path[i + 1]] next_node_rloc16 = next_node.get_addr16() - assert next_node_rloc16 == node_icmp_msg.mac_header.dest_address.rloc, "Error: The path is unexpected." + assert ( + next_node_rloc16 == node_icmp_msg.mac_header.dest_address.rloc + ), "Error: The path is unexpected." else: return True return False + def check_id_set(command_msg, router_id): """Check the command_msg's Route64 tlv to verify router_id is an active router. """ tlv = command_msg.assertMleMessageContainsTlv(mle.Route64) - return ((tlv.router_id_mask >> (63 - router_id)) & 1) + return (tlv.router_id_mask >> (63 - router_id)) & 1 + def get_routing_cost(command_msg, router_id): """Check the command_msg's Route64 tlv to get the routing cost to router. @@ -221,8 +300,9 @@ def get_routing_cost(command_msg, router_id): tlv = command_msg.assertMleMessageContainsTlv(mle.Route64) # Get router's mask pos - # Turn the number into binary string. Need to consider the preceding 0 omitted during conversion. - router_id_mask_str = bin(tlv.router_id_mask).replace('0b','') + # Turn the number into binary string. Need to consider the preceding 0 + # omitted during conversion. + router_id_mask_str = bin(tlv.router_id_mask).replace('0b', '') prefix_len = 64 - len(router_id_mask_str) routing_entry_pos = 0 @@ -230,37 +310,47 @@ def get_routing_cost(command_msg, router_id): if router_id_mask_str[i] == '1': routing_entry_pos += 1 - assert router_id_mask_str[router_id - prefix_len] == '1', "Error: The router isn't in the topology. \n" \ - + "route64 tlv is: %s. \nrouter_id is: %s. \nrouting_entry_pos is: %s. \nrouter_id_mask_str is: %s." \ - %(tlv, router_id, routing_entry_pos, router_id_mask_str) + assert router_id_mask_str[router_id - prefix_len] == '1', \ + (("Error: The router isn't in the topology. \n", + "route64 tlv is: %s. \nrouter_id is: %s. \nrouting_entry_pos is: %s. \nrouter_id_mask_str is: %s.") % + (tlv, router_id, routing_entry_pos, router_id_mask_str)) return tlv.link_quality_and_route_data[routing_entry_pos].route + def check_mle_optional_tlv(command_msg, type, tlv): - if (type == CheckType.CONTAIN): + if type == CheckType.CONTAIN: command_msg.assertMleMessageContainsTlv(tlv) - elif (type == CheckType.NOT_CONTAIN): + elif type == CheckType.NOT_CONTAIN: command_msg.assertMleMessageDoesNotContainTlv(tlv) - elif (type == CheckType.OPTIONAL): + elif type == CheckType.OPTIONAL: command_msg.assertMleMessageContainsOptionalTlv(tlv) else: raise ValueError("Invalid check type") + def check_mle_advertisement(command_msg): command_msg.assertSentWithHopLimit(255) - command_msg.assertSentToDestinationAddress(config.LINK_LOCAL_ALL_NODES_ADDRESS) + command_msg.assertSentToDestinationAddress( + config.LINK_LOCAL_ALL_NODES_ADDRESS + ) command_msg.assertMleMessageContainsTlv(mle.SourceAddress) command_msg.assertMleMessageContainsTlv(mle.LeaderData) command_msg.assertMleMessageContainsTlv(mle.Route64) + def check_parent_request(command_msg, is_first_request): """Verify a properly formatted Parent Request command message. """ if command_msg.mle.aux_sec_hdr.key_id_mode != 0x2: - raise ValueError("The Key Identifier Mode of the Security Control Field SHALL be set to 0x02") + raise ValueError( + "The Key Identifier Mode of the Security Control Field SHALL be set to 0x02" + ) command_msg.assertSentWithHopLimit(255) - command_msg.assertSentToDestinationAddress(config.LINK_LOCAL_ALL_ROUTERS_ADDRESS) + command_msg.assertSentToDestinationAddress( + config.LINK_LOCAL_ALL_ROUTERS_ADDRESS + ) command_msg.assertMleMessageContainsTlv(mle.Mode) command_msg.assertMleMessageContainsTlv(mle.Challenge) command_msg.assertMleMessageContainsTlv(mle.Version) @@ -273,7 +363,8 @@ def check_parent_request(command_msg, is_first_request): elif not scan_mask.end_device: raise ValueError("Second parent request without E bit set") -def check_parent_response(command_msg, mle_frame_counter = CheckType.OPTIONAL): + +def check_parent_response(command_msg, mle_frame_counter=CheckType.OPTIONAL): """Verify a properly formatted Parent Response command message. """ command_msg.assertMleMessageContainsTlv(mle.Challenge) @@ -287,14 +378,22 @@ def check_parent_response(command_msg, mle_frame_counter = CheckType.OPTIONAL): check_mle_optional_tlv(command_msg, mle_frame_counter, mle.MleFrameCounter) -def check_child_id_request(command_msg, tlv_request = CheckType.OPTIONAL, \ - mle_frame_counter = CheckType.OPTIONAL, address_registration = CheckType.OPTIONAL, \ - active_timestamp = CheckType.OPTIONAL, pending_timestamp = CheckType.OPTIONAL, - route64 = CheckType.OPTIONAL): + +def check_child_id_request( + command_msg, + tlv_request=CheckType.OPTIONAL, + mle_frame_counter=CheckType.OPTIONAL, + address_registration=CheckType.OPTIONAL, + active_timestamp=CheckType.OPTIONAL, + pending_timestamp=CheckType.OPTIONAL, + route64=CheckType.OPTIONAL, +): """Verify a properly formatted Child Id Request command message. """ if command_msg.mle.aux_sec_hdr.key_id_mode != 0x2: - raise ValueError("The Key Identifier Mode of the Security Control Field SHALL be set to 0x02") + raise ValueError( + "The Key Identifier Mode of the Security Control Field SHALL be set to 0x02" + ) command_msg.assertMleMessageContainsTlv(mle.LinkLayerFrameCounter) command_msg.assertMleMessageContainsTlv(mle.Mode) @@ -304,19 +403,34 @@ def check_child_id_request(command_msg, tlv_request = CheckType.OPTIONAL, \ check_mle_optional_tlv(command_msg, tlv_request, mle.TlvRequest) check_mle_optional_tlv(command_msg, mle_frame_counter, mle.MleFrameCounter) - check_mle_optional_tlv(command_msg, address_registration, mle.AddressRegistration) + check_mle_optional_tlv( + command_msg, address_registration, mle.AddressRegistration + ) check_mle_optional_tlv(command_msg, active_timestamp, mle.ActiveTimestamp) - check_mle_optional_tlv(command_msg, pending_timestamp, mle.PendingTimestamp) + check_mle_optional_tlv( + command_msg, pending_timestamp, mle.PendingTimestamp + ) check_mle_optional_tlv(command_msg, route64, mle.Route64) - check_tlv_request_tlv(command_msg, CheckType.CONTAIN, mle.TlvType.ADDRESS16) - check_tlv_request_tlv(command_msg, CheckType.CONTAIN, mle.TlvType.NETWORK_DATA) + check_tlv_request_tlv( + command_msg, CheckType.CONTAIN, mle.TlvType.ADDRESS16 + ) + check_tlv_request_tlv( + command_msg, CheckType.CONTAIN, mle.TlvType.NETWORK_DATA + ) -def check_child_id_response(command_msg, route64 = CheckType.OPTIONAL, network_data = CheckType.OPTIONAL, \ - address_registration = CheckType.OPTIONAL, active_timestamp = CheckType.OPTIONAL, \ - pending_timestamp = CheckType.OPTIONAL, active_operational_dataset = CheckType.OPTIONAL, \ - pending_operational_dataset = CheckType.OPTIONAL, - network_data_check = None): + +def check_child_id_response( + command_msg, + route64=CheckType.OPTIONAL, + network_data=CheckType.OPTIONAL, + address_registration=CheckType.OPTIONAL, + active_timestamp=CheckType.OPTIONAL, + pending_timestamp=CheckType.OPTIONAL, + active_operational_dataset=CheckType.OPTIONAL, + pending_operational_dataset=CheckType.OPTIONAL, + network_data_check=None, +): """Verify a properly formatted Child Id Response command message. """ command_msg.assertMleMessageContainsTlv(mle.SourceAddress) @@ -325,67 +439,105 @@ def check_child_id_response(command_msg, route64 = CheckType.OPTIONAL, network_d check_mle_optional_tlv(command_msg, route64, mle.Route64) check_mle_optional_tlv(command_msg, network_data, mle.NetworkData) - check_mle_optional_tlv(command_msg, address_registration, mle.AddressRegistration) + check_mle_optional_tlv( + command_msg, address_registration, mle.AddressRegistration + ) check_mle_optional_tlv(command_msg, active_timestamp, mle.ActiveTimestamp) - check_mle_optional_tlv(command_msg, pending_timestamp, mle.PendingTimestamp) - check_mle_optional_tlv(command_msg, active_operational_dataset, mle.ActiveOperationalDataset) - check_mle_optional_tlv(command_msg, pending_operational_dataset, mle.PendingOperationalDataset) + check_mle_optional_tlv( + command_msg, pending_timestamp, mle.PendingTimestamp + ) + check_mle_optional_tlv( + command_msg, active_operational_dataset, mle.ActiveOperationalDataset + ) + check_mle_optional_tlv( + command_msg, pending_operational_dataset, mle.PendingOperationalDataset + ) if network_data_check is not None: - network_data_tlv = command_msg.assertMleMessageContainsTlv(mle.NetworkData) + network_data_tlv = command_msg.assertMleMessageContainsTlv( + mle.NetworkData + ) network_data_check.check(network_data_tlv) + def check_prefix(prefix): """Verify if a prefix contains 6loWPAN sub-TLV and border router sub-TLV """ - assert contains_tlv(prefix.sub_tlvs, network_data.BorderRouter), 'Prefix doesn\'t contain a border router sub-TLV!' - assert contains_tlv(prefix.sub_tlvs, network_data.LowpanId), 'Prefix doesn\'t contain a LowpanId sub-TLV!' + assert contains_tlv( + prefix.sub_tlvs, network_data.BorderRouter + ), 'Prefix doesn\'t contain a border router sub-TLV!' + assert contains_tlv( + prefix.sub_tlvs, network_data.LowpanId + ), 'Prefix doesn\'t contain a LowpanId sub-TLV!' -def check_child_update_request_from_child(command_msg, source_address=CheckType.OPTIONAL, - leader_data=CheckType.OPTIONAL, challenge=CheckType.OPTIONAL, time_out=CheckType.OPTIONAL, - address_registration=CheckType.OPTIONAL, tlv_request_tlv=CheckType.OPTIONAL, - active_timestamp=CheckType.OPTIONAL, CIDs=[]): + +def check_child_update_request_from_child( + command_msg, + source_address=CheckType.OPTIONAL, + leader_data=CheckType.OPTIONAL, + challenge=CheckType.OPTIONAL, + time_out=CheckType.OPTIONAL, + address_registration=CheckType.OPTIONAL, + tlv_request_tlv=CheckType.OPTIONAL, + active_timestamp=CheckType.OPTIONAL, + CIDs=[], +): command_msg.assertMleMessageContainsTlv(mle.Mode) check_mle_optional_tlv(command_msg, source_address, mle.SourceAddress) check_mle_optional_tlv(command_msg, leader_data, mle.LeaderData) check_mle_optional_tlv(command_msg, challenge, mle.Challenge) check_mle_optional_tlv(command_msg, time_out, mle.Timeout) - check_mle_optional_tlv(command_msg, address_registration, mle.AddressRegistration) + check_mle_optional_tlv( + command_msg, address_registration, mle.AddressRegistration + ) check_mle_optional_tlv(command_msg, tlv_request_tlv, mle.TlvRequest) check_mle_optional_tlv(command_msg, active_timestamp, mle.ActiveTimestamp) if (address_registration == CheckType.CONTAIN) and len(CIDs) > 0: _check_address_registration(command_msg, CIDs) + def check_coap_optional_tlv(coap_msg, type, tlv): - if (type == CheckType.CONTAIN): + if type == CheckType.CONTAIN: coap_msg.assertCoapMessageContainsTlv(tlv) - elif (type == CheckType.NOT_CONTAIN): + elif type == CheckType.NOT_CONTAIN: coap_msg.assertCoapMessageDoesNotContainTlv(tlv) - elif (type == CheckType.OPTIONAL): + elif type == CheckType.OPTIONAL: coap_msg.assertCoapMessageContainsOptionalTlv(tlv) else: raise ValueError("Invalid check type") -def check_router_id_cached(node, router_id, cached = True): + +def check_router_id_cached(node, router_id, cached=True): """Verify if the node has cached any entries based on the router ID """ eidcaches = node.get_eidcaches() if cached: - assert any(router_id == (int(rloc, 16) >> 10) for (_, rloc) in eidcaches) + assert any( + router_id == (int(rloc, 16) >> 10) for (_, rloc) in eidcaches + ) else: - assert any(router_id == (int(rloc, 16) >> 10) for (_, rloc) in eidcaches) is False + assert ( + any(router_id == (int(rloc, 16) >> 10) for (_, rloc) in eidcaches) + is False + ) + def contains_tlv(sub_tlvs, tlv_type): """Verify if a specific type of tlv is included in a sub-tlv list. """ return any(isinstance(sub_tlv, tlv_type) for sub_tlv in sub_tlvs) + def contains_tlvs(sub_tlvs, tlv_types): """Verify if all types of tlv in a list are included in a sub-tlv list. """ - return all((any(isinstance(sub_tlv, tlv_type) for sub_tlv in sub_tlvs)) for tlv_type in tlv_types) + return all( + (any(isinstance(sub_tlv, tlv_type) for sub_tlv in sub_tlvs)) + for tlv_type in tlv_types + ) + def check_secure_mle_key_id_mode(command_msg, key_id_mode): """Verify if the mle command message sets the right key id mode. @@ -393,7 +545,10 @@ def check_secure_mle_key_id_mode(command_msg, key_id_mode): assert isinstance(command_msg.mle, mle.MleMessageSecured) assert command_msg.mle.aux_sec_hdr.key_id_mode == key_id_mode -def check_data_response(command_msg, network_data_check=None, active_timestamp=CheckType.OPTIONAL): + +def check_data_response( + command_msg, network_data_check=None, active_timestamp=CheckType.OPTIONAL +): """Verify a properly formatted Data Response command message. """ check_secure_mle_key_id_mode(command_msg, 0x02) @@ -401,12 +556,20 @@ def check_data_response(command_msg, network_data_check=None, active_timestamp=C command_msg.assertMleMessageContainsTlv(mle.LeaderData) check_mle_optional_tlv(command_msg, active_timestamp, mle.ActiveTimestamp) if network_data_check is not None: - network_data_tlv = command_msg.assertMleMessageContainsTlv(mle.NetworkData) + network_data_tlv = command_msg.assertMleMessageContainsTlv( + mle.NetworkData + ) network_data_check.check(network_data_tlv) -def check_child_update_request_from_parent(command_msg, leader_data=CheckType.OPTIONAL, - network_data=CheckType.OPTIONAL, challenge=CheckType.OPTIONAL, - tlv_request=CheckType.OPTIONAL, active_timestamp=CheckType.OPTIONAL): + +def check_child_update_request_from_parent( + command_msg, + leader_data=CheckType.OPTIONAL, + network_data=CheckType.OPTIONAL, + challenge=CheckType.OPTIONAL, + tlv_request=CheckType.OPTIONAL, + active_timestamp=CheckType.OPTIONAL, +): """Verify a properly formatted Child Update Request(from parent) command message. """ check_secure_mle_key_id_mode(command_msg, 0x02) @@ -418,10 +581,19 @@ def check_child_update_request_from_parent(command_msg, leader_data=CheckType.OP check_mle_optional_tlv(command_msg, tlv_request, mle.TlvRequest) check_mle_optional_tlv(command_msg, active_timestamp, mle.ActiveTimestamp) -def check_child_update_response(command_msg, timeout=CheckType.OPTIONAL, - address_registration=CheckType.OPTIONAL, address16=CheckType.OPTIONAL, - leader_data=CheckType.OPTIONAL, network_data=CheckType.OPTIONAL, response=CheckType.OPTIONAL, - link_layer_frame_counter=CheckType.OPTIONAL, mle_frame_counter=CheckType.OPTIONAL, CIDs=[]): + +def check_child_update_response( + command_msg, + timeout=CheckType.OPTIONAL, + address_registration=CheckType.OPTIONAL, + address16=CheckType.OPTIONAL, + leader_data=CheckType.OPTIONAL, + network_data=CheckType.OPTIONAL, + response=CheckType.OPTIONAL, + link_layer_frame_counter=CheckType.OPTIONAL, + mle_frame_counter=CheckType.OPTIONAL, + CIDs=[], +): """Verify a properly formatted Child Update Response from parent """ check_secure_mle_key_id_mode(command_msg, 0x02) @@ -429,37 +601,51 @@ def check_child_update_response(command_msg, timeout=CheckType.OPTIONAL, command_msg.assertMleMessageContainsTlv(mle.SourceAddress) command_msg.assertMleMessageContainsTlv(mle.Mode) check_mle_optional_tlv(command_msg, timeout, mle.Timeout) - check_mle_optional_tlv(command_msg, address_registration, mle.AddressRegistration) + check_mle_optional_tlv( + command_msg, address_registration, mle.AddressRegistration + ) check_mle_optional_tlv(command_msg, address16, mle.Address16) check_mle_optional_tlv(command_msg, leader_data, mle.LeaderData) check_mle_optional_tlv(command_msg, network_data, mle.NetworkData) check_mle_optional_tlv(command_msg, response, mle.Response) - check_mle_optional_tlv(command_msg, link_layer_frame_counter, mle.LinkLayerFrameCounter) + check_mle_optional_tlv( + command_msg, link_layer_frame_counter, mle.LinkLayerFrameCounter + ) check_mle_optional_tlv(command_msg, mle_frame_counter, mle.MleFrameCounter) if (address_registration == CheckType.CONTAIN) and len(CIDs) > 0: _check_address_registration(command_msg, CIDs) + def _check_address_registration(command_msg, CIDs=[]): - addresses = command_msg.assertMleMessageContainsTlv(mle.AddressRegistration).addresses - for cid in CIDs: - found = False - for address in addresses: - if isinstance(address, mle.AddressCompressed): - if cid == address.cid: - found = True - break - assert found, "AddressRegistration TLV doesn't have CID {} ".format(cid) + addresses = command_msg.assertMleMessageContainsTlv( + mle.AddressRegistration + ).addresses + for cid in CIDs: + found = False + for address in addresses: + if isinstance(address, mle.AddressCompressed): + if cid == address.cid: + found = True + break + assert found, "AddressRegistration TLV doesn't have CID {} ".format( + cid + ) + def get_sub_tlv(tlvs, tlv_type): for sub_tlv in tlvs: if isinstance(sub_tlv, tlv_type): return sub_tlv + def check_address_registration_tlv(addr_reg_tlv, address_set): """Verify all addresses contained in address_set are contained in add_reg_tlv """ - assert all(addr in addr_reg_tlv.addresses for addr in address_set), 'Some addresses are not included in AddressRegistration TLV' + assert all( + addr in addr_reg_tlv.addresses for addr in address_set + ), 'Some addresses are not included in AddressRegistration TLV' + def assert_contains_tlv(tlvs, check_type, tlv_type): """Assert a tlv list contains specific tlv and return the first qualified. @@ -476,39 +662,55 @@ def assert_contains_tlv(tlvs, check_type, tlv_type): else: raise ValueError("Invalid check type: {}".format(check_type)) + def check_discovery_request(command_msg): """Verify a properly formatted Thread Discovery Request command message. """ assert not isinstance(command_msg.mle, mle.MleMessageSecured) tlvs = command_msg.assertMleMessageContainsTlv(mle.ThreadDiscovery).tlvs - request = assert_contains_tlv(tlvs, CheckType.CONTAIN, mesh_cop.DiscoveryRequest) + request = assert_contains_tlv( + tlvs, CheckType.CONTAIN, mesh_cop.DiscoveryRequest + ) assert request.version == config.PROTOCOL_VERSION -def check_discovery_response(command_msg, request_src_addr, steering_data=CheckType.OPTIONAL): + +def check_discovery_response( + command_msg, request_src_addr, steering_data=CheckType.OPTIONAL +): """Verify a properly formatted Thread Discovery Response command message. """ assert not isinstance(command_msg.mle, mle.MleMessageSecured) - assert command_msg.mac_header.src_address.type == common.MacAddressType.LONG + assert ( + command_msg.mac_header.src_address.type == common.MacAddressType.LONG + ) assert command_msg.mac_header.dest_address == request_src_addr tlvs = command_msg.assertMleMessageContainsTlv(mle.ThreadDiscovery).tlvs - response = assert_contains_tlv(tlvs, CheckType.CONTAIN, mesh_cop.DiscoveryResponse) + response = assert_contains_tlv( + tlvs, CheckType.CONTAIN, mesh_cop.DiscoveryResponse + ) assert response.version == config.PROTOCOL_VERSION assert_contains_tlv(tlvs, CheckType.CONTAIN, mesh_cop.ExtendedPanid) assert_contains_tlv(tlvs, CheckType.CONTAIN, mesh_cop.NetworkName) assert_contains_tlv(tlvs, steering_data, mesh_cop.SteeringData) assert_contains_tlv(tlvs, steering_data, mesh_cop.JoinerUdpPort) - check_type = CheckType.CONTAIN if response.native_flag else CheckType.OPTIONAL + check_type = ( + CheckType.CONTAIN if response.native_flag else CheckType.OPTIONAL + ) assert_contains_tlv(tlvs, check_type, mesh_cop.CommissionerUdpPort) + def get_joiner_udp_port_in_discovery_response(command_msg): """Get the udp port specified in a DISCOVERY RESPONSE message """ tlvs = command_msg.assertMleMessageContainsTlv(mle.ThreadDiscovery).tlvs - udp_port_tlv = assert_contains_tlv(tlvs, CheckType.CONTAIN, mesh_cop.JoinerUdpPort) + udp_port_tlv = assert_contains_tlv( + tlvs, CheckType.CONTAIN, mesh_cop.JoinerUdpPort + ) return udp_port_tlv.udp_port + def check_joiner_commissioning_messages(commissioning_messages): """Verify COAP messages sent by joiner while commissioning process. """ @@ -516,21 +718,32 @@ def check_joiner_commissioning_messages(commissioning_messages): assert len(commissioning_messages) >= 2 join_fin_req = commissioning_messages[0] assert join_fin_req.type == mesh_cop.MeshCopMessageType.JOIN_FIN_REQ - assert_contains_tlv(join_fin_req.tlvs, CheckType.NOT_CONTAIN, mesh_cop.ProvisioningUrl) + assert_contains_tlv( + join_fin_req.tlvs, CheckType.NOT_CONTAIN, mesh_cop.ProvisioningUrl + ) join_ent_rsp = commissioning_messages[1] assert join_ent_rsp.type == mesh_cop.MeshCopMessageType.JOIN_ENT_RSP + def check_commissioner_commissioning_messages(commissioning_messages): """Verify COAP messages sent by commissioner while commissioning process. """ - assert any(msg.type == mesh_cop.MeshCopMessageType.JOIN_FIN_RSP for msg in commissioning_messages) + assert any( + msg.type == mesh_cop.MeshCopMessageType.JOIN_FIN_RSP + for msg in commissioning_messages + ) + def check_joiner_router_commissioning_messages(commissioning_messages): """Verify COAP messages sent by joiner router while commissioning process. """ - assert any(msg.type == mesh_cop.MeshCopMessageType.JOIN_ENT_NTF for msg in commissioning_messages) + assert any( + msg.type == mesh_cop.MeshCopMessageType.JOIN_ENT_NTF + for msg in commissioning_messages + ) return None + def check_payload_same(tp1, tp2): """Verfiy two payloads are totally the same. A payload is a tuple of tlvs. @@ -538,7 +751,10 @@ def check_payload_same(tp1, tp2): assert len(tp1) == len(tp2) for tlv in tp2: peer_tlv = get_sub_tlv(tp1, type(tlv)) - assert peer_tlv is not None and peer_tlv == tlv, 'peer_tlv:{}, tlv:{} type:{}'.format(peer_tlv, tlv, type(tlv)) + assert ( + peer_tlv is not None and peer_tlv == tlv + ), 'peer_tlv:{}, tlv:{} type:{}'.format(peer_tlv, tlv, type(tlv)) + def check_coap_message(msg, payloads, dest_addrs=None): if dest_addrs is not None: @@ -550,25 +766,30 @@ def check_coap_message(msg, payloads, dest_addrs=None): assert found, 'Destination address incorrect' check_payload_same(msg.coap.payload, payloads) -class SinglePrefixCheck: +class SinglePrefixCheck: def __init__(self, prefix=None, border_router_16=None): self._prefix = prefix self._border_router_16 = border_router_16 def check(self, prefix_tlv): - border_router_tlv = assert_contains_tlv(prefix_tlv.sub_tlvs, CheckType.CONTAIN, network_data.BorderRouter) - lowpan_id_tlv = assert_contains_tlv(prefix_tlv.sub_tlvs, CheckType.CONTAIN, network_data.LowpanId) + border_router_tlv = assert_contains_tlv( + prefix_tlv.sub_tlvs, CheckType.CONTAIN, network_data.BorderRouter + ) + assert_contains_tlv( + prefix_tlv.sub_tlvs, CheckType.CONTAIN, network_data.LowpanId + ) result = True if self._prefix is not None: - result &= (self._prefix == binascii.hexlify(prefix_tlv.prefix)) + result &= self._prefix == binascii.hexlify(prefix_tlv.prefix) if self._border_router_16 is not None: - result &= (self._border_router_16 == border_router_tlv.border_router_16) + result &= ( + self._border_router_16 == border_router_tlv.border_router_16 + ) return result class PrefixesCheck: - def __init__(self, prefix_cnt=0, prefix_check_list=[]): self._prefix_cnt = prefix_cnt self._prefix_check_list = prefix_check_list @@ -576,7 +797,9 @@ class PrefixesCheck: def check(self, prefix_tlvs): # if prefix_cnt is given, then check count only if self._prefix_cnt > 0: - assert len(prefix_tlvs) >= self._prefix_cnt, 'prefix count is less than expected' + assert ( + len(prefix_tlvs) >= self._prefix_cnt + ), 'prefix count is less than expected' else: for prefix_check in self._prefix_check_list: found = False @@ -588,28 +811,37 @@ class PrefixesCheck: class CommissioningDataCheck: - def __init__(self, stable=None, sub_tlv_type_list=[]): self._stable = stable self._sub_tlv_type_list = sub_tlv_type_list def check(self, commissioning_data_tlv): if self._stable is not None: - assert self._stable == commissioning_data_tlv.stable, 'Commissioning Data stable flag is not correct' - assert contains_tlvs(commissioning_data_tlv.sub_tlvs, self._sub_tlv_type_list), 'Some sub tlvs are missing in Commissioning Data' + assert ( + self._stable == commissioning_data_tlv.stable + ), 'Commissioning Data stable flag is not correct' + assert contains_tlvs( + commissioning_data_tlv.sub_tlvs, self._sub_tlv_type_list + ), 'Some sub tlvs are missing in Commissioning Data' class NetworkDataCheck: - def __init__(self, prefixes_check=None, commissioning_data_check=None): self._prefixes_check = prefixes_check self._commissioning_data_check = commissioning_data_check def check(self, network_data_tlv): if self._prefixes_check is not None: - prefix_tlvs = [tlv for tlv in network_data_tlv.tlvs if isinstance(tlv, network_data.Prefix)] + prefix_tlvs = [ + tlv + for tlv in network_data_tlv.tlvs + if isinstance(tlv, network_data.Prefix) + ] self._prefixes_check.check(prefix_tlvs) if self._commissioning_data_check is not None: - commissioning_data_tlv = assert_contains_tlv(network_data_tlv.tlvs, CheckType.CONTAIN, network_data.CommissioningData) + commissioning_data_tlv = assert_contains_tlv( + network_data_tlv.tlvs, + CheckType.CONTAIN, + network_data.CommissioningData, + ) self._commissioning_data_check.check(commissioning_data_tlv) - diff --git a/tests/scripts/thread-cert/common.py b/tests/scripts/thread-cert/common.py index 77cb0e585..b3bc5a470 100644 --- a/tests/scripts/thread-cert/common.py +++ b/tests/scripts/thread-cert/common.py @@ -38,11 +38,14 @@ import ipaddress def expect_the_same_class(self, other): if not isinstance(other, self.__class__): - raise TypeError("Expected the same class. Got {} and {}".format(type(self), type(other))) + raise TypeError( + "Expected the same class. Got {} and {}".format( + type(self), type(other) + ) + ) class MessageInfo(object): - def __init__(self): self.aux_sec_hdr = None self.aux_sec_hdr_bytes = None @@ -110,7 +113,6 @@ class MacAddressType(IntEnum): class MacAddress(object): - def __init__(self, mac_address, _type, big_endian=True): if _type == MacAddressType.SHORT: length = 2 @@ -137,16 +139,26 @@ class MacAddress(object): def convert_to_iid(self): if self._type == MacAddressType.SHORT: - return bytearray([0x00, 0x00, 0x00, 0xff, 0xfe, 0x00]) + self._mac_address[:2] + return ( + bytearray([0x00, 0x00, 0x00, 0xff, 0xfe, 0x00]) + + self._mac_address[:2] + ) elif self._type == MacAddressType.LONG: - return bytearray([self._mac_address[0] ^ 0x02]) + self._mac_address[1:] + return ( + bytearray([self._mac_address[0] ^ 0x02]) + + self._mac_address[1:] + ) else: - raise RuntimeError("Could not convert to IID. Invalid MAC address type: {}".format(self._type)) + raise RuntimeError( + "Could not convert to IID. Invalid MAC address type: {}".format( + self._type)) @classmethod def from_eui64(cls, eui64, big_endian=True): if not isinstance(eui64, bytearray): - raise RuntimeError("Could not create MAC address from EUI64. Invalid data type: {}".format(type(eui64))) + raise RuntimeError( + "Could not create MAC address from EUI64. Invalid data type: {}".format( + type(eui64))) return cls(eui64, MacAddressType.LONG) @@ -157,12 +169,18 @@ class MacAddress(object): elif isinstance(rloc16, bytearray): mac_address = rloc16[:2] else: - raise RuntimeError("Could not create MAC address from RLOC16. Invalid data type: {}".format(type(rloc16))) + raise RuntimeError( + "Could not create MAC address from RLOC16. Invalid data type: {}".format( + type(rloc16))) return cls(mac_address, MacAddressType.SHORT) def __eq__(self, other): - return (self.type == other.type) and (self.mac_address == other.mac_address) + return (self.type == other.type) and ( + self.mac_address == other.mac_address + ) def __repr__(self): - return "MacAddress(mac_address=b'{}', type={})".format(hexlify(self.mac_address), MacAddressType(self._type)) + return "MacAddress(mac_address=b'{}', type={})".format( + hexlify(self.mac_address), MacAddressType(self._type) + ) diff --git a/tests/scripts/thread-cert/config.py b/tests/scripts/thread-cert/config.py index dd9323516..e6a49019a 100644 --- a/tests/scripts/thread-cert/config.py +++ b/tests/scripts/thread-cert/config.py @@ -46,7 +46,7 @@ import sniffer MESH_LOCAL_PREFIX = 'fdde:ad00:beef::/64' MESH_LOCAL_PREFIX_REGEX_PATTERN = '^fdde:ad00:beef:(0){0,4}:' ROUTING_LOCATOR = '64/:0:ff:fe00:/16' -ROUTING_LOCATOR_REGEX_PATTERN = '.*:(0)?:0{0,2}ff:fe00:\w{1,4}$' +ROUTING_LOCATOR_REGEX_PATTERN = r'.*:(0)?:0{0,2}ff:fe00:\w{1,4}$' LINK_LOCAL = 'fe80:/112' LINK_LOCAL_REGEX_PATTERN = '^fe80:.*' ALOC_FLAG_REGEX_PATTERN = '.*:fc..$' @@ -56,11 +56,36 @@ REALM_LOCAL_ALL_ROUTERS_ADDRESS = 'ff03::2' LINK_LOCAL_ALL_NODES_ADDRESS = 'ff02::1' LINK_LOCAL_ALL_ROUTERS_ADDRESS = 'ff02::2' -DEFAULT_MASTER_KEY = bytearray([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]) +DEFAULT_MASTER_KEY = bytearray( + [ + 0x00, + 0x11, + 0x22, + 0x33, + 0x44, + 0x55, + 0x66, + 0x77, + 0x88, + 0x99, + 0xaa, + 0xbb, + 0xcc, + 0xdd, + 0xee, + 0xff, + ] +) -ADDRESS_TYPE = Enum('ADDRESS_TYPE', ('LINK_LOCAL', 'GLOBAL', 'RLOC', 'ALOC', 'ML_EID')) -RSSI = {'LINK_QULITY_0': -100, 'LINK_QULITY_1': -95, 'LINK_QULITY_2': -85, 'LINK_QULITY_3': -65} +ADDRESS_TYPE = Enum( + 'ADDRESS_TYPE', ('LINK_LOCAL', 'GLOBAL', 'RLOC', 'ALOC', 'ML_EID') +) +RSSI = { + 'LINK_QULITY_0': -100, + 'LINK_QULITY_1': -95, + 'LINK_QULITY_2': -85, + 'LINK_QULITY_3': -65, +} SNIFFER_ID = int(os.getenv('SNIFFER_ID', 34)) PANID = 0xface @@ -80,14 +105,16 @@ LEADER_NOTIFY_SED_BY_CHILD_UPDATE_REQUEST = True PROTOCOL_VERSION = 2 + def create_default_network_data_prefix_sub_tlvs_factories(): return { network_data.TlvType.HAS_ROUTE: network_data.HasRouteFactory( routes_factory=network_data.RoutesFactory( - route_factory=network_data.RouteFactory()) + route_factory=network_data.RouteFactory() + ) ), network_data.TlvType.BORDER_ROUTER: network_data.BorderRouterFactory(), - network_data.TlvType.LOWPAN_ID: network_data.LowpanIdFactory() + network_data.TlvType.LOWPAN_ID: network_data.LowpanIdFactory(), } @@ -97,9 +124,7 @@ def create_default_network_data_prefix_sub_tlvs_factory(): def create_default_network_data_service_sub_tlvs_factories(): - return { - network_data.TlvType.SERVER: network_data.ServerFactory() - } + return {network_data.TlvType.SERVER: network_data.ServerFactory()} def create_default_network_data_service_sub_tlvs_factory(): @@ -138,7 +163,8 @@ def create_default_network_data_tlvs_factories(): def create_default_network_data_tlvs_factory(): return network_data.NetworkDataTlvsFactory( - sub_tlvs_factories=create_default_network_data_tlvs_factories()) + sub_tlvs_factories=create_default_network_data_tlvs_factories() + ) def create_default_mle_tlv_route64_factory(): @@ -148,21 +174,27 @@ def create_default_mle_tlv_route64_factory(): def create_default_mle_tlv_network_data_factory(): return mle.NetworkDataFactory( - network_data_tlvs_factory=create_default_network_data_tlvs_factory()) + network_data_tlvs_factory=create_default_network_data_tlvs_factory() + ) def create_default_mle_tlv_address_registration_factory(): return mle.AddressRegistrationFactory( addr_compressed_factory=mle.AddressCompressedFactory(), - addr_full_factory=mle.AddressFullFactory()) + addr_full_factory=mle.AddressFullFactory(), + ) + def create_default_mle_tlv_thread_discovery_factory(): return mle.ThreadDiscoveryFactory( thread_discovery_tlvs_factory=create_default_thread_discovery_tlvs_factory()) + def create_default_thread_discovery_tlvs_factory(): return mesh_cop.ThreadDiscoveryTlvsFactory( - sub_tlvs_factories=create_default_thread_discovery_sub_tlvs_factories()) + sub_tlvs_factories=create_default_thread_discovery_sub_tlvs_factories() + ) + def create_default_thread_discovery_sub_tlvs_factories(): return { @@ -172,9 +204,10 @@ def create_default_thread_discovery_sub_tlvs_factories(): mesh_cop.TlvType.NETWORK_NAME: mesh_cop.NetworkNameFactory(), mesh_cop.TlvType.STEERING_DATA: mesh_cop.SteeringDataFactory(), mesh_cop.TlvType.JOINER_UDP_PORT: mesh_cop.JoinerUdpPortFactory(), - mesh_cop.TlvType.COMMISSIONER_UDP_PORT: mesh_cop.CommissionerUdpPortFactory() + mesh_cop.TlvType.COMMISSIONER_UDP_PORT: mesh_cop.CommissionerUdpPortFactory(), } + def create_default_mle_tlvs_factories(): return { mle.TlvType.SOURCE_ADDRESS: mle.SourceAddressFactory(), @@ -203,20 +236,24 @@ def create_default_mle_tlvs_factories(): mle.TlvType.PENDING_OPERATIONAL_DATASET: mle.PendingOperationalDatasetFactory(), mle.TlvType.TIME_REQUEST: mle.TimeRequestFactory(), mle.TlvType.TIME_PARAMETER: mle.TimeParameterFactory(), - mle.TlvType.THREAD_DISCOVERY: create_default_mle_tlv_thread_discovery_factory() + mle.TlvType.THREAD_DISCOVERY: create_default_mle_tlv_thread_discovery_factory(), } def create_default_mle_crypto_engine(master_key): - return net_crypto.CryptoEngine(crypto_material_creator=net_crypto.MleCryptoMaterialCreator(master_key)) + return net_crypto.CryptoEngine( + crypto_material_creator=net_crypto.MleCryptoMaterialCreator(master_key) + ) def create_default_mle_message_factory(master_key): return mle.MleMessageFactory( aux_sec_hdr_factory=net_crypto.AuxiliarySecurityHeaderFactory(), mle_command_factory=mle.MleCommandFactory( - tlvs_factories=create_default_mle_tlvs_factories()), - crypto_engine=create_default_mle_crypto_engine(master_key)) + tlvs_factories=create_default_mle_tlvs_factories() + ), + crypto_engine=create_default_mle_crypto_engine(master_key), + ) def create_deafult_network_tlvs_factories(): @@ -230,17 +267,21 @@ def create_deafult_network_tlvs_factories(): network_layer.TlvType.ROUTER_MASK: network_layer.RouterMaskFactory(), network_layer.TlvType.ND_OPTION: network_layer.NdOptionFactory(), network_layer.TlvType.ND_DATA: network_layer.NdDataFactory(), - network_layer.TlvType.THREAD_NETWORK_DATA: network_layer.ThreadNetworkDataFactory(create_default_network_data_tlvs_factory()), + network_layer.TlvType.THREAD_NETWORK_DATA: network_layer.ThreadNetworkDataFactory( + create_default_network_data_tlvs_factory() + ), network_layer.TlvType.XTAL_ACCURACY: network_layer.XtalAccuracyFactory(), - # Routing information are distributed in a Thread network by MLE Routing TLV # which is in fact MLE Route64 TLV. Thread specificaton v1.1. - Chapter 5.20 - network_layer.TlvType.MLE_ROUTING: create_default_mle_tlv_route64_factory() + network_layer.TlvType.MLE_ROUTING: create_default_mle_tlv_route64_factory(), } def create_default_network_tlvs_factory(): - return SubTlvsFactory(sub_tlvs_factories=create_deafult_network_tlvs_factories()) + return SubTlvsFactory( + sub_tlvs_factories=create_deafult_network_tlvs_factories() + ) + def create_default_mesh_cop_tlvs_factories(): return { @@ -280,11 +321,15 @@ def create_default_mesh_cop_tlvs_factories(): mesh_cop.TlvType.COUNT: mesh_cop.CountFactory(), mesh_cop.TlvType.PERIOD: mesh_cop.PeriodFactory(), mesh_cop.TlvType.SCAN_DURATION: mesh_cop.ScanDurationFactory(), - mesh_cop.TlvType.ENERGY_LIST: mesh_cop.EnergyListFactory() + mesh_cop.TlvType.ENERGY_LIST: mesh_cop.EnergyListFactory(), } + def create_default_mesh_cop_tlvs_factory(): - return SubTlvsFactory(sub_tlvs_factories=create_default_mesh_cop_tlvs_factories()) + return SubTlvsFactory( + sub_tlvs_factories=create_default_mesh_cop_tlvs_factories() + ) + def create_default_uri_path_based_payload_factories(): network_layer_tlvs_factory = create_default_network_tlvs_factory() @@ -297,25 +342,26 @@ def create_default_uri_path_based_payload_factories(): "/a/an": network_layer_tlvs_factory, "/a/sd": network_layer_tlvs_factory, "/c/lp": mesh_cop_tlvs_factory, - "/c/cs": mesh_cop_tlvs_factory + "/c/cs": mesh_cop_tlvs_factory, } def create_default_coap_message_factory(): - return coap.CoapMessageFactory(options_factory=coap.CoapOptionsFactory(), - uri_path_based_payload_factories=create_default_uri_path_based_payload_factories(), - message_id_to_uri_path_binder=coap.CoapMessageIdToUriPathBinder()) + return coap.CoapMessageFactory( + options_factory=coap.CoapOptionsFactory(), + uri_path_based_payload_factories=create_default_uri_path_based_payload_factories(), + message_id_to_uri_path_binder=coap.CoapMessageIdToUriPathBinder(), + ) def create_default_ipv6_hop_by_hop_options_factories(): - return { - 109: ipv6.MPLOptionFactory() - } + return {109: ipv6.MPLOptionFactory()} def create_default_ipv6_hop_by_hop_options_factory(): return ipv6.HopByHopOptionsFactory( - options_factories=create_default_ipv6_hop_by_hop_options_factories()) + options_factories=create_default_ipv6_hop_by_hop_options_factories() + ) def create_default_based_on_src_dst_ports_udp_payload_factory(master_key): @@ -327,7 +373,7 @@ def create_default_based_on_src_dst_ports_udp_payload_factory(master_key): src_dst_port_based_payload_factories={ 19788: mle_message_factory, 61631: coap_message_factory, - 1000: dtls_message_factory + 1000: dtls_message_factory, } ) @@ -341,7 +387,7 @@ def create_default_ipv6_icmp_body_factories(): ipv6.ICMP_DESTINATION_UNREACHABLE: ipv6.ICMPv6DestinationUnreachableFactory(), ipv6.ICMP_ECHO_REQUEST: ipv6.ICMPv6EchoBodyFactory(), ipv6.ICMP_ECHO_RESPONSE: ipv6.ICMPv6EchoBodyFactory(), - "default": ipv6.BytesPayloadFactory() + "default": ipv6.BytesPayloadFactory(), } @@ -349,33 +395,30 @@ def create_default_ipv6_upper_layer_factories(master_key): return { ipv6.IPV6_NEXT_HEADER_UDP: ipv6.UDPDatagramFactory( udp_header_factory=ipv6.UDPHeaderFactory(), - udp_payload_factory=create_default_based_on_src_dst_ports_udp_payload_factory(master_key) + udp_payload_factory=create_default_based_on_src_dst_ports_udp_payload_factory( + master_key + ), ), ipv6.IPV6_NEXT_HEADER_ICMP: ipv6.ICMPv6Factory( body_factories=create_default_ipv6_icmp_body_factories() - ) + ), } def create_default_lowpan_extension_headers_factories(): - return { - ipv6.IPV6_NEXT_HEADER_HOP_BY_HOP: lowpan.LowpanHopByHopFactory( - hop_by_hop_options_factory=create_default_ipv6_hop_by_hop_options_factory() - ) - } + return {ipv6.IPV6_NEXT_HEADER_HOP_BY_HOP: lowpan.LowpanHopByHopFactory( + hop_by_hop_options_factory=create_default_ipv6_hop_by_hop_options_factory())} def create_default_ipv6_extension_headers_factories(): - return { - ipv6.IPV6_NEXT_HEADER_HOP_BY_HOP: ipv6.HopByHopFactory( - hop_by_hop_options_factory=create_default_ipv6_hop_by_hop_options_factory()) - } + return {ipv6.IPV6_NEXT_HEADER_HOP_BY_HOP: ipv6.HopByHopFactory( + hop_by_hop_options_factory=create_default_ipv6_hop_by_hop_options_factory())} def create_default_ipv6_packet_factory(master_key): return ipv6.IPv6PacketFactory( ehf=create_default_ipv6_extension_headers_factories(), - ulpf=create_default_ipv6_upper_layer_factories(master_key) + ulpf=create_default_ipv6_upper_layer_factories(master_key), ) @@ -387,7 +430,7 @@ def create_default_lowpan_decompressor(context_manager): lowpan_extension_headers_factory=lowpan.LowpanExtensionHeadersFactory( ext_headers_factories=create_default_lowpan_extension_headers_factories() ), - lowpan_udp_header_factory=lowpan.LowpanUdpHeaderFactory() + lowpan_udp_header_factory=lowpan.LowpanUdpHeaderFactory(), ) @@ -398,12 +441,14 @@ def create_default_thread_context_manager(): return context_manager -def create_default_lowpan_parser(context_manager, master_key=DEFAULT_MASTER_KEY): +def create_default_lowpan_parser( + context_manager, master_key=DEFAULT_MASTER_KEY +): return lowpan.LowpanParser( lowpan_mesh_header_factory=lowpan.LowpanMeshHeaderFactory(), lowpan_decompressor=create_default_lowpan_decompressor(context_manager), lowpan_fragements_buffers_manager=lowpan.LowpanFragmentsBuffersManager(), - ipv6_packet_factory=create_default_ipv6_packet_factory(master_key) + ipv6_packet_factory=create_default_ipv6_packet_factory(master_key), ) diff --git a/tests/scripts/thread-cert/debug.py b/tests/scripts/thread-cert/debug.py index 0d70593a4..edd609b96 100644 --- a/tests/scripts/thread-cert/debug.py +++ b/tests/scripts/thread-cert/debug.py @@ -27,6 +27,10 @@ # POSSIBILITY OF SUCH DAMAGE. # + +from builtins import input + + class Inspector: """This class provides a way to inspect node status of a test case. @@ -71,7 +75,7 @@ class Inspector: """ node = self.test_case.nodes[nodeid] while True: - line = raw_input('> ') + line = input('> ') if not line: continue @@ -85,7 +89,7 @@ class Inspector: """ Start inspecting. """ while True: - line = raw_input('# ') + line = input('# ') if not line: continue diff --git a/tests/scripts/thread-cert/dtls.py b/tests/scripts/thread-cert/dtls.py index 44d0ef01c..8a86b34a6 100644 --- a/tests/scripts/thread-cert/dtls.py +++ b/tests/scripts/thread-cert/dtls.py @@ -27,11 +27,9 @@ # POSSIBILITY OF SUCH DAMAGE. # -from binascii import hexlify from enum import IntEnum from functools import reduce import io -import math import struct from ipv6 import BuildableFromBytes @@ -93,9 +91,9 @@ class AlertDescription(IntEnum): class Record(ConvertibleToBytes, BuildableFromBytes): - - def __init__(self, content_type, version, epoch, - sequence_number, length, fragment): + def __init__( + self, content_type, version, epoch, sequence_number, length, fragment + ): self.content_type = content_type self.version = version self.epoch = epoch @@ -104,12 +102,14 @@ class Record(ConvertibleToBytes, BuildableFromBytes): self.fragment = fragment def to_bytes(self): - return (struct.pack(">B", self.content_type) + - self.version.to_bytes() + - struct.pack(">H", self.epoch) + - self.sequence_number.to_bytes(6, byteorder='big') + - struct.pack(">H", self.length) + - self.fragment) + return ( + struct.pack(">B", self.content_type) + + self.version.to_bytes() + + struct.pack(">H", self.epoch) + + self.sequence_number.to_bytes(6, byteorder='big') + + struct.pack(">H", self.length) + + self.fragment + ) @classmethod def from_bytes(cls, data): @@ -119,15 +119,16 @@ class Record(ConvertibleToBytes, BuildableFromBytes): sequence_number = struct.unpack(">Q", b'\x00\x00' + data.read(6))[0] length = struct.unpack(">H", data.read(2))[0] fragment = bytes(data.read(length)) - return cls(content_type, version, epoch, sequence_number, length, fragment) + return cls( + content_type, version, epoch, sequence_number, length, fragment + ) def __repr__(self): return "Record(content_type={}, version={}, epoch={}, sequence_number={}, length={})".format( - str(self.content_type), self.version, self.epoch, self.sequence_number, self.length) + str(self.content_type), self.version, self.epoch, self.sequence_number, self.length, ) class Message(ConvertibleToBytes, BuildableFromBytes): - def __init__(self, content_type): self.content_type = content_type @@ -140,9 +141,15 @@ class Message(ConvertibleToBytes, BuildableFromBytes): class HandshakeMessage(Message): - - def __init__(self, handshake_type, length, message_seq, - fragment_offset, fragment_length, body): + def __init__( + self, + handshake_type, + length, + message_seq, + fragment_offset, + fragment_length, + body, + ): super(HandshakeMessage, self).__init__(ContentType.HANDSHAKE) self.handshake_type = handshake_type self.length = length @@ -152,12 +159,14 @@ class HandshakeMessage(Message): self.body = body def to_bytes(self): - return (struct.pack(">B", self.handshake_type) + - struct.pack(">I", self.length)[1:] + - struct.pack(">H", self.message_seq) + - struct.pack(">I", self.fragment_offset)[1:] + - struct.pack(">I", self.fragment_length)[1:] + - self.body.to_bytes()) + return ( + struct.pack(">B", self.handshake_type) + + struct.pack(">I", self.length)[1:] + + struct.pack(">H", self.message_seq) + + struct.pack(">I", self.fragment_offset)[1:] + + struct.pack(">I", self.fragment_length)[1:] + + self.body.to_bytes() + ) @classmethod def from_bytes(cls, data): @@ -177,23 +186,32 @@ class HandshakeMessage(Message): body = bytes(data.read(fragment_length)) assert data.tell() == end_position - return cls(handshake_type, length, message_seq, - fragment_offset, fragment_length, body) + return cls( + handshake_type, + length, + message_seq, + fragment_offset, + fragment_length, + body, + ) def __repr__(self): - return "Handshake(type={}, length={})".format(str(self.handshake_type), self.length) + return "Handshake(type={}, length={})".format( + str(self.handshake_type), self.length + ) class ProtocolVersion(ConvertibleToBytes, BuildableFromBytes): - def __init__(self, major, minor): self.major = major self.minor = minor def __eq__(self, other): - return (type(self) == type(other) and - self.major == other.major and - self.minor == other.minor) + return ( + isinstance(self, type(other)) + and self.major == other.major + and self.minor == other.minor + ) def to_bytes(self): return struct.pack(">BB", self.major, self.minor) @@ -204,7 +222,9 @@ class ProtocolVersion(ConvertibleToBytes, BuildableFromBytes): return cls(major, minor) def __repr__(self): - return "ProtocolVersion(major={}, minor={})".format(self.major, self.minor) + return "ProtocolVersion(major={}, minor={})".format( + self.major, self.minor + ) class Random(ConvertibleToBytes, BuildableFromBytes): @@ -217,9 +237,11 @@ class Random(ConvertibleToBytes, BuildableFromBytes): assert len(self.random_bytes) == Random.random_bytes_length def __eq__(self, other): - return (type(self) == type(other) and - self.gmt_unix_time == other.gmt_unix_time and - self.random_bytes == other.random_bytes) + return ( + isinstance(self, type(other)) + and self.gmt_unix_time == other.gmt_unix_time + and self.random_bytes == other.random_bytes + ) def to_bytes(self): return struct.pack(">I", self.gmt_unix_time) + (self.random_bytes) @@ -232,7 +254,6 @@ class Random(ConvertibleToBytes, BuildableFromBytes): class VariableVector(ConvertibleToBytes): - def __init__(self, subrange, ele_cls, elements): self.subrange = subrange self.ele_cls = ele_cls @@ -243,10 +264,12 @@ class VariableVector(ConvertibleToBytes): return len(self.elements) def __eq__(self, other): - return (type(self) == type(other) and - self.subrange == other.subrange and - self.ele_cls == other.ele_cls and - self.elements == other.elements) + return ( + isinstance(self, type(other)) + and self.subrange == other.subrange + and self.ele_cls == other.ele_cls + and self.elements == other.elements + ) def to_bytes(self): data = reduce(lambda ele, acc: acc + ele.to_bytes(), self.elements) @@ -264,7 +287,11 @@ class VariableVector(ConvertibleToBytes): @classmethod def _decode_length(cls, subrange, data): length_in_byte = cls._calc_length_in_byte(subrange[1]) - return reduce(lambda acc, byte: (acc << 8) | byte, bytearray(data.read(length_in_byte)), 0) + return reduce( + lambda acc, byte: (acc << 8) | byte, + bytearray(data.read(length_in_byte)), + 0, + ) @classmethod def _encode_length(cls, length, subrange): @@ -281,12 +308,11 @@ class VariableVector(ConvertibleToBytes): class Opaque(ConvertibleToBytes, BuildableFromBytes): - def __init__(self, byte): self.byte = byte def __eq__(self, other): - return type(self) == type(other) and self.byte == other.byte + return isinstance(self, type(other)) and self.byte == other.byte def to_bytes(self): return struct.pack(">B", self.byte) @@ -297,12 +323,11 @@ class Opaque(ConvertibleToBytes, BuildableFromBytes): class CipherSuite(ConvertibleToBytes, BuildableFromBytes): - def __init__(self, cipher): self.cipher = cipher def __eq__(self, other): - return type(self) == type(other) and self.cipher == other.cipher + return isinstance(self, type(other)) and self.cipher == other.cipher def to_bytes(self): return struct.pack(">BB", self.cipher[0], self.cipher[1]) @@ -323,7 +348,7 @@ class CompressionMethod(ConvertibleToBytes, BuildableFromBytes): pass def __eq__(self, other): - return type(self) == type(other) + return isinstance(self, type(other)) def to_bytes(self): return struct.pack(">B", CompressionMethod.NULL) @@ -336,31 +361,43 @@ class CompressionMethod(ConvertibleToBytes, BuildableFromBytes): class Extension(ConvertibleToBytes, BuildableFromBytes): - def __init__(self, extension_type, extension_data): self.extension_type = extension_type self.extension_data = extension_data def __eq__(self, other): - return (type(self) == type(other) and - self.extension_type == other.extension_type and - self.extension_data == other.extension_data) + return ( + isinstance(self, type(other)) + and self.extension_type == other.extension_type + and self.extension_data == other.extension_data + ) def to_bytes(self): - return (struct.pack(">H", self.extension_type) + - self.extension_data.to_bytes()) + return ( + struct.pack(">H", self.extension_type) + + self.extension_data.to_bytes() + ) @classmethod def from_bytes(cls, data): extension_type = struct.unpack(">H", data.read(2))[0] - extension_data = VariableVector.from_bytes(Opaque, (0, 2**16 - 1), data) + extension_data = VariableVector.from_bytes( + Opaque, (0, 2 ** 16 - 1), data + ) return cls(extension_type, extension_data) class ClientHello(HandshakeMessage): - - def __init__(self, client_version, random, session_id, - cookie, cipher_suites, compression_methods, extensions): + def __init__( + self, + client_version, + random, + session_id, + cookie, + cipher_suites, + compression_methods, + extensions, + ): self.client_version = client_version self.random = random self.session_id = session_id @@ -370,31 +407,45 @@ class ClientHello(HandshakeMessage): self.extensions = extensions def to_bytes(self): - return (self.client_version.to_bytes() + - self.random.to_bytes() + - self.session_id.to_bytes() + - self.cookie.to_bytes() + - self.cipher_suites.to_bytes() + - self.compression_methods.to_bytes() + - self.extensions.to_bytes()) + return ( + self.client_version.to_bytes() + + self.random.to_bytes() + + self.session_id.to_bytes() + + self.cookie.to_bytes() + + self.cipher_suites.to_bytes() + + self.compression_methods.to_bytes() + + self.extensions.to_bytes() + ) @classmethod def from_bytes(cls, data): client_version = ProtocolVersion.from_bytes(data) random = Random.from_bytes(data) session_id = VariableVector.from_bytes(Opaque, (0, 32), data) - cookie = VariableVector.from_bytes(Opaque, (0, 2**8 - 1), data) - cipher_suites = VariableVector.from_bytes(CipherSuite, (2, 2**16 - 1), data) - compression_methods = VariableVector.from_bytes(CompressionMethod, (1, 2**8 - 1), data) + cookie = VariableVector.from_bytes(Opaque, (0, 2 ** 8 - 1), data) + cipher_suites = VariableVector.from_bytes( + CipherSuite, (2, 2 ** 16 - 1), data + ) + compression_methods = VariableVector.from_bytes( + CompressionMethod, (1, 2 ** 8 - 1), data + ) extensions = None if data.tell() < len(data.getvalue()): - extensions = VariableVector.from_bytes(Extension, (0, 2**16 - 1), data) - return cls(client_version, random, session_id, - cookie, cipher_suites, compression_methods, extensions) + extensions = VariableVector.from_bytes( + Extension, (0, 2 ** 16 - 1), data + ) + return cls( + client_version, + random, + session_id, + cookie, + cipher_suites, + compression_methods, + extensions, + ) class HelloVerifyRequest(HandshakeMessage): - def __init__(self, server_version, cookie): self.server_version = server_version self.cookie = cookie @@ -405,14 +456,20 @@ class HelloVerifyRequest(HandshakeMessage): @classmethod def from_bytes(cls, data): server_version = ProtocolVersion.from_bytes(data) - cookie = VariableVector.from_bytes(Opaque, (0, 2**8 - 1), data) + cookie = VariableVector.from_bytes(Opaque, (0, 2 ** 8 - 1), data) return cls(server_version, cookie) class ServerHello(HandshakeMessage): - - def __init__(self, server_version, random, session_id, - cipher_suite, compression_method, extensions): + def __init__( + self, + server_version, + random, + session_id, + cipher_suite, + compression_method, + extensions, + ): self.server_version = server_version self.random = random self.session_id = session_id @@ -421,12 +478,14 @@ class ServerHello(HandshakeMessage): self.extensions = extensions def to_bytes(self): - return (self.server_version.to_bytes() + - self.random.to_bytes() + - self.session_id.to_bytes() + - self.cipher_suite.to_bytes() + - self.compression_method.to_bytes() + - self.extensions.to_bytes()) + return ( + self.server_version.to_bytes() + + self.random.to_bytes() + + self.session_id.to_bytes() + + self.cipher_suite.to_bytes() + + self.compression_method.to_bytes() + + self.extensions.to_bytes() + ) @classmethod def from_bytes(cls, data): @@ -437,13 +496,20 @@ class ServerHello(HandshakeMessage): compression_method = CompressionMethod.from_bytes(data) extensions = None if data.tell() < len(data.getvalue()): - extensions = VariableVector.from_bytes(Extension, (0, 2**16 - 1), data) - return cls(server_version, random, session_id, - cipher_suite, compression_method, extensions) + extensions = VariableVector.from_bytes( + Extension, (0, 2 ** 16 - 1), data + ) + return cls( + server_version, + random, + session_id, + cipher_suite, + compression_method, + extensions, + ) class ServerHelloDone(HandshakeMessage): - def __init__(self): pass @@ -456,49 +522,41 @@ class ServerHelloDone(HandshakeMessage): class HelloRequest(HandshakeMessage): - def __init__(self): raise NotImplementedError class Certificate(HandshakeMessage): - def __init__(self): raise NotImplementedError class ServerKeyExchange(HandshakeMessage): - def __init__(self): raise NotImplementedError class CertificateRequest(HandshakeMessage): - def __init__(self): raise NotImplementedError class CertificateVerify(HandshakeMessage): - def __init__(self): raise NotImplementedError class ClientKeyExchange(HandshakeMessage): - def __init__(self): raise NotImplementedError class Finished(HandshakeMessage): - def __init__(self, verify_data): raise NotImplementedError class AlertMessage(Message): - def __init__(self, level, description): super(AlertMessage, self).__init__(ContentType.ALERT) self.level = level @@ -512,20 +570,22 @@ class AlertMessage(Message): level, description = struct.unpack(">BB", data.read(2)) try: return cls(AlertLevel(level), AlertDescription(description)) - except: + except BaseException: data.read() # An AlertMessage could be encrypted and we can't parsing it. return cls(None, None) def __repr__(self): return "Alert(level={}, description={})".format( - str(self.level), str(self.description)) + str(self.level), str(self.description) + ) class ChangeCipherSpecMessage(Message): - def __init__(self): - super(ChangeCipherSpecMessage, self).__init__(ContentType.CHANGE_CIPHER_SPEC) + super(ChangeCipherSpecMessage, self).__init__( + ContentType.CHANGE_CIPHER_SPEC + ) def to_bytes(self): return struct.pack(">B", 1) @@ -540,9 +600,10 @@ class ChangeCipherSpecMessage(Message): class ApplicationDataMessage(Message): - def __init__(self, raw): - super(ApplicationDataMessage, self).__init__(ContentType.APPLICATION_DATA) + super(ApplicationDataMessage, self).__init__( + ContentType.APPLICATION_DATA + ) self.raw = raw self.body = None @@ -568,13 +629,13 @@ handshake_map = { HandshakeType.CLIENT_HELLO: ClientHello, HandshakeType.SERVER_HELLO: ServerHello, HandshakeType.HELLO_VERIFY_REQUEST: HelloVerifyRequest, - HandshakeType.CERTIFICATE: None, # Certificate - HandshakeType.SERVER_KEY_EXCHANGE: None, # ServerKeyExchange - HandshakeType.CERTIFICATE_REQUEST: None, # CertificateRequest + HandshakeType.CERTIFICATE: None, # Certificate + HandshakeType.SERVER_KEY_EXCHANGE: None, # ServerKeyExchange + HandshakeType.CERTIFICATE_REQUEST: None, # CertificateRequest HandshakeType.SERVER_HELLO_DONE: ServerHelloDone, - HandshakeType.CERTIFICATE_VERIFY: None, # CertificateVerify - HandshakeType.CLIENT_KEY_EXCHANGE: None, # ClientKeyExchange - HandshakeType.FINISHED: None, # Finished + HandshakeType.CERTIFICATE_VERIFY: None, # CertificateVerify + HandshakeType.CLIENT_KEY_EXCHANGE: None, # ClientKeyExchange + HandshakeType.FINISHED: None, # Finished } @@ -582,7 +643,7 @@ content_map = { ContentType.CHANGE_CIPHER_SPEC: ChangeCipherSpecMessage, ContentType.ALERT: AlertMessage, ContentType.HANDSHAKE: HandshakeMessage, - ContentType.APPLICATION_DATA: ApplicationDataMessage + ContentType.APPLICATION_DATA: ApplicationDataMessage, } @@ -600,11 +661,15 @@ class MessageFactory(object): while data.tell() < len(data.getvalue()): record = Record.from_bytes(data) - if record.version.major != 0xfe or record.version.minor != 0xfd: + if record.version.major != 0xfe or record.version.minor != 0xFD: raise ValueError("DTLS version error, expect DTLSv1.2") - last_msg_is_change_cipher_spec = type(self).last_msg_is_change_cipher_spec - type(self).last_msg_is_change_cipher_spec = (record.content_type == ContentType.CHANGE_CIPHER_SPEC) + last_msg_is_change_cipher_spec = type( + self + ).last_msg_is_change_cipher_spec + type(self).last_msg_is_change_cipher_spec = ( + record.content_type == ContentType.CHANGE_CIPHER_SPEC + ) # FINISHED message immediately follows CHANGE_CIPHER_SPEC message # We skip FINISHED message as it is encrypted diff --git a/tests/scripts/thread-cert/ipv6.py b/tests/scripts/thread-cert/ipv6.py index fb4047bac..ebf7481e2 100644 --- a/tests/scripts/thread-cert/ipv6.py +++ b/tests/scripts/thread-cert/ipv6.py @@ -74,18 +74,22 @@ def calculate_checksum(data): Returns: int: calculated checksum """ - # Create halfwords from data bytes. Example: data[0] = 0x01, data[1] = 0xb2 => 0x01b2 - halfwords = [((byte0 << 8) | byte1) for byte0, byte1 in zip_longest(data[::2], data[1::2], fillvalue=0x00)] + # Create halfwords from data bytes. Example: data[0] = 0x01, data[1] = + # 0xb2 => 0x01b2 + halfwords = [ + ((byte0 << 8) | byte1) + for byte0, byte1 in zip_longest(data[::2], data[1::2], fillvalue=0x00) + ] checksum = 0 for halfword in halfwords: checksum += halfword - checksum = (checksum & 0xFFFF) + (checksum >> 16) + checksum = (checksum & 0xffff) + (checksum >> 16) - checksum ^= 0xFFFF + checksum ^= 0xffff if checksum == 0: - return 0xFFFF + return 0xffff else: return checksum @@ -203,9 +207,13 @@ class IPv6PseudoHeader(ConvertibleToBytes): """ - def __init__(self, source_address, destination_address, payload_length, next_header): + def __init__( + self, source_address, destination_address, payload_length, next_header + ): self._source_address = self._convert_to_ipaddress(source_address) - self._destination_address = self._convert_to_ipaddress(destination_address) + self._destination_address = self._convert_to_ipaddress( + destination_address + ) self.payload_length = payload_length self.next_header = next_header @@ -252,11 +260,21 @@ class IPv6Header(ConvertibleToBytes, BuildableFromBytes): _header_length = 40 - def __init__(self, source_address, destination_address, traffic_class=0, flow_label=0, hop_limit=64, - payload_length=0, next_header=0): + def __init__( + self, + source_address, + destination_address, + traffic_class=0, + flow_label=0, + hop_limit=64, + payload_length=0, + next_header=0, + ): self.version = self._version self._source_address = self._convert_to_ipaddress(source_address) - self._destination_address = self._convert_to_ipaddress(destination_address) + self._destination_address = self._convert_to_ipaddress( + destination_address + ) self.traffic_class = traffic_class self.flow_label = flow_label self.hop_limit = hop_limit @@ -285,12 +303,16 @@ class IPv6Header(ConvertibleToBytes, BuildableFromBytes): return self._destination_address def to_bytes(self): - data = bytearray([ - ((self.version & 0x0F) << 4) | ((self.traffic_class >> 4) & 0x0F), - ((self.traffic_class & 0x0F) << 4) | ((self.flow_label >> 16) & 0x0F), - ((self.flow_label >> 8) & 0xFF), - ((self.flow_label & 0xFF)) - ]) + data = bytearray( + [ + ((self.version & 0x0F) << 4) + | ((self.traffic_class >> 4) & 0x0F), + ((self.traffic_class & 0x0F) << 4) + | ((self.flow_label >> 16) & 0x0F), + ((self.flow_label >> 8) & 0xff), + ((self.flow_label & 0xff)), + ] + ) data += struct.pack(">H", self.payload_length) data += bytearray([self.next_header, self.hop_limit]) data += self.source_address.packed @@ -302,7 +324,7 @@ class IPv6Header(ConvertibleToBytes, BuildableFromBytes): def from_bytes(cls, data): b = bytearray(data.read(4)) - version = (b[0] >> 4) & 0x0F + (b[0] >> 4) & 0x0F traffic_class = ((b[0] & 0x0F) << 4) | ((b[1] >> 4) & 0x0F) flow_label = ((b[1] & 0x0F) << 16) | (b[2] << 8) | b[3] @@ -312,23 +334,27 @@ class IPv6Header(ConvertibleToBytes, BuildableFromBytes): src_addr = bytearray(data.read(16)) dst_addr = bytearray(data.read(16)) - return cls(src_addr, - dst_addr, - traffic_class, - flow_label, - hop_limit, - payload_length, - next_header) + return cls( + src_addr, + dst_addr, + traffic_class, + flow_label, + hop_limit, + payload_length, + next_header, + ) def __repr__(self): return "IPv6Header(source_address={}, destination_address={}, next_header={}, payload_length={}, \ - hop_limit={}, traffic_class={}, flow_label={})".format(self.source_address.compressed, - self.destination_address.compressed, - self.next_header, - self.payload_length, - self.hop_limit, - self.traffic_class, - self.flow_label) + hop_limit={}, traffic_class={}, flow_label={})".format( + self.source_address.compressed, + self.destination_address.compressed, + self.next_header, + self.payload_length, + self.hop_limit, + self.traffic_class, + self.flow_label, + ) def __len__(self): return self._header_length @@ -380,12 +406,16 @@ class IPv6Packet(ConvertibleToBytes): """ - def __init__(self, ipv6_header, upper_layer_protocol, extension_headers=None): + def __init__( + self, ipv6_header, upper_layer_protocol, extension_headers=None + ): self.ipv6_header = ipv6_header self.upper_layer_protocol = upper_layer_protocol - self.extension_headers = extension_headers if extension_headers is not None else [] + self.extension_headers = ( + extension_headers if extension_headers is not None else [] + ) self._update_next_header_values_in_headers() @@ -396,14 +426,22 @@ class IPv6Packet(ConvertibleToBytes): checksum = self.calculate_checksum() if self.upper_layer_protocol.checksum != checksum: - raise RuntimeError("Could not create IPv6 packet. " - "Invalid checksum: {}!={}".format(self.upper_layer_protocol.checksum, checksum)) + raise RuntimeError( + "Could not create IPv6 packet. " + "Invalid checksum: {}!={}".format( + self.upper_layer_protocol.checksum, checksum + ) + ) self.upper_layer_protocol.checksum = checksum def _update_payload_length_value_in_ipv6_header(self): - self.ipv6_header.payload_length = len(self.upper_layer_protocol) + \ - sum([len(extension_header) for extension_header in self.extension_headers]) + self.ipv6_header.payload_length = len(self.upper_layer_protocol) + sum( + [ + len(extension_header) + for extension_header in self.extension_headers + ] + ) def _update_next_header_values_in_headers(self): last_header = self.ipv6_header @@ -423,12 +461,16 @@ class IPv6Packet(ConvertibleToBytes): self.upper_layer_protocol.checksum = saved_checksum - pseudo_header = IPv6PseudoHeader(self.ipv6_header.source_address, - self.ipv6_header.destination_address, - len(upper_layer_protocol_bytes), - self.upper_layer_protocol.type) + pseudo_header = IPv6PseudoHeader( + self.ipv6_header.source_address, + self.ipv6_header.destination_address, + len(upper_layer_protocol_bytes), + self.upper_layer_protocol.type, + ) - return calculate_checksum(pseudo_header.to_bytes() + upper_layer_protocol_bytes) + return calculate_checksum( + pseudo_header.to_bytes() + upper_layer_protocol_bytes + ) def to_bytes(self): self._update_payload_length_value_in_ipv6_header() @@ -445,7 +487,9 @@ class IPv6Packet(ConvertibleToBytes): return ipv6_packet def __repr__(self): - return "IPv6Packet(header={}, upper_layer_protocol={})".format(self.ipv6_header, self.upper_layer_protocol) + return "IPv6Packet(header={}, upper_layer_protocol={})".format( + self.ipv6_header, self.upper_layer_protocol + ) class UDPHeader(ConvertibleToBytes, BuildableFromBytes): @@ -552,7 +596,9 @@ class ICMPv6Header(ConvertibleToBytes, BuildableFromBytes): self.checksum = checksum def to_bytes(self): - return bytearray([self.type, self.code]) + struct.pack(">H", self.checksum) + return bytearray([self.type, self.code]) + struct.pack( + ">H", self.checksum + ) @classmethod def from_bytes(cls, data): @@ -581,6 +627,7 @@ class ICMPv6(UpperLayerProtocol): 0x41, 0x41]))) """ + @property def type(self): return 58 @@ -606,6 +653,7 @@ class HopByHop(ExtensionHeader): - options """ + _one_byte_padding = 0x00 _many_bytes_padding = 0x01 @@ -698,7 +746,9 @@ class HopByHopOptionHeader(ConvertibleToBytes, BuildableFromBytes): return self._header_length def __repr__(self): - return "HopByHopOptionHeader(type={}, length={})".format(self.type, self.length) + return "HopByHopOptionHeader(type={}, length={})".format( + self.type, self.length + ) class HopByHopOption(ConvertibleToBytes): @@ -729,7 +779,9 @@ class HopByHopOption(ConvertibleToBytes): return len(self.header) + len(self.value) def __repr__(self): - return "HopByHopOption(header={}, value={})".format(self.header, self.value) + return "HopByHopOption(header={}, value={})".format( + self.header, self.value + ) class MPLOption(ConvertibleToBytes): @@ -738,12 +790,7 @@ class MPLOption(ConvertibleToBytes): _header_length = 2 - _seed_id_length = { - 0: 0, - 1: 2, - 2: 8, - 3: 16 - } + _seed_id_length = {0: 0, 1: 2, 2: 8, 3: 16} def __init__(self, S, M, V, sequence, seed_id): self.S = S @@ -753,7 +800,11 @@ class MPLOption(ConvertibleToBytes): self.seed_id = seed_id def to_bytes(self): - smv = ((self.S & 0x03) << 6) | ((self.M & 0x01) << 5) | ((self.V & 0x01) << 4) + smv = ( + ((self.S & 0x03) << 6) + | ((self.M & 0x01) << 5) + | ((self.V & 0x01) << 4) + ) return bytearray([smv, self.sequence]) + self.seed_id @@ -761,9 +812,9 @@ class MPLOption(ConvertibleToBytes): def from_bytes(cls, data): b = ord(data.read(1)) - s = ((b >> 6) & 0x03) - m = ((b >> 5) & 0x01) - v = ((b >> 4) & 0x01) + s = (b >> 6) & 0x03 + m = (b >> 5) & 0x01 + v = (b >> 4) & 0x01 sequence = ord(data.read(1)) seed_id = data.read(cls._seed_id_length[s]) @@ -774,7 +825,9 @@ class MPLOption(ConvertibleToBytes): return self._header_length + self._seed_id_length[self.S] def __repr__(self): - return "MPLOption(S={}, M={}, V={}, sequence={}, seed_id={})".format(self.S, self.M, self.V, self.sequence, hexlify(self.seed_id)) + return "MPLOption(S={}, M={}, V={}, sequence={}, seed_id={})".format( + self.S, self.M, self.V, self.sequence, hexlify(self.seed_id) + ) class IPv6PacketFactory(PacketFactory): @@ -832,19 +885,27 @@ class IPv6PacketFactory(PacketFactory): self._ulpf = ulpf if ulpf is not None else {} def _is_extension_header(self, header_type): - return not header_type in UPPER_LAYER_PROTOCOLS + return header_type not in UPPER_LAYER_PROTOCOLS def _get_extension_header_factory_for(self, next_header): try: return self._ehf[next_header] except KeyError: - raise RuntimeError("Could not get Extension Header factory for next_header={}.".format(next_header)) + raise RuntimeError( + "Could not get Extension Header factory for next_header={}.".format( + next_header + ) + ) def _get_upper_layer_protocol_factory_for(self, next_header): try: return self._ulpf[next_header] except KeyError: - raise RuntimeError("Could not get Upper Layer Protocol factory for next_header={}.".format(next_header)) + raise RuntimeError( + "Could not get Upper Layer Protocol factory for next_header={}.".format( + next_header + ) + ) def _parse_extension_headers(self, data, next_header, message_info): extension_headers = [] @@ -871,9 +932,13 @@ class IPv6PacketFactory(PacketFactory): message_info.source_ipv6 = ipv6_header.source_address message_info.destination_ipv6 = ipv6_header.destination_address - next_header, extension_headers = self._parse_extension_headers(data, ipv6_header.next_header, message_info) + next_header, extension_headers = self._parse_extension_headers( + data, ipv6_header.next_header, message_info + ) - upper_layer_protocol = self._parse_upper_layer_protocol(data, next_header, message_info) + upper_layer_protocol = self._parse_upper_layer_protocol( + data, next_header, message_info + ) return IPv6Packet(ipv6_header, upper_layer_protocol, extension_headers) @@ -886,13 +951,16 @@ class HopByHopOptionsFactory(object): _many_bytes_padding = 0x01 def __init__(self, options_factories=None): - self._options_factories = options_factories if options_factories is not None else {} + self._options_factories = ( + options_factories if options_factories is not None else {} + ) def _get_HopByHopOption_value_factory(self, _type): try: return self._options_factories[_type] except KeyError: - raise RuntimeError("Could not find HopByHopOption value factory for type={}.".format(_type)) + raise RuntimeError( + "Could not find HopByHopOption value factory for type={}.".format(_type)) def parse(self, data, message_info): options = [] @@ -909,11 +977,16 @@ class HopByHopOptionsFactory(object): data.read(option_header.length) else: - factory = self._get_HopByHopOption_value_factory(option_header.type) + factory = self._get_HopByHopOption_value_factory( + option_header.type + ) option_data = data.read(option_header.length) - option = HopByHopOption(option_header, factory.parse(io.BytesIO(option_data), message_info)) + option = HopByHopOption( + option_header, + factory.parse(io.BytesIO(option_data), message_info), + ) options.append(option) @@ -935,12 +1008,17 @@ class HopByHopFactory(PacketFactory): hdr_ext_len = ord(data.read(1)) - # Note! Two bytes were read (next_header and hdr_ext_len) so they must be substracted from header length - hop_by_hop_length = self._calculate_extension_header_length(hdr_ext_len) - 2 + # Note! Two bytes were read (next_header and hdr_ext_len) so they must + # be substracted from header length + hop_by_hop_length = ( + self._calculate_extension_header_length(hdr_ext_len) - 2 + ) hop_by_hop_data = data.read(hop_by_hop_length) - options = self._hop_by_hop_options_factory.parse(io.BytesIO(hop_by_hop_data), message_info) + options = self._hop_by_hop_options_factory.parse( + io.BytesIO(hop_by_hop_data), message_info + ) hop_by_hop = HopByHop(next_header, options, hdr_ext_len) @@ -974,7 +1052,9 @@ class UdpBasedOnSrcDstPortsPayloadFactory: def __init__(self, src_dst_port_based_payload_factories): """ Args: - src_dst_port_based_payload_factories (PacketFactory): Factories parse UDP payload based on source or destination port. + src_dst_port_based_payload_factories (PacketFactory): + Factories parse UDP payload based on source or + destination port. """ self._factories = src_dst_port_based_payload_factories @@ -1007,7 +1087,9 @@ class UDPDatagramFactory(PacketFactory): header = self._udp_header_factory.parse(data, message_info) # Update message payload length: UDP header (8B) + payload length - message_info.payload_length += len(header) + (len(data.getvalue()) - data.tell()) + message_info.payload_length += len(header) + ( + len(data.getvalue()) - data.tell() + ) message_info.src_port = header.src_port message_info.dst_port = header.dst_port @@ -1022,7 +1104,9 @@ class ICMPv6Factory(PacketFactory): """ Factory that produces ICMPv6 messages from data. """ def __init__(self, body_factories=None): - self._body_factories = body_factories if body_factories is not None else {} + self._body_factories = ( + body_factories if body_factories is not None else {} + ) def _get_icmpv6_body_factory(self, _type): try: @@ -1030,13 +1114,17 @@ class ICMPv6Factory(PacketFactory): except KeyError: if "default" not in self._body_factories: - raise RuntimeError("Could not find specialized factory to parse ICMP body. " - "Unsupported ICMP type: {}".format(_type)) + raise RuntimeError( + "Could not find specialized factory to parse ICMP body. " + "Unsupported ICMP type: {}".format(_type) + ) default_factory = self._body_factories["default"] - print("Could not find specialized factory to parse ICMP body. " - "Take the default one: {}".format(type(default_factory))) + print( + "Could not find specialized factory to parse ICMP body. " + "Take the default one: {}".format(type(default_factory)) + ) return default_factory @@ -1045,7 +1133,9 @@ class ICMPv6Factory(PacketFactory): factory = self._get_icmpv6_body_factory(header.type) - message_info.payload_length += len(header) + (len(data.getvalue()) - data.tell()) + message_info.payload_length += len(header) + ( + len(data.getvalue()) - data.tell() + ) return ICMPv6(header, factory.parse(data, message_info)) @@ -1140,7 +1230,8 @@ class ICMPv6DestinationUnreachable(ConvertibleToBytes, BuildableFromBytes): unused = struct.unpack(">I", data.read(4))[0] if unused != 0: raise RuntimeError( - "Invalid value of unused field in the ICMPv6 Destination Unreachable data. Expected value: 0.") + "Invalid value of unused field in the ICMPv6 Destination Unreachable data. Expected value: 0." + ) return cls(bytearray(data.read())) diff --git a/tests/scripts/thread-cert/lowpan.py b/tests/scripts/thread-cert/lowpan.py index 945b44c4f..43ec9dee5 100644 --- a/tests/scripts/thread-cert/lowpan.py +++ b/tests/scripts/thread-cert/lowpan.py @@ -27,14 +27,12 @@ # POSSIBILITY OF SUCH DAMAGE. # -import collections import io import ipaddress import struct import sys import common -import config import ipv6 @@ -118,7 +116,8 @@ class LowpanIPHC: return cls(tf, nh, hlim, cid, sac, sam, m, dac, dam) def __repr__(self): - return "LowpanIPHC(tf={}, nh={}, hlim={}, cid={}, sac={}, sam={}, m={}, dac={}, dam={})".format(self.tf, self.nh, self.hlim, self.cid, self.sac, self.sam, self.m, self.dac, self.dam) + return "LowpanIPHC(tf={}, nh={}, hlim={}, cid={}, sac={}, sam={}, m={}, dac={}, dam={})".format( + self.tf, self.nh, self.hlim, self.cid, self.sac, self.sam, self.m, self.dac, self.dam, ) class LowpanNHC: @@ -189,8 +188,8 @@ class LowpanUDPHC: def from_bytes(cls, data_bytes): data_byte = data_bytes[0] - hdr = (data_byte >> 3) & 0x1f - if hdr != 0x1e: + hdr = (data_byte >> 3) & 0x1F + if hdr != 0x1E: raise RuntimeError("Not a 6LowPAN UDP header.") c = (data_byte >> 2) & 0x01 @@ -214,7 +213,9 @@ class LowpanHopByHopFactory: ext_header_data = data.read(ext_header_length) - options = self._hop_by_hop_options_factory.parse(io.BytesIO(ext_header_data), message_info) + options = self._hop_by_hop_options_factory.parse( + io.BytesIO(ext_header_data), message_info + ) ext_header = ipv6.HopByHop(next_header, options) @@ -231,7 +232,9 @@ class LowpanExtensionHeadersFactory: NHC_NH_COMPRESSED = 1 def __init__(self, ext_headers_factories): - self._ext_headers_factories = ext_headers_factories if ext_headers_factories is not None else {} + self._ext_headers_factories = ( + ext_headers_factories if ext_headers_factories is not None else {} + ) def _decompress_nh(self, hc, data): if hc.nh == self.NHC_NH_INLINE: @@ -244,8 +247,12 @@ class LowpanExtensionHeadersFactory: try: return self._ext_headers_factories[eid] - except: - raise RuntimeError("Could not find an extension header factory for the EID type: {}".format(eid)) + except BaseException: + raise RuntimeError( + "Could not find an extension header factory for the EID type: {}".format( + eid + ) + ) def parse(self, data, message_info): nhc = LowpanNHC.from_bytes(bytearray(data.read(1))) @@ -310,8 +317,7 @@ class LowpanUdpHeaderFactory: return header -class Context(): - +class Context: def __init__(self, prefix, prefix_length=None): if isinstance(prefix, str): if sys.version_info[0] == 2: @@ -327,15 +333,19 @@ class Context(): elif isinstance(prefix, bytearray): self._prefix = prefix - self._prefix_length = prefix_length if prefix_length is not None else len(self._prefix) * 8 + self._prefix_length = ( + prefix_length + if prefix_length is not None + else len(self._prefix) * 8 + ) @property def prefix(self): - return self._prefix[:self.prefix_length_all_bytes] + return self._prefix[: self.prefix_length_all_bytes] @property def prefix_full_bytes(self): - return self._prefix[:self.prefix_length_full_bytes] + return self._prefix[: self.prefix_length_full_bytes] @property def prefix_length(self): @@ -352,7 +362,7 @@ class Context(): @property def prefix_length_all_bytes(self): if self.prefix_length_rest_bits > 0: - return (self.prefix_length_full_bytes + 1) + return self.prefix_length_full_bytes + 1 return self.prefix_length_full_bytes @@ -363,7 +373,11 @@ class ContextManager(dict): def __check_index(self, index): if index < 0 or index > 15: - raise IndexError("Invalid index: {}. Valid index is in range [0, 15]".format(index)) + raise IndexError( + "Invalid index: {}. Valid index is in range [0, 15]".format( + index + ) + ) def __check_type(self, value): if not isinstance(value, Context): @@ -385,7 +399,9 @@ class LowpanIpv6HeaderFactory: """ Factory that produces IPv6 header. """ - IPV6_LINKLOCAL_PREFIX = bytearray([0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) + IPV6_LINKLOCAL_PREFIX = bytearray( + [0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + ) SHORT_ADDR_PADDING_BYTES = bytearray([0x00, 0x00, 0x00, 0xff, 0xfe, 0x00]) @@ -449,10 +465,10 @@ class LowpanIpv6HeaderFactory: return (dscp << 2) | ecn def _unpack_dscp(self, data_byte): - return (data_byte & 0x3F) + return data_byte & 0x3F def _unpack_ecn(self, data_byte): - return (data_byte >> 6) + return data_byte >> 6 def _decompress_tf_4bytes(self, data): data_bytes = [b for b in bytearray(data.read(4))] @@ -523,8 +539,8 @@ class LowpanIpv6HeaderFactory: if iphc.cid == self.IPHC_CID_SET: cid = ord(data.read(1)) - sci = (cid >> 4) & 0x0f - dci = cid & 0x0f + sci = (cid >> 4) & 0x0F + dci = cid & 0x0F return sci, dci @@ -539,7 +555,11 @@ class LowpanIpv6HeaderFactory: return self.IPV6_LINKLOCAL_PREFIX + bytearray(data.read(8)) elif iphc.sam == self.IPHC_SAM_16B: - return self.IPV6_LINKLOCAL_PREFIX + self.SHORT_ADDR_PADDING_BYTES + bytearray(data.read(2)) + return ( + self.IPV6_LINKLOCAL_PREFIX + + self.SHORT_ADDR_PADDING_BYTES + + bytearray(data.read(2)) + ) elif iphc.sam == self.IPHC_SAM_ELIDED: return self.IPV6_LINKLOCAL_PREFIX + src_mac_addr.convert_to_iid() @@ -557,7 +577,7 @@ class LowpanIpv6HeaderFactory: # Case in which some bytes overlap if (prefix_length_all_bytes + len(address_bytes)) > required_bytes: - ############################################################################################### + ################################################################### # Example: # # Total address length: 128 bits @@ -570,7 +590,7 @@ class LowpanIpv6HeaderFactory: # +--------------------+---------------------+ # | prefix (68 bits) | address (64 bits) | # +--------------------+---------------------+ - ############################################################################################### + ################################################################### src_addr = prefix[:prefix_length_full_bytes] required_bytes -= prefix_length_full_bytes @@ -579,8 +599,12 @@ class LowpanIpv6HeaderFactory: prefix_overlapping_byte = prefix[prefix_length_all_bytes - 1] address_overlapping_byte = address_bytes[-required_bytes] - overlapping_byte = prefix_overlapping_byte & ~(0xff >> prefix_length_rest_bits) - overlapping_byte |= address_overlapping_byte & (0xff >> prefix_length_rest_bits) + overlapping_byte = prefix_overlapping_byte & ~( + 0xff >> prefix_length_rest_bits + ) + overlapping_byte |= address_overlapping_byte & ( + 0xff >> prefix_length_rest_bits + ) src_addr += bytearray([overlapping_byte]) required_bytes -= 1 @@ -592,7 +616,11 @@ class LowpanIpv6HeaderFactory: required_bytes -= prefix_length_all_bytes required_bytes -= len(address_bytes) - src_addr = prefix[:prefix_length_all_bytes] + bytearray([0x00] * required_bytes) + address_bytes + src_addr = ( + prefix[:prefix_length_all_bytes] + + bytearray([0x00] * required_bytes) + + address_bytes + ) return src_addr @@ -603,31 +631,43 @@ class LowpanIpv6HeaderFactory: elif iphc.sam == self.IPHC_SAM_64B: context = self._context_manager[sci] - return self._merge_prefix_with_address(prefix=context.prefix, - prefix_length=context.prefix_length, - address_bytes=bytearray(data.read(8))) + return self._merge_prefix_with_address( + prefix=context.prefix, + prefix_length=context.prefix_length, + address_bytes=bytearray(data.read(8)), + ) elif iphc.sam == self.IPHC_SAM_16B: context = self._context_manager[sci] - address_bytes = self.SHORT_ADDR_PADDING_BYTES + bytearray(data.read(2)) + address_bytes = self.SHORT_ADDR_PADDING_BYTES + bytearray( + data.read(2) + ) - return self._merge_prefix_with_address(prefix=context.prefix, - prefix_length=context.prefix_length, - address_bytes=address_bytes) + return self._merge_prefix_with_address( + prefix=context.prefix, + prefix_length=context.prefix_length, + address_bytes=address_bytes, + ) elif iphc.sam == self.IPHC_SAM_0B: context = self._context_manager[sci] - return self._merge_prefix_with_address(prefix=context.prefix, - prefix_length=context.prefix_length, - address_bytes=src_mac_addr.convert_to_iid()) + return self._merge_prefix_with_address( + prefix=context.prefix, + prefix_length=context.prefix_length, + address_bytes=src_mac_addr.convert_to_iid(), + ) def _decompress_src_addr(self, iphc, src_mac_addr, sci, data): if iphc.sac == self.IPHC_SAC_STATELESS: - return self._decompress_src_addr_stateless(iphc, src_mac_addr, data) + return self._decompress_src_addr_stateless( + iphc, src_mac_addr, data + ) elif iphc.sac == self.IPHC_SAC_STATEFUL: - return self._decompress_src_addr_stateful(iphc, src_mac_addr, sci, data) + return self._decompress_src_addr_stateful( + iphc, src_mac_addr, sci, data + ) def _decompress_unicast_dst_addr_stateless(self, iphc, dst_mac_addr, data): if iphc.dam == self.IPHC_DAM_128B: @@ -637,43 +677,61 @@ class LowpanIpv6HeaderFactory: return self.IPV6_LINKLOCAL_PREFIX + bytearray(data.read(8)) elif iphc.dam == self.IPHC_DAM_16B: - return self.IPV6_LINKLOCAL_PREFIX + self.SHORT_ADDR_PADDING_BYTES + bytearray(data.read(2)) + return ( + self.IPV6_LINKLOCAL_PREFIX + + self.SHORT_ADDR_PADDING_BYTES + + bytearray(data.read(2)) + ) elif iphc.dam == self.IPHC_DAM_ELIDED: return self.IPV6_LINKLOCAL_PREFIX + dst_mac_addr.convert_to_iid() - def _decompress_unicast_dst_addr_stateful(self, iphc, dst_mac_addr, dci, data): + def _decompress_unicast_dst_addr_stateful( + self, iphc, dst_mac_addr, dci, data + ): if iphc.dam == self.IPHC_DAM_128B: raise RuntimeError("Reserved") elif iphc.dam == self.IPHC_DAM_64B: context = self._context_manager[dci] - return self._merge_prefix_with_address(prefix=context.prefix, - prefix_length=context.prefix_length, - address_bytes=bytearray(data.read(8))) + return self._merge_prefix_with_address( + prefix=context.prefix, + prefix_length=context.prefix_length, + address_bytes=bytearray(data.read(8)), + ) elif iphc.dam == self.IPHC_DAM_16B: context = self._context_manager[dci] - address_bytes = self.SHORT_ADDR_PADDING_BYTES + bytearray(data.read(2)) + address_bytes = self.SHORT_ADDR_PADDING_BYTES + bytearray( + data.read(2) + ) - return self._merge_prefix_with_address(prefix=context.prefix, - prefix_length=context.prefix_length, - address_bytes=address_bytes) + return self._merge_prefix_with_address( + prefix=context.prefix, + prefix_length=context.prefix_length, + address_bytes=address_bytes, + ) elif iphc.dam == self.IPHC_DAM_0B: context = self._context_manager[dci] - return self._merge_prefix_with_address(prefix=context.prefix, - prefix_length=context.prefix_length, - address_bytes=dst_mac_addr.convert_to_iid()) + return self._merge_prefix_with_address( + prefix=context.prefix, + prefix_length=context.prefix_length, + address_bytes=dst_mac_addr.convert_to_iid(), + ) def _decompress_unicast_dst_addr(self, iphc, dst_mac_addr, dci, data): if iphc.dac == self.IPHC_DAC_STATELESS: - return self._decompress_unicast_dst_addr_stateless(iphc, dst_mac_addr, data) + return self._decompress_unicast_dst_addr_stateless( + iphc, dst_mac_addr, data + ) elif iphc.dac == self.IPHC_DAC_STATEFUL: - return self._decompress_unicast_dst_addr_stateful(iphc, dst_mac_addr, dci, data) + return self._decompress_unicast_dst_addr_stateful( + iphc, dst_mac_addr, dci, data + ) def _decompress_multicast_dst_addr_stateless(self, iphc, data): if iphc.dam == self.IPHC_DAM_128B: @@ -681,14 +739,24 @@ class LowpanIpv6HeaderFactory: elif iphc.dam == self.IPHC_DAM_48B: addr48b = bytearray(data.read(6)) - return bytearray([0xff, addr48b[0]]) + bytearray([0x00] * 9) + addr48b[1:] + return ( + bytearray([0xff, addr48b[0]]) + + bytearray([0x00] * 9) + + addr48b[1:] + ) elif iphc.dam == self.IPHC_DAM_32B: addr32b = bytearray(data.read(4)) - return bytearray([0xFF, addr32b[0]]) + bytearray([0x00] * 11) + addr32b[1:] + return ( + bytearray([0xff, addr32b[0]]) + + bytearray([0x00] * 11) + + addr32b[1:] + ) elif iphc.dam == self.IPHC_DAM_8B: - return bytearray([0xFF, 0x02]) + bytearray([0x00] * 13) + data.read(1) + return ( + bytearray([0xff, 0x02]) + bytearray([0x00] * 13) + data.read(1) + ) def _decompress_multicast_dst_addr_stateful(self, iphc, dci, data): if iphc.dam == self.IPHC_M_DAM_00: @@ -706,7 +774,13 @@ class LowpanIpv6HeaderFactory: if missing_bytes > 0: prefix += bytearray([0x00] * missing_bytes) - return bytearray([0xff]) + addr48b[:2] + bytearray([prefix_length]) + prefix + addr48b[2:] + return ( + bytearray([0xff]) + + addr48b[:2] + + bytearray([prefix_length]) + + prefix + + addr48b[2:] + ) elif iphc.dam == self.IPHC_M_DAM_01: raise RuntimeError("Reserved") @@ -722,11 +796,15 @@ class LowpanIpv6HeaderFactory: return self._decompress_multicast_dst_addr_stateless(iphc, data) elif iphc.dac == self.IPHC_DAC_STATEFUL: - return self._decompress_multicast_dst_addr_stateful(iphc, dci, data) + return self._decompress_multicast_dst_addr_stateful( + iphc, dci, data + ) def _decompress_dst_addr(self, iphc, dst_mac_addr, dci, data): if iphc.m == self.IPHC_M_NO: - return self._decompress_unicast_dst_addr(iphc, dst_mac_addr, dci, data) + return self._decompress_unicast_dst_addr( + iphc, dst_mac_addr, dci, data + ) elif iphc.m == self.IPHC_M_YES: return self._decompress_multicast_dst_addr(iphc, dci, data) @@ -745,11 +823,17 @@ class LowpanIpv6HeaderFactory: hop_limit = self._decompress_hlim(iphc, data) - src_address = self._decompress_src_addr(iphc, message_info.source_mac_address, sci, data) + src_address = self._decompress_src_addr( + iphc, message_info.source_mac_address, sci, data + ) - dst_address = self._decompress_dst_addr(iphc, message_info.destination_mac_address, dci, data) + dst_address = self._decompress_dst_addr( + iphc, message_info.destination_mac_address, dci, data + ) - header = ipv6.IPv6Header(src_address, dst_address, traffic_class, flow_label, hop_limit) + header = ipv6.IPv6Header( + src_address, dst_address, traffic_class, flow_label, hop_limit + ) header.next_header = next_header @@ -760,16 +844,23 @@ class LowpanDecompressor: """ Class decompressing 6LoWPAN packets. """ - def __init__(self, lowpan_ip_header_factory, lowpan_extension_headers_factory, lowpan_udp_header_factory): + def __init__( + self, + lowpan_ip_header_factory, + lowpan_extension_headers_factory, + lowpan_udp_header_factory, + ): self._lowpan_ip_header_factory = lowpan_ip_header_factory - self._lowpan_extension_headers_factory = lowpan_extension_headers_factory + self._lowpan_extension_headers_factory = ( + lowpan_extension_headers_factory + ) self._lowpan_udp_header_factory = lowpan_udp_header_factory def _is_ipv6_extension_header(self, header_first_byte): - return ((header_first_byte >> 4) & 0x0f) == 0x0e + return ((header_first_byte >> 4) & 0x0F) == 0x0E def _is_udp_header(self, header_first_byte): - return ((header_first_byte >> 4) & 0x0f) == 0x0f + return ((header_first_byte >> 4) & 0x0F) == 0x0F def _peek_n_bytes(self, data, n): read_data = data.read(n) @@ -777,7 +868,7 @@ class LowpanDecompressor: return read_data def _is_next_header_compressed(self, header): - return (header.next_header is None) + return header.next_header is None def set_lowpan_context(self, cid, prefix): self._lowpan_ip_header_factory.set_lowpan_context(cid, prefix) @@ -796,7 +887,8 @@ class LowpanDecompressor: header_first_byte = ord(self._peek_n_bytes(data, 1)) if self._is_ipv6_extension_header(header_first_byte): - extension_header = self._lowpan_extension_headers_factory.parse(data, message_info) + extension_header = self._lowpan_extension_headers_factory.parse( + data, message_info) extension_headers.append(extension_header) # Update next header field in the previous header @@ -808,7 +900,9 @@ class LowpanDecompressor: break elif self._is_udp_header(header_first_byte): - udp_header = self._lowpan_udp_header_factory.parse(data, message_info) + udp_header = self._lowpan_udp_header_factory.parse( + data, message_info + ) # Update next header field in the previous header previous_header.next_header = udp_header.type @@ -823,7 +917,9 @@ class LowpanMeshHeader(object): """ Class representing 6LoWPAN mesh header (RFC 4944 5.2). """ - def __init__(self, hops_left, originator_address, final_destination_address): + def __init__( + self, hops_left, originator_address, final_destination_address + ): self._hops_left = hops_left self._originator_address = originator_address self._final_destination_address = final_destination_address @@ -842,7 +938,6 @@ class LowpanMeshHeader(object): class LowpanMeshHeaderFactory: - def _parse_address(self, data, is_short): if is_short: return common.MacAddress.from_rloc16(bytearray(data.read(2))) @@ -855,19 +950,24 @@ class LowpanMeshHeaderFactory: is_short_originator_address = bool(data_byte & 0x20) is_short_final_destination_address = bool(data_byte & 0x10) - if (data_byte & 0x0f) != 0x0f: - hops_left = (data_byte & 0x0f) + if (data_byte & 0x0F) != 0x0F: + hops_left = data_byte & 0x0F else: hops_left = ord(data.read(1)) - originator_address = self._parse_address(data, is_short_originator_address) - final_destination_address = self._parse_address(data, is_short_final_destination_address) + originator_address = self._parse_address( + data, is_short_originator_address + ) + final_destination_address = self._parse_address( + data, is_short_final_destination_address + ) - return LowpanMeshHeader(hops_left, originator_address, final_destination_address) + return LowpanMeshHeader( + hops_left, originator_address, final_destination_address + ) class LowpanFragmentationHeader(object): - def __init__(self, datagram_size, datagram_tag, datagram_offset=0): self._datagram_size = datagram_size self._datagram_tag = datagram_tag @@ -892,9 +992,9 @@ class LowpanFragmentationHeader(object): @classmethod def from_bytes(cls, data): datagram_size = struct.unpack(">H", data.read(2))[0] - has_offset = ((datagram_size >> 11) & 0x1f) == 0x1c + has_offset = ((datagram_size >> 11) & 0x1F) == 0x1C - datagram_size &= 0x7ff + datagram_size &= 0x7FF datagram_tag = struct.unpack(">H", data.read(2))[0] datagram_offset = 0 @@ -905,14 +1005,15 @@ class LowpanFragmentationHeader(object): class LowpanFragmentsBuffer(object): - def __init__(self, buffer_size): self._buffer = [None] * buffer_size self._position = 0 def write(self, data): if (self._position + len(data)) > len(self._buffer): - raise ValueError("Write failure. Data length is bigger than the destination buffer length.") + raise ValueError( + "Write failure. Data length is bigger than the destination buffer length." + ) for i, byte in enumerate(data): self._buffer[self._position + i] = byte @@ -922,7 +1023,9 @@ class LowpanFragmentsBuffer(object): def seek(self, offset): if offset >= len(self._buffer): - raise ValueError("Could not seek current offset. Offset value is bigger than the buffer length.") + raise ValueError( + "Could not seek current offset. Offset value is bigger than the buffer length." + ) self._position = offset @@ -934,7 +1037,9 @@ class LowpanFragmentsBuffer(object): def read(self): if not self.whole_packet_received(): - raise ValueError("Only a part of the packet has been stored in the buffer.") + raise ValueError( + "Only a part of the packet has been stored in the buffer." + ) return bytearray(self._buffer) @@ -943,29 +1048,36 @@ class LowpanFragmentsBuffer(object): class LowpanFragmentsBuffersManager(object): - def __init__(self): self._fragments_buffers = {} def _create_key(self, message_info, datagram_tag): - key = bytes(message_info.source_mac_address.mac_address) +\ - bytes(message_info.destination_mac_address.mac_address) +\ - bytes(datagram_tag) + key = ( + bytes(message_info.source_mac_address.mac_address) + + bytes(message_info.destination_mac_address.mac_address) + + bytes(datagram_tag) + ) return key def _allocate_fragments_buffer(self, key, datagram_size): if datagram_size is None or datagram_size < 0: - raise ValueError("Could not allocate fragments buffer. Invalid datagram size: {}".format(datagram_size)) + raise ValueError( + "Could not allocate fragments buffer. Invalid datagram size: {}".format( + datagram_size + ) + ) fragments_buffer = LowpanFragmentsBuffer(datagram_size) self._fragments_buffers[key] = fragments_buffer return fragments_buffer - def get_fragments_buffer(self, message_info, datagram_tag, datagram_size=None): + def get_fragments_buffer( + self, message_info, datagram_tag, datagram_size=None + ): key = self._create_key(message_info, datagram_tag) - if not key in self._fragments_buffers: + if key not in self._fragments_buffers: self._allocate_fragments_buffer(key, datagram_size) return self._fragments_buffers[key] @@ -977,11 +1089,18 @@ class LowpanFragmentsBuffersManager(object): class LowpanParser(object): - - def __init__(self, lowpan_mesh_header_factory, lowpan_decompressor, lowpan_fragements_buffers_manager, ipv6_packet_factory): + def __init__( + self, + lowpan_mesh_header_factory, + lowpan_decompressor, + lowpan_fragements_buffers_manager, + ipv6_packet_factory, + ): self._lowpan_mesh_header_factory = lowpan_mesh_header_factory self._lowpan_decompressor = lowpan_decompressor - self._lowpan_fragments_buffers_manager = lowpan_fragements_buffers_manager + self._lowpan_fragments_buffers_manager = ( + lowpan_fragements_buffers_manager + ) self._ipv6_packet_factory = ipv6_packet_factory def _peek_n_bytes(self, data, n): @@ -990,16 +1109,16 @@ class LowpanParser(object): return data_bytes def _is_mesh_header(self, first_byte): - return (((first_byte >> 6) & 0x03) == 0x02) + return ((first_byte >> 6) & 0x03) == 0x02 def _is_first_fragmentation_header(self, first_byte): - return (((first_byte >> 3) & 0x1f) == 0x18) + return ((first_byte >> 3) & 0x1F) == 0x18 def _is_subsequent_fragmentation_header(self, first_byte): - return (((first_byte >> 3) & 0x1f) == 0x1c) + return ((first_byte >> 3) & 0x1F) == 0x1C def _is_iphc(self, first_byte): - return (((first_byte >> 5) & 0x07) == 0x03) + return ((first_byte >> 5) & 0x07) == 0x03 def _decompress_iphc(self, data, message_info): return self._lowpan_decompressor.decompress(data, message_info) @@ -1008,14 +1127,21 @@ class LowpanParser(object): fragmentation_header = LowpanFragmentationHeader.from_bytes(data) fragments_buffer = self._lowpan_fragments_buffers_manager.get_fragments_buffer( - message_info, fragmentation_header.datagram_tag, fragmentation_header.datagram_size) + message_info, + fragmentation_header.datagram_tag, + fragmentation_header.datagram_size, + ) - ipv6_header, extension_headers, udp_header = self._decompress_iphc(data, message_info) + ipv6_header, extension_headers, udp_header = self._decompress_iphc( + data, message_info + ) uncompressed_data = data.read() # Update payload lengths - ipv6_header.payload_length = fragmentation_header.datagram_size - len(ipv6_header) + ipv6_header.payload_length = fragmentation_header.datagram_size - len( + ipv6_header + ) fragments_buffer.seek(0) fragments_buffer.write(ipv6_header.to_bytes()) @@ -1031,8 +1157,9 @@ class LowpanParser(object): if fragments_buffer.whole_packet_received(): data = io.BytesIO(fragments_buffer.read()) - self._lowpan_fragments_buffers_manager.free_fragments_buffer(message_info, - fragmentation_header.datagram_tag) + self._lowpan_fragments_buffers_manager.free_fragments_buffer( + message_info, fragmentation_header.datagram_tag + ) return self._ipv6_packet_factory.parse(data, message_info) @@ -1042,9 +1169,12 @@ class LowpanParser(object): fragmentation_header = LowpanFragmentationHeader.from_bytes(data) fragments_buffer = self._lowpan_fragments_buffers_manager.get_fragments_buffer( - message_info, fragmentation_header.datagram_tag, fragmentation_header.datagram_size) + message_info, + fragmentation_header.datagram_tag, + fragmentation_header.datagram_size, + ) - offset = (fragmentation_header.datagram_offset * 8) + offset = fragmentation_header.datagram_offset * 8 fragments_buffer.seek(offset) fragments_buffer.write(data.read()) @@ -1052,15 +1182,18 @@ class LowpanParser(object): if fragments_buffer.whole_packet_received(): data = io.BytesIO(fragments_buffer.read()) - self._lowpan_fragments_buffers_manager.free_fragments_buffer(message_info, - fragmentation_header.datagram_tag) + self._lowpan_fragments_buffers_manager.free_fragments_buffer( + message_info, fragmentation_header.datagram_tag + ) return self._ipv6_packet_factory.parse(data, message_info) return None def _handle_iphc_header(self, data, message_info): - ipv6_header, extension_headers, udp_header = self._decompress_iphc(data, message_info) + ipv6_header, extension_headers, udp_header = self._decompress_iphc( + data, message_info + ) uncompressed_data = data.read() @@ -1080,7 +1213,9 @@ class LowpanParser(object): decompressed_data = ipv6_header.to_bytes() + decompressed_data - return self._ipv6_packet_factory.parse(io.BytesIO(decompressed_data), message_info) + return self._ipv6_packet_factory.parse( + io.BytesIO(decompressed_data), message_info + ) def set_lowpan_context(self, cid, prefix): self._lowpan_decompressor.set_lowpan_context(cid, prefix) @@ -1091,20 +1226,31 @@ class LowpanParser(object): first_byte = ord(self._peek_n_bytes(data, n=1)) if self._is_mesh_header(first_byte): - mesh_header = self._lowpan_mesh_header_factory.parse(data, message_info) + mesh_header = self._lowpan_mesh_header_factory.parse( + data, message_info + ) - message_info.source_mac_address = mesh_header.originator_address - message_info.destination_mac_address = mesh_header.final_destination_address + message_info.source_mac_address = ( + mesh_header.originator_address + ) + message_info.destination_mac_address = ( + mesh_header.final_destination_address + ) elif self._is_first_fragmentation_header(first_byte): - return self._handle_first_fragmentation_header(data, message_info) + return self._handle_first_fragmentation_header( + data, message_info + ) elif self._is_subsequent_fragmentation_header(first_byte): - return self._handle_subsequent_fragmentation_header(data, message_info) + return self._handle_subsequent_fragmentation_header( + data, message_info + ) elif self._is_iphc(first_byte): return self._handle_iphc_header(data, message_info) else: - raise RuntimeError("Unsupported header type: 0x{:02x}".format(first_byte)) - + raise RuntimeError( + "Unsupported header type: 0x{:02x}".format(first_byte) + ) diff --git a/tests/scripts/thread-cert/mac802154.py b/tests/scripts/thread-cert/mac802154.py index a8897a90c..955973f4b 100644 --- a/tests/scripts/thread-cert/mac802154.py +++ b/tests/scripts/thread-cert/mac802154.py @@ -32,12 +32,15 @@ """ import io -import binascii import struct import config from common import MacAddress, MacAddressType, MessageInfo -from net_crypto import AuxiliarySecurityHeader, CryptoEngine, MacCryptoMaterialCreator +from net_crypto import ( + AuxiliarySecurityHeader, + CryptoEngine, + MacCryptoMaterialCreator, +) class DeviceDescriptors: @@ -81,10 +84,22 @@ class MacHeader: class CommandIdentifier: DATA_REQUEST = 4 - def __init__(self, frame_type, frame_pending, ack_request, frame_version, seq, - dest_pan_id=None, dest_address=None, src_pan_id=None, src_address=None, command_type=None, - aux_sec_header=None, mic=None, - fcs=None): + def __init__( + self, + frame_type, + frame_pending, + ack_request, + frame_version, + seq, + dest_pan_id=None, + dest_address=None, + src_pan_id=None, + src_address=None, + command_type=None, + aux_sec_header=None, + mic=None, + fcs=None, + ): self.frame_type = frame_type self.frame_pending = frame_pending @@ -117,11 +132,11 @@ class MacFrame: """Class representing 802.15.4 MAC frame.""" IEEE802154_HEADER_IE_TYPE_MASK = 0x8000 - IEEE802154_HEADER_IE_ID_MASK = 0x7f80 - IEEE802154_HEADER_IE_LENGTH_MASK = 0x007f + IEEE802154_HEADER_IE_ID_MASK = 0x7F80 + IEEE802154_HEADER_IE_LENGTH_MASK = 0x007F - IEEE802154_HEADER_IE_HT1 = 0x7e - IEEE802154_HEADER_IE_HT2 = 0x7f + IEEE802154_HEADER_IE_HT1 = 0x7E + IEEE802154_HEADER_IE_HT2 = 0x7F def parse(self, data): mhr_start = data.tell() @@ -133,18 +148,26 @@ class MacFrame: frame_pending = bool(fc & 0x0010) ack_request = bool(fc & 0x0020) panid_compression = bool(fc & 0x0040) - dest_addr_mode = (fc & 0x0c00) >> 10 + dest_addr_mode = (fc & 0x0C00) >> 10 frame_version = (fc & 0x3000) >> 12 - source_addr_mode = (fc & 0xc000) >> 14 + source_addr_mode = (fc & 0xC000) >> 14 ie_present = bool(fc & 0x0200) if frame_type == MacHeader.FrameType.ACK: fcs = self._parse_fcs(data, data.tell()) - self.header = MacHeader(frame_type, frame_pending, ack_request, frame_version, seq, fcs=fcs) + self.header = MacHeader( + frame_type, + frame_pending, + ack_request, + frame_version, + seq, + fcs=fcs, + ) self.payload = None return - # Presence of PAN Ids is not fully implemented yet but should be enough for Thread. + # Presence of PAN Ids is not fully implemented yet but should be enough + # for Thread. dest_pan_id = struct.unpack("> 7) - header_ie_length = (header_ie & MacFrame.IEEE802154_HEADER_IE_LENGTH_MASK) + header_ie_id = ( + header_ie & MacFrame.IEEE802154_HEADER_IE_ID_MASK + ) >> 7 + header_ie_length = ( + header_ie & MacFrame.IEEE802154_HEADER_IE_LENGTH_MASK + ) if header_ie_length: data.read(header_ie_length) - if header_ie_id in [MacFrame.IEEE802154_HEADER_IE_HT1, MacFrame.IEEE802154_HEADER_IE_HT2]: + if header_ie_id in [ + MacFrame.IEEE802154_HEADER_IE_HT1, + MacFrame.IEEE802154_HEADER_IE_HT2, + ]: break header_ie_end = data.tell() @@ -203,7 +233,9 @@ class MacFrame: fcs_start = data.tell() if aux_sec_header and aux_sec_header.security_level: - mic, payload_end = self._parse_mic(data, aux_sec_header.security_level) + mic, payload_end = self._parse_mic( + data, aux_sec_header.security_level + ) else: payload_end = data.tell() mic = None @@ -211,10 +243,21 @@ class MacFrame: fcs = self._parse_fcs(data, fcs_start) # Create Header object - self.header = MacHeader(frame_type, frame_pending, ack_request, frame_version, seq, - dest_pan_id, dest_address, src_pan_id, src_address, command_type, - aux_sec_header, mic, - fcs) + self.header = MacHeader( + frame_type, + frame_pending, + ack_request, + frame_version, + seq, + dest_pan_id, + dest_address, + src_pan_id, + src_address, + command_type, + aux_sec_header, + mic, + fcs, + ) # Create Payload object payload_len = payload_end - payload_pos @@ -234,7 +277,9 @@ class MacFrame: if ie_present: data.seek(header_ie_start) - non_payload_fields += data.read(header_ie_end - header_ie_start) + non_payload_fields += data.read( + header_ie_end - header_ie_start + ) if command_type is not None: non_payload_fields.append(command_type) @@ -244,22 +289,31 @@ class MacFrame: message_info.nonpayload_fields = non_payload_fields message_info.mhr_bytes = mhr_bytes if src_address.type == MacAddressType.SHORT: - message_info.source_mac_address = DeviceDescriptors.get_extended(src_address).mac_address + message_info.source_mac_address = DeviceDescriptors.get_extended( + src_address).mac_address else: message_info.source_mac_address = src_address.mac_address - sec_obj = CryptoEngine(MacCryptoMaterialCreator(config.DEFAULT_MASTER_KEY)) - self.payload = MacPayload(sec_obj.decrypt(payload, mic, message_info)) + sec_obj = CryptoEngine( + MacCryptoMaterialCreator(config.DEFAULT_MASTER_KEY) + ) + self.payload = MacPayload( + sec_obj.decrypt(payload, mic, message_info) + ) else: self.payload = MacPayload(payload) def _parse_address(self, data, mode): if mode == MacHeader.AddressMode.SHORT: - return MacAddress(data.read(2), MacAddressType.SHORT, big_endian=False) + return MacAddress( + data.read(2), MacAddressType.SHORT, big_endian=False + ) if mode == MacHeader.AddressMode.EXTENDED: - return MacAddress(data.read(8), MacAddressType.LONG, big_endian=False) + return MacAddress( + data.read(8), MacAddressType.LONG, big_endian=False + ) else: return None @@ -277,10 +331,15 @@ class MacFrame: elif key_id_mode == 2: key_id = data.read(5) else: - key_source = None - key_index = None + pass - return AuxiliarySecurityHeader(key_id_mode, security_level, frame_counter, key_id, big_endian=False) + return AuxiliarySecurityHeader( + key_id_mode, + security_level, + frame_counter, + key_id, + big_endian=False, + ) def _parse_mic(self, data, security_level): if security_level in (1, 5): diff --git a/tests/scripts/thread-cert/mesh_cop.py b/tests/scripts/thread-cert/mesh_cop.py index 250bb4405..649813d00 100644 --- a/tests/scripts/thread-cert/mesh_cop.py +++ b/tests/scripts/thread-cert/mesh_cop.py @@ -35,6 +35,7 @@ import struct from network_data import SubTlvsFactory import common + class TlvType(IntEnum): CHANNEL = 0 PAN_ID = 1 @@ -79,26 +80,27 @@ class TlvType(IntEnum): class MeshCopState(IntEnum): ACCEPT = 0x1 - REJECT = 0xFF + REJECT = 0xff class MeshCopMessageType(IntEnum): - JOIN_FIN_REQ = 1, - JOIN_FIN_RSP = 2, - JOIN_ENT_NTF = 3, + JOIN_FIN_REQ = (1,) + JOIN_FIN_RSP = (2,) + JOIN_ENT_NTF = (3,) JOIN_ENT_RSP = 4 def create_mesh_cop_message_type_set(): - return [ MeshCopMessageType.JOIN_FIN_REQ, - MeshCopMessageType.JOIN_FIN_RSP, - MeshCopMessageType.JOIN_ENT_NTF, - MeshCopMessageType.JOIN_ENT_RSP ] + return [ + MeshCopMessageType.JOIN_FIN_REQ, + MeshCopMessageType.JOIN_FIN_RSP, + MeshCopMessageType.JOIN_ENT_NTF, + MeshCopMessageType.JOIN_ENT_RSP, + ] # Channel TLV (0) class Channel(object): - def __init__(self, channel_page, channel): self._channel_page = channel_page self._channel = channel @@ -114,17 +116,23 @@ class Channel(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self._channel_page == other._channel_page and self._channel == other.__channel + return ( + self._channel_page == other._channel_page + and self._channel == other.__channel + ) def __repr__(self): - return 'Channel(channel_page={},channel={})'.format(self._channel_page, self._channel) + return 'Channel(channel_page={},channel={})'.format( + self._channel_page, self._channel + ) def to_hex(self): - return struct.pack('>BBBH', TlvType.CHANNEL, 3, self.channel_page, self.channel) + return struct.pack( + '>BBBH', TlvType.CHANNEL, 3, self.channel_page, self.channel + ) class ChannelFactory(object): - def parse(self, data, message_info): data_tp = struct.unpack('>BH', data.read(3)) channel_page = data_tp[0] @@ -147,7 +155,6 @@ class PanidFactory(object): # ExtendedPanid TLV (2) class ExtendedPanid(object): - def __init__(self, extended_panid): self._extended_panid = extended_panid @@ -156,15 +163,16 @@ class ExtendedPanid(object): return self._extended_panid def __eq__(self, other): - return (type(self) is type(other) - and self.extended_panid == other.extended_panid) + return ( + isinstance(self, type(other)) + and self.extended_panid == other.extended_panid + ) def __repr__(self): return "ExtendedPanid(extended_panid={})".format(self.extended_panid) class ExtendedPanidFactory(object): - def parse(self, data, message_info): extended_panid = struct.unpack(">Q", data.read(8))[0] return ExtendedPanid(extended_panid) @@ -172,7 +180,6 @@ class ExtendedPanidFactory(object): # NetworkName TLV (3) class NetworkName(object): - def __init__(self, network_name): self._network_name = network_name @@ -181,15 +188,16 @@ class NetworkName(object): return self._network_name def __eq__(self, other): - return (type(self) is type(other) - and self.network_name == other.network_name) + return ( + isinstance(self, type(other)) + and self.network_name == other.network_name + ) def __repr__(self): return "NetworkName(network_name={})".format(self.network_name) class NetworkNameFactory(object): - def parse(self, data, message_info): len = message_info.length network_name = struct.unpack("{}s".format(10), data.read(len))[0] @@ -250,7 +258,6 @@ class NetworkMeshLocalPrefixFactory(object): # Steering Data TLV (8) class SteeringData(object): - def __init__(self, bloom_filter): self._bloom_filter = bloom_filter @@ -264,15 +271,19 @@ class SteeringData(object): return self._bloom_filter == other._bloom_filter def __repr__(self): - return "SteeringData(bloom_filter={})".format(hexlify(self._bloom_filter)) + return "SteeringData(bloom_filter={})".format( + hexlify(self._bloom_filter) + ) def to_hex(self): bloom_filter_len = len(self.bloom_filter) - return struct.pack('>BB', TlvType.STEERING_DATA, bloom_filter_len) + self.bloom_filter + return ( + struct.pack('>BB', TlvType.STEERING_DATA, bloom_filter_len) + + self.bloom_filter + ) class SteeringDataFactory: - def parse(self, data, message_info): bloom_filter = data.read(message_info.length) return SteeringData(bloom_filter) @@ -280,7 +291,6 @@ class SteeringDataFactory: # Border Agent Locator TLV (9) class BorderAgentLocator(object): - def __init__(self, address): self._border_agent_locator = address @@ -294,14 +304,17 @@ class BorderAgentLocator(object): return self._border_agent_locator == other._border_agent_locator def __repr__(self): - return "BorderAgentLocator(rloc16={})".format(hex(self._border_agent_locator)) + return "BorderAgentLocator(rloc16={})".format( + hex(self._border_agent_locator) + ) def to_hex(self): - return struct.pack('>BBH', TlvType.BORDER_AGENT_LOCATOR, 2, self.border_agent_locator) + return struct.pack( + '>BBH', TlvType.BORDER_AGENT_LOCATOR, 2, self.border_agent_locator + ) class BorderAgentLocatorFactory: - def parse(self, data, message_info): border_agent_locator = struct.unpack(">H", data.read(2))[0] return BorderAgentLocator(border_agent_locator) @@ -309,7 +322,6 @@ class BorderAgentLocatorFactory: # CommissionerId TLV (10) class CommissionerId(object): - def __init__(self, commissioner_id): self._commissioner_id = commissioner_id @@ -321,7 +333,9 @@ class CommissionerId(object): return self.commissioner_id == other.commissioner_id def __repr__(self): - return "CommissionerId(commissioner_id={})".format(self.commissioner_id) + return "CommissionerId(commissioner_id={})".format( + self.commissioner_id + ) class CommissionerIdFactory(object): @@ -332,7 +346,6 @@ class CommissionerIdFactory(object): # Commissioner Session ID TLV (11) class CommissionerSessionId(object): - def __init__(self, commissioner_session_id): self._commissioner_session_id = commissioner_session_id @@ -346,14 +359,20 @@ class CommissionerSessionId(object): return self._commissioner_session_id == other._commissioner_session_id def __repr__(self): - return "CommissionerSessionId(commissioner_session_id={})".format(self._commissioner_session_id) + return "CommissionerSessionId(commissioner_session_id={})".format( + self._commissioner_session_id + ) def to_hex(self): - return struct.pack('>BBH', TlvType.COMMISSIONER_SESSION_ID, 2, self.commissioner_session_id) + return struct.pack( + '>BBH', + TlvType.COMMISSIONER_SESSION_ID, + 2, + self.commissioner_session_id, + ) class CommissionerSessionIdFactory: - def parse(self, data, message_info): session_id = struct.unpack(">H", data.read(2))[0] return CommissionerSessionId(session_id) @@ -400,7 +419,6 @@ class ActiveTimestampFactory(object): # Commissioner UDP Port TLV (15) class CommissionerUdpPort(object): - def __init__(self, udp_port): self._udp_port = udp_port @@ -418,7 +436,6 @@ class CommissionerUdpPort(object): class CommissionerUdpPortFactory: - def parse(self, data, message_info): udp_port = struct.unpack(">H", data.read(2))[0] return CommissionerUdpPort(udp_port) @@ -426,7 +443,6 @@ class CommissionerUdpPortFactory: # State TLV (16) class State(object): - def __init__(self, state): self._state = state @@ -442,7 +458,6 @@ class State(object): class StateFactory: - def parse(self, data, message_info): state = ord(data.read(1)) return State(state) @@ -463,7 +478,6 @@ class JoinerDtlsEncapsulationFactory(object): # JoinerUdpPort TLV (18) class JoinerUdpPort(object): - def __init__(self, udp_port): self._udp_port = udp_port @@ -472,14 +486,15 @@ class JoinerUdpPort(object): return self._udp_port def __eq__(self, other): - return type(self) is type(other) and self.udp_port == other.udp_port + return ( + isinstance(self, type(other)) and self.udp_port == other.udp_port + ) def __repr__(self): return "JoinerUdpPort(udp_port={})".format(self.udp_port) class JoinerUdpPortFactory(object): - def parse(self, data, message_info): udp_port = struct.unpack(">H", data.read(2))[0] return JoinerUdpPort(udp_port) @@ -526,7 +541,6 @@ class JoinerRouterKEKFactory(object): # ProvisioningURL TLV (32) class ProvisioningUrl(object): - def __init__(self, url): self._url = url @@ -539,7 +553,6 @@ class ProvisioningUrl(object): class ProvisioningUrlFactory: - def parse(self, data, message_info): url = data.decode('utf-8') return ProvisioningUrl(url) @@ -547,7 +560,6 @@ class ProvisioningUrlFactory: # VendorName TLV (33) class VendorName(object): - def __init__(self, vendor_name): self._vendor_name = vendor_name @@ -561,8 +573,8 @@ class VendorName(object): def __repr__(self): return "VendorName(vendor_name={})".format(self.vendor_name) -class VendorNameFactory: +class VendorNameFactory: def parse(self, data, message_info): vendor_name = data.getvalue().decode('utf-8') return VendorName(vendor_name) @@ -570,7 +582,6 @@ class VendorNameFactory: # VendorModel TLV (34) class VendorModel(object): - def __init__(self, vendor_model): self._vendor_model = vendor_model @@ -586,7 +597,6 @@ class VendorModel(object): class VendorModelFactory: - def parse(self, data, message_info): vendor_model = data.getvalue().decode('utf-8') return VendorModel(vendor_model) @@ -594,7 +604,6 @@ class VendorModelFactory: # VendorSWVersion TLV (35) class VendorSWVersion(object): - def __init__(self, vendor_sw_version): self._vendor_sw_version = vendor_sw_version @@ -606,11 +615,12 @@ class VendorSWVersion(object): return self.vendor_sw_version == other.vendor_sw_version def __repr__(self): - return "VendorName(vendor_sw_version={})".format(self.vendor_sw_version) + return "VendorName(vendor_sw_version={})".format( + self.vendor_sw_version + ) class VendorSWVersionFactory: - def parse(self, data, message_info): vendor_sw_version = data.getvalue() return VendorSWVersion(vendor_sw_version) @@ -618,7 +628,6 @@ class VendorSWVersionFactory: # VendorData TLV (36) class VendorData(object): - def __init__(self, data): self._vendor_data = data @@ -631,14 +640,12 @@ class VendorData(object): class VendorDataFactory(object): - def parse(self, data, message_info): return VendorData(data) # VendorStackVersion TLV (37) class VendorStackVersion(object): - def __init__(self, stack_vendor_oui, build, rev, minor, major): self._stack_vendor_oui = stack_vendor_oui self._build = build @@ -668,17 +675,18 @@ class VendorStackVersion(object): return self._major def __repr__(self): - return "VendorStackVersion(vendor_stack_version={}, build={}, rev={}, minor={}, major={})".format(self.stack_vendor_oui, self.build, self.rev, self.minor, self.major) + return "VendorStackVersion(vendor_stack_version={}, build={}, rev={}, minor={}, major={})".format( + self.stack_vendor_oui, self.build, self.rev, self.minor, self.major) + class VendorStackVersionFactory: - def parse(self, data, message_info): stack_vendor_oui = struct.unpack(">H", data.read(2))[0] rest = struct.unpack(">BBBB", data.read(4)) build = rest[1] << 4 | (0xf0 & rest[2]) - rev = 0xf & rest[2] + rev = 0xF & rest[2] minor = rest[3] & 0xf0 - major = rest[3] & 0xf + major = rest[3] & 0xF return VendorStackVersion(stack_vendor_oui, build, rev, minor, major) @@ -801,7 +809,6 @@ class EnergyListFactory(object): # Discovery Request TLV (128) class DiscoveryRequest(object): - def __init__(self, version, joiner_flag): self._version = version self._joiner_flag = joiner_flag @@ -815,17 +822,19 @@ class DiscoveryRequest(object): return self._joiner_flag def __eq__(self, other): - return (type(self) is type(other) + return ( + isinstance(self, type(other)) and self.version == other.version - and self.joiner_flag == other.joiner_flag) + and self.joiner_flag == other.joiner_flag + ) def __repr__(self): return "DiscoveryRequest(version={}, joiner_flag={})".format( - self.version, self.joiner_flag) + self.version, self.joiner_flag + ) class DiscoveryRequestFactory(object): - def parse(self, data, message_info): data_byte = struct.unpack(">B", data.read(1))[0] version = (data_byte & 0xf0) >> 4 @@ -836,7 +845,6 @@ class DiscoveryRequestFactory(object): # Discovery Response TLV (128) class DiscoveryResponse(object): - def __init__(self, version, native_flag): self._version = version self._native_flag = native_flag @@ -850,17 +858,19 @@ class DiscoveryResponse(object): return self._native_flag def __eq__(self, other): - return (type(self) is type(other) + return ( + isinstance(self, type(other)) and self.version == other.version - and self.native_flag == other.native_flag) + and self.native_flag == other.native_flag + ) def __repr__(self): return "DiscoveryResponse(version={}, native_flag={})".format( - self.version, self.native_flag) + self.version, self.native_flag + ) class DiscoveryResponseFactory(object): - def parse(self, data, message_info): data_byte = struct.unpack(">B", data.read(1))[0] version = (data_byte & 0xf0) >> 4 @@ -870,7 +880,6 @@ class DiscoveryResponseFactory(object): class MeshCopCommand(object): - def __init__(self, _type, tlvs): self._type = _type self._tlvs = tlvs @@ -893,12 +902,11 @@ def create_deault_mesh_cop_msg_type_map(): 'JOIN_FIN.req': MeshCopMessageType.JOIN_FIN_REQ, 'JOIN_FIN.rsp': MeshCopMessageType.JOIN_FIN_RSP, 'JOIN_ENT.ntf': MeshCopMessageType.JOIN_ENT_NTF, - 'JOIN_ENT.rsp': MeshCopMessageType.JOIN_ENT_RSP + 'JOIN_ENT.rsp': MeshCopMessageType.JOIN_ENT_RSP, } class MeshCopCommandFactory: - def __init__(self, tlvs_factories): self._tlvs_factories = tlvs_factories self._mesh_cop_msg_type_map = create_deault_mesh_cop_msg_type_map() @@ -910,20 +918,28 @@ class MeshCopCommandFactory: try: return self._tlvs_factories[_type] except KeyError: - raise KeyError("Could not find TLV factory. Unsupported TLV type: {}".format(_type)) + raise KeyError( + "Could not find TLV factory. Unsupported TLV type: {}".format( + _type + ) + ) def _parse_tlv(self, data): _type = TlvType(ord(data.read(1))) length = self._get_length(data) value = data.read(length) factory = self._get_tlv_factory(_type) - return factory.parse(io.BytesIO(value), None) # message_info not needed here + return factory.parse( + io.BytesIO(value), None + ) # message_info not needed here def _get_mesh_cop_msg_type(self, msg_type_str): try: return self._mesh_cop_msg_type_map[msg_type_str] except KeyError: - raise KeyError('Mesh cop message type not found: {}'.format(msg_type_str)) + raise KeyError( + 'Mesh cop message type not found: {}'.format(msg_type_str) + ) def parse(self, cmd_type_str, data): cmd_type = self._get_mesh_cop_msg_type(cmd_type_str) @@ -944,11 +960,10 @@ def create_default_mesh_cop_tlv_factories(): TlvType.VENDOR_MODEL: VendorModelFactory(), TlvType.VENDOR_SW_VERSION: VendorSWVersionFactory(), TlvType.VENDOR_DATA: VendorDataFactory(), - TlvType.VENDOR_STACK_VERSION: VendorStackVersionFactory() + TlvType.VENDOR_STACK_VERSION: VendorStackVersionFactory(), } class ThreadDiscoveryTlvsFactory(SubTlvsFactory): - def __init__(self, sub_tlvs_factories): super(ThreadDiscoveryTlvsFactory, self).__init__(sub_tlvs_factories) diff --git a/tests/scripts/thread-cert/message.py b/tests/scripts/thread-cert/message.py index 4747bdc5f..73761aa60 100644 --- a/tests/scripts/thread-cert/message.py +++ b/tests/scripts/thread-cert/message.py @@ -36,12 +36,12 @@ import coap import common import dtls import ipv6 -import lowpan import mac802154 import mle from enum import IntEnum + class MessageType(IntEnum): MLE = 0 COAP = 1 @@ -54,7 +54,6 @@ class MessageType(IntEnum): class Message(object): - def __init__(self): self._type = None self._channel = None @@ -70,7 +69,9 @@ class Message(object): self._type = MessageType.MLE self._mle = udp_datagram.payload - elif isinstance(udp_datagram.payload, (coap.CoapMessage, coap.CoapMessageProxy)): + elif isinstance( + udp_datagram.payload, (coap.CoapMessage, coap.CoapMessageProxy) + ): self._type = MessageType.COAP self._coap = udp_datagram.payload @@ -145,10 +146,15 @@ class Message(object): elif self._mac_header.frame_type == mac802154.MacHeader.FrameType.DATA: self._type = MessageType.DATA - elif self._mac_header.frame_type == mac802154.MacHeader.FrameType.COMMAND: + elif ( + self._mac_header.frame_type + == mac802154.MacHeader.FrameType.COMMAND + ): self._type = MessageType.COMMAND else: - raise ValueError('Invalid mac frame type %d' % self._mac_header.frame_type) + raise ValueError( + 'Invalid mac frame type %d' % self._mac_header.frame_type + ) @property def ipv6_packet(self): @@ -191,7 +197,7 @@ class Message(object): if self.type != MessageType.MLE: raise ValueError("Invalid message type. Expected MLE message.") - assert(self.mle.command.type == command_type) + assert self.mle.command.type == command_type def assertMleMessageContainsTlv(self, tlv_class_type): """To confirm if Mle message contains the TLV type. @@ -211,7 +217,7 @@ class Message(object): contains_tlv = True break - assert(contains_tlv == True) + assert contains_tlv return tlv def assertAssignedRouterQuantity(self, router_quantity): @@ -225,9 +231,9 @@ class Message(object): count = 0 for i in range(1, 65): - count += (router_id_mask & 1) - router_id_mask = (router_id_mask >> 1) - assert(count == router_quantity) + count += router_id_mask & 1 + router_id_mask = router_id_mask >> 1 + assert count == router_quantity def assertMleMessageDoesNotContainTlv(self, tlv_class_type): if self.type != MessageType.MLE: @@ -239,7 +245,7 @@ class Message(object): contains_tlv = True break - assert(contains_tlv == False) + assert contains_tlv is False def assertMleMessageContainsOptionalTlv(self, tlv_class_type): if self.type != MessageType.MLE: @@ -251,10 +257,16 @@ class Message(object): contains_tlv = True break - if contains_tlv == True: - print("MleMessage contains optional TLV: {}".format(tlv_class_type)) + if contains_tlv: + print( + "MleMessage contains optional TLV: {}".format(tlv_class_type) + ) else: - print("MleMessage doesn't contain optional TLV: {}".format(tlv_class_type)) + print( + "MleMessage doesn't contain optional TLV: {}".format( + tlv_class_type + ) + ) def get_coap_message_tlv(self, tlv_class_type): if self.type != MessageType.COAP: @@ -274,7 +286,7 @@ class Message(object): contains_tlv = True break - assert(contains_tlv == True) + assert contains_tlv def assertCoapMessageDoesNotContainTlv(self, tlv_class_type): if self.type != MessageType.COAP: @@ -286,31 +298,33 @@ class Message(object): contains_tlv = True break - assert(contains_tlv == False) + assert contains_tlv is False def assertCoapMessageContainsOptionalTlv(self, tlv_class_type): if self.type != MessageType.COAP: raise ValueError("Invalid message type. Expected CoAP message.") - contains_tlv = False for tlv in self.coap.payload: if isinstance(tlv, tlv_class_type): - contains_tlv = True break - print("CoapMessage doesn't contain optional TLV: {}".format(tlv_class_type)) + print( + "CoapMessage doesn't contain optional TLV: {}".format( + tlv_class_type + ) + ) def assertCoapMessageRequestUriPath(self, uri_path): if self.type != MessageType.COAP: raise ValueError("Invalid message type. Expected CoAP message.") - assert(uri_path == self.coap.uri_path) + assert uri_path == self.coap.uri_path def assertCoapMessageCode(self, code): if self.type != MessageType.COAP: raise ValueError("Invalid message type. Expected CoAP message.") - assert(code == self.coap.code) + assert code == self.coap.code def assertSentToNode(self, node): sent_to_node = False @@ -326,17 +340,22 @@ class Message(object): sent_to_node = True elif self.mac_header.dest_address.type == common.MacAddressType.LONG: - mac_address = common.MacAddress.from_eui64(bytearray(node.get_addr64(), encoding="utf-8")) + mac_address = common.MacAddress.from_eui64( + bytearray(node.get_addr64(), encoding="utf-8") + ) if self.mac_header.dest_address == mac_address: sent_to_node = True - assert sent_to_node == True + assert sent_to_node def assertSentToDestinationAddress(self, ipv6_address): if sys.version_info[0] == 2: ipv6_address = ipv6_address.decode("utf-8") - assert self.ipv6_packet.ipv6_header.destination_address == ipaddress.ip_address(ipv6_address) + assert ( + self.ipv6_packet.ipv6_header.destination_address + == ipaddress.ip_address(ipv6_address) + ) def assertSentWithHopLimit(self, hop_limit): assert self.ipv6_packet.ipv6_header.hop_limit == hop_limit @@ -345,17 +364,21 @@ class Message(object): return self.mac_header.dest_address.type == common.MacAddressType.LONG def get_dst_udp_port(self): - assert isinstance(self.ipv6_packet.upper_layer_protocol, ipv6.UDPDatagram) + assert isinstance( + self.ipv6_packet.upper_layer_protocol, ipv6.UDPDatagram + ) return self.ipv6_packet.upper_layer_protocol.header.dst_port def __repr__(self): - if self.type == MessageType.DTLS and self.dtls.content_type == dtls.ContentType.HANDSHAKE: + if ( + self.type == MessageType.DTLS + and self.dtls.content_type == dtls.ContentType.HANDSHAKE + ): return "Message(type={})".format(str(self.dtls.handshake_type)) return "Message(type={})".format(MessageType(self.type).name) class MessagesSet(object): - def __init__(self, messages, commissioning_messages=[]): self._messages = messages self._commissioning_messages = commissioning_messages @@ -388,11 +411,13 @@ class MessagesSet(object): break if assert_enabled: - assert message is not None, "Could not find CoapMessage with code: {}".format(code) + assert ( + message is not None + ), "Could not find CoapMessage with code: {}".format(code) return message - def last_mle_message(self, command_type, assert_enabled = True): + def last_mle_message(self, command_type, assert_enabled=True): """Get the last Mle Message with specified type from existing capture. Args: @@ -411,23 +436,29 @@ class MessagesSet(object): if m.type != MessageType.MLE: continue - #for command_type in command_types: + # for command_type in command_types: if m.mle.command.type == command_type: message = m break if assert_enabled: - assert message is not None, "Could not find MleMessage with type: {}".format(command_type) + assert ( + message is not None + ), "Could not find MleMessage with type: {}".format(command_type) return message - def next_mle_message(self, command_type, assert_enabled=True, sent_to_node=None): + def next_mle_message( + self, command_type, assert_enabled=True, sent_to_node=None + ): message = self.next_mle_message_of_one_of_command_types(command_type) if assert_enabled: - assert message is not None, "Could not find MleMessage of the type: {}".format(command_type) + assert ( + message is not None + ), "Could not find MleMessage of the type: {}".format(command_type) - if sent_to_node != None: + if sent_to_node is not None: message.assertSentToNode(sent_to_node) return message @@ -472,7 +503,9 @@ class MessagesSet(object): break if assert_enabled: - assert message is not None, "Could not find Message of the type: {}".format(message_type) + assert ( + message is not None + ), "Could not find Message of the type: {}".format(message_type) return message @@ -489,13 +522,21 @@ class MessagesSet(object): continue if msg.dtls.content_type != content_type: continue - if (content_type == dtls.ContentType.HANDSHAKE and - msg.dtls.handshake_type != handshake_type): + if ( + content_type == dtls.ContentType.HANDSHAKE + and msg.dtls.handshake_type != handshake_type + ): continue return msg - t = handshake_type if content_type == dtls.ContentType.HANDSHAKE else content_type - raise ValueError("Could not find DTLS message of type: {}".format(str(t))) + t = ( + handshake_type + if content_type == dtls.ContentType.HANDSHAKE + else content_type + ) + raise ValueError( + "Could not find DTLS message of type: {}".format(str(t)) + ) def contains_icmp_message(self): for m in self.messages: @@ -543,7 +584,6 @@ class MessagesSet(object): class MessageFactory: - def __init__(self, lowpan_parser): self._lowpan_parser = lowpan_parser @@ -551,10 +591,14 @@ class MessageFactory: for tlv in message.mle.command.tlvs: if isinstance(tlv, mle.SourceAddress): - mac802154.DeviceDescriptors.add(tlv.address, message.mac_header.src_address) + mac802154.DeviceDescriptors.add( + tlv.address, message.mac_header.src_address + ) if isinstance(tlv, mle.Address16): - mac802154.DeviceDescriptors.add(tlv.address, message.mac_header.dest_address) + mac802154.DeviceDescriptors.add( + tlv.address, message.mac_header.dest_address + ) def _parse_mac_frame(self, data): mac_frame = mac802154.MacFrame() diff --git a/tests/scripts/thread-cert/mle.py b/tests/scripts/thread-cert/mle.py index 8bf81edab..4c3e05dc8 100644 --- a/tests/scripts/thread-cert/mle.py +++ b/tests/scripts/thread-cert/mle.py @@ -28,13 +28,11 @@ # import io -import ipaddress import struct from binascii import hexlify import common -import network_data from enum import IntEnum @@ -92,7 +90,6 @@ class TlvType(IntEnum): class SourceAddress(object): - def __init__(self, address): self._address = address @@ -110,14 +107,12 @@ class SourceAddress(object): class SourceAddressFactory: - def parse(self, data, message_info): address = struct.unpack(">H", data.read(2))[0] return SourceAddress(address) class Mode(object): - def __init__(self, receiver, secure, device_type, network_data): self._receiver = receiver self._secure = secure @@ -143,20 +138,19 @@ class Mode(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.receiver == other.receiver and \ - self.secure == other.secure and \ - self.device_type == other.device_type and \ - self.network_data == other.network_data + return ( + self.receiver == other.receiver + and self.secure == other.secure + and self.device_type == other.device_type + and self.network_data == other.network_data + ) def __repr__(self): - return "Mode(receiver={}, secure={}, device_type={}, network_data={})".format(self.receiver, - self.secure, - self.device_type, - self.network_data) + return "Mode(receiver={}, secure={}, device_type={}, network_data={})".format( + self.receiver, self.secure, self.device_type, self.network_data) class ModeFactory: - def parse(self, data, message_info): mode = ord(data.read(1)) receiver = (mode >> 3) & 0x01 @@ -167,7 +161,6 @@ class ModeFactory: class Timeout(object): - def __init__(self, timeout): self._timeout = timeout @@ -185,14 +178,12 @@ class Timeout(object): class TimeoutFactory: - def parse(self, data, message_info): timeout = struct.unpack(">I", data.read(4))[0] return Timeout(timeout) class Challenge(object): - def __init__(self, challenge): self._challenge = challenge @@ -210,14 +201,12 @@ class Challenge(object): class ChallengeFactory: - def parse(self, data, message_info): challenge = data.read() return Challenge(challenge) class Response(object): - def __init__(self, response): self._response = response @@ -235,14 +224,12 @@ class Response(object): class ResponseFactory: - def parse(self, data, message_info): response = data.read() return Response(response) class LinkLayerFrameCounter(object): - def __init__(self, frame_counter): self._frame_counter = frame_counter @@ -256,18 +243,18 @@ class LinkLayerFrameCounter(object): return self.frame_counter == other.frame_counter def __repr__(self): - return "LinkLayerFrameCounter(frame_counter={})".format(self.frame_counter) + return "LinkLayerFrameCounter(frame_counter={})".format( + self.frame_counter + ) class LinkLayerFrameCounterFactory: - def parse(self, data, message_info): frame_counter = struct.unpack(">I", data.read(4))[0] return LinkLayerFrameCounter(frame_counter) class MleFrameCounter(object): - def __init__(self, frame_counter): self._frame_counter = frame_counter @@ -285,14 +272,12 @@ class MleFrameCounter(object): class MleFrameCounterFactory: - def parse(self, data, message_info): frame_counter = struct.unpack(">I", data.read(4))[0] return MleFrameCounter(frame_counter) class LinkQualityAndRouteData(object): - def __init__(self, output, _input, route): self._output = output self._input = _input @@ -313,25 +298,31 @@ class LinkQualityAndRouteData(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.output == other.output and self.input == other.input and self.route == other.route + return ( + self.output == other.output + and self.input == other.input + and self.route == other.route + ) def __repr__(self): - return "LinkQualityAndRouteData(ouput={}, input={}, route={})".format(self.output, self.input, self.route) + return "LinkQualityAndRouteData(ouput={}, input={}, route={})".format( + self.output, self.input, self.route + ) class LinkQualityAndRouteDataFactory: - def parse(self, data, message_info): lqrd = ord(data.read(1)) output = (lqrd >> 6) & 0x3 _input = (lqrd >> 4) & 0x3 - route = lqrd & 0x0f + route = lqrd & 0x0F return LinkQualityAndRouteData(output, _input, route) class Route64(object): - - def __init__(self, id_sequence, router_id_mask, link_quality_and_route_data): + def __init__( + self, id_sequence, router_id_mask, link_quality_and_route_data + ): self._id_sequence = id_sequence self._router_id_mask = router_id_mask self._link_quality_and_route_data = link_quality_and_route_data @@ -351,18 +342,22 @@ class Route64(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.id_sequence == other.id_sequence and \ - self.router_id_mask == other.router_id_mask and \ - self.link_quality_and_route_data == other.link_quality_and_route_data + return ( + self.id_sequence == other.id_sequence + and self.router_id_mask == other.router_id_mask + and self.link_quality_and_route_data + == other.link_quality_and_route_data + ) def __repr__(self): - lqrd_str = ", ".join(["{}".format(lqrd) for lqrd in self.link_quality_and_route_data]) + lqrd_str = ", ".join( + ["{}".format(lqrd) for lqrd in self.link_quality_and_route_data] + ) return "Route64(id_sequence={}, router_id_mask={}, link_quality_and_route_data=[{}])".format( self.id_sequence, hex(self.router_id_mask), lqrd_str) class Route64Factory: - def __init__(self, link_quality_and_route_data_factory): self._lqrd_factory = link_quality_and_route_data_factory @@ -373,13 +368,16 @@ class Route64Factory: link_quality_and_route_data = [] while data.tell() < len(data.getvalue()): - link_quality_and_route_data.append(self._lqrd_factory.parse(data, message_info)) + link_quality_and_route_data.append( + self._lqrd_factory.parse(data, message_info) + ) - return Route64(id_sequence, router_id_mask, link_quality_and_route_data) + return Route64( + id_sequence, router_id_mask, link_quality_and_route_data + ) class Address16(object): - def __init__(self, address): self._address = address @@ -397,15 +395,20 @@ class Address16(object): class Address16Factory: - def parse(self, data, message_info): address = struct.unpack(">H", data.read(2))[0] return Address16(address) class LeaderData(object): - - def __init__(self, partition_id, weighting, data_version, stable_data_version, leader_router_id): + def __init__( + self, + partition_id, + weighting, + data_version, + stable_data_version, + leader_router_id, + ): self._partition_id = partition_id self._weighting = weighting self._data_version = data_version @@ -435,30 +438,37 @@ class LeaderData(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.partition_id == other.partition_id and \ - self.weighting == other.weighting and \ - self.data_version == other.data_version and \ - self.stable_data_version == other.stable_data_version and \ - self.leader_router_id == other.leader_router_id + return ( + self.partition_id == other.partition_id + and self.weighting == other.weighting + and self.data_version == other.data_version + and self.stable_data_version == other.stable_data_version + and self.leader_router_id == other.leader_router_id + ) def __repr__(self): - return "LeaderData(partition_id={}, weighting={}, data_version={}, stable_data_version={}, leader_router_id={})".format( - self.partition_id, self.weighting, self.data_version, self.stable_data_version, self.leader_router_id) + return ("LeaderData(partition_id={}, weighting={}, data_version={}, stable_data_version={},", + "leader_router_id={})").format( + self.partition_id, self.weighting, self.data_version, self.stable_data_version, self.leader_router_id, ) class LeaderDataFactory: - def parse(self, data, message_info): partition_id = struct.unpack(">I", data.read(4))[0] weighting = ord(data.read(1)) data_version = ord(data.read(1)) stable_data_version = ord(data.read(1)) leader_router_id = ord(data.read(1)) - return LeaderData(partition_id, weighting, data_version, stable_data_version, leader_router_id) + return LeaderData( + partition_id, + weighting, + data_version, + stable_data_version, + leader_router_id, + ) class NetworkData(object): - def __init__(self, tlvs): self._tlvs = tlvs @@ -477,7 +487,6 @@ class NetworkData(object): class NetworkDataFactory: - def __init__(self, network_data_tlvs_factory): self._tlvs_factory = network_data_tlvs_factory @@ -487,7 +496,6 @@ class NetworkDataFactory: class TlvRequest(object): - def __init__(self, tlvs): self._tlvs = tlvs @@ -506,14 +514,12 @@ class TlvRequest(object): class TlvRequestFactory: - def parse(self, data, message_info): tlvs = [b for b in bytearray(data.read())] return TlvRequest(tlvs) class ScanMask(object): - def __init__(self, router, end_device): self._router = router self._end_device = end_device @@ -529,14 +535,17 @@ class ScanMask(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.router == other.router and self.end_device == other.end_device + return ( + self.router == other.router and self.end_device == other.end_device + ) def __repr__(self): - return "ScanMask(router={}, end_device={})".format(self.router, self.end_device) + return "ScanMask(router={}, end_device={})".format( + self.router, self.end_device + ) class ScanMaskFactory: - def parse(self, data, message_info): scan_mask = ord(data.read(1)) router = (scan_mask >> 7) & 0x01 @@ -545,17 +554,18 @@ class ScanMaskFactory: class Connectivity(object): - - def __init__(self, - pp, - link_quality_3, - link_quality_2, - link_quality_1, - leader_cost, - id_sequence, - active_routers, - sed_buffer_size=None, - sed_datagram_count=None): + def __init__( + self, + pp, + link_quality_3, + link_quality_2, + link_quality_1, + leader_cost, + id_sequence, + active_routers, + sed_buffer_size=None, + sed_datagram_count=None, + ): self._pp = pp self._link_quality_3 = link_quality_3 self._link_quality_2 = link_quality_2 @@ -605,15 +615,17 @@ class Connectivity(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.pp == other.pp and \ - self.link_quality_3 == other.link_quality_3 and \ - self.link_quality_2 == other.link_quality_2 and \ - self.link_quality_1 == other.link_quality_1 and \ - self.leader_cost == other.leader_cost and \ - self.id_sequence == other.id_sequence and \ - self.active_routers == other.active_routers and \ - self.sed_buffer_size == other.sed_buffer_size and \ - self.sed_datagram_count == other.sed_datagram_count + return ( + self.pp == other.pp + and self.link_quality_3 == other.link_quality_3 + and self.link_quality_2 == other.link_quality_2 + and self.link_quality_1 == other.link_quality_1 + and self.leader_cost == other.leader_cost + and self.id_sequence == other.id_sequence + and self.active_routers == other.active_routers + and self.sed_buffer_size == other.sed_buffer_size + and self.sed_datagram_count == other.sed_datagram_count + ) def __repr__(self): return r"Connectivity(pp={}, \ @@ -633,12 +645,11 @@ class Connectivity(object): self.id_sequence, self.active_routers, self.sed_buffer_size, - self.sed_datagram_count + self.sed_datagram_count, ) class ConnectivityFactory: - def parse(self, data, message_info): pp = ord(data.read(1)) & 0x03 link_quality_3 = ord(data.read(1)) @@ -657,19 +668,20 @@ class ConnectivityFactory: sed_buffer_size = None sed_datagram_count = None - return Connectivity(pp, - link_quality_3, - link_quality_2, - link_quality_1, - leader_cost, - id_sequence, - active_routers, - sed_buffer_size, - sed_datagram_count) + return Connectivity( + pp, + link_quality_3, + link_quality_2, + link_quality_1, + leader_cost, + id_sequence, + active_routers, + sed_buffer_size, + sed_datagram_count, + ) class LinkMargin(object): - def __init__(self, link_margin): self._link_margin = link_margin @@ -687,14 +699,12 @@ class LinkMargin(object): class LinkMarginFactory: - def parse(self, data, message_info): link_margin = ord(data.read(1)) return LinkMargin(link_margin) class Status(object): - def __init__(self, status): self._status = status @@ -712,14 +722,12 @@ class Status(object): class StatusFactory: - def parse(self, data, message_info): status = ord(data.read(1)) return Status(status) class Version(object): - def __init__(self, version): self._version = version @@ -737,14 +745,12 @@ class Version(object): class VersionFactory: - def parse(self, data, message_info): version = struct.unpack(">H", data.read(2))[0] return Version(version) class AddressFull(object): - def __init__(self, ipv6_address): self._ipv6_address = ipv6_address @@ -758,11 +764,12 @@ class AddressFull(object): return self.ipv6_address == other.ipv6_address def __repr__(self): - return "AddressFull(ipv6_address={}')".format(hexlify(self.ipv6_address)) + return "AddressFull(ipv6_address={}')".format( + hexlify(self.ipv6_address) + ) class AddressFullFactory: - def parse(self, data, message_info): data.read(1) # first byte is ignored ipv6_address = data.read(16) @@ -770,7 +777,6 @@ class AddressFullFactory: class AddressCompressed(object): - def __init__(self, cid, iid): self._cid = cid self._iid = iid @@ -789,19 +795,19 @@ class AddressCompressed(object): return self.cid == other.cid and self.iid == other.iid def __repr__(self): - return "AddressCompressed(cid={}, iid={}')".format(self.cid, hexlify(self.iid)) + return "AddressCompressed(cid={}, iid={}')".format( + self.cid, hexlify(self.iid) + ) class AddressCompressedFactory: - def parse(self, data, message_info): - cid = (ord(data.read(1)) & 0x0F) + cid = ord(data.read(1)) & 0x0F iid = bytearray(data.read(8)) return AddressCompressed(cid, iid) class AddressRegistration(object): - def __init__(self, addresses): self._addresses = addresses @@ -815,12 +821,13 @@ class AddressRegistration(object): return self.addresses == other.addresses def __repr__(self): - addresses_str = ", ".join(["{}".format(address) for address in self.addresses]) + addresses_str = ", ".join( + ["{}".format(address) for address in self.addresses] + ) return "AddressRegistration(addresses=[{}])".format(addresses_str) class AddressRegistrationFactory: - def __init__(self, addr_compressed_factory, addr_full_factory): self._addr_compressed_factory = addr_compressed_factory self._addr_full_factory = addr_full_factory @@ -833,15 +840,18 @@ class AddressRegistrationFactory: data.seek(-1, io.SEEK_CUR) if compressed: - addresses.append(self._addr_compressed_factory.parse(data, message_info)) + addresses.append( + self._addr_compressed_factory.parse(data, message_info) + ) else: - addresses.append(self._addr_full_factory.parse(data, message_info)) + addresses.append( + self._addr_full_factory.parse(data, message_info) + ) return AddressRegistration(addresses) class Channel(object): - def __init__(self, channel_page, channel): self._channel_page = channel_page self._channel = channel @@ -857,15 +867,18 @@ class Channel(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.channel_page == other.channel_page and \ - self.channel == other.channel + return ( + self.channel_page == other.channel_page + and self.channel == other.channel + ) def __repr__(self): - return "Channel(channel_page={}, channel={})".format(self.channel_page, channel) + return "Channel(channel_page={}, channel={})".format( + self.channel_page, self.channel + ) class ChannelFactory: - def parse(self, data, message_info): channel_page = ord(data.read(1)) channel = struct.unpack(">H", data.read(2))[0] @@ -873,7 +886,6 @@ class ChannelFactory: class PanId: - def __init__(self, pan_id): self._pan_id = pan_id @@ -891,14 +903,12 @@ class PanId: class PanIdFactory: - def parse(self, data, message_info): pan_id = struct.unpack(">H", data.read(2))[0] return PanId(pan_id) class ActiveTimestamp(object): - def __init__(self, timestamp_seconds, timestamp_ticks, u): self._timestamp_seconds = timestamp_seconds self._timestamp_ticks = timestamp_ticks @@ -919,9 +929,11 @@ class ActiveTimestamp(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.timestamp_seconds == other.timestamp_seconds and \ - self.timestamp_ticks == other.timestamp_ticks and \ - self.u == other.u + return ( + self.timestamp_seconds == other.timestamp_seconds + and self.timestamp_ticks == other.timestamp_ticks + and self.u == other.u + ) def __repr__(self): return "ActiveTimestamp(timestamp_seconds={}, timestamp_ticks={}, u={})".format( @@ -929,19 +941,17 @@ class ActiveTimestamp(object): class ActiveTimestampFactory: - def parse(self, data, message_info): seconds = bytearray([0x00, 0x00]) + bytearray(data.read(6)) ticks = struct.unpack(">H", data.read(2))[0] timestamp_seconds = struct.unpack(">Q", bytes(seconds))[0] - timestamp_ticks = (ticks >> 1) + timestamp_ticks = ticks >> 1 u = ticks & 0x01 return ActiveTimestamp(timestamp_seconds, timestamp_ticks, u) class PendingTimestamp(object): - def __init__(self, timestamp_seconds, timestamp_ticks, u): self._timestamp_seconds = timestamp_seconds self._timestamp_ticks = timestamp_ticks @@ -962,9 +972,11 @@ class PendingTimestamp(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.timestamp_seconds == other.timestamp_seconds and \ - self.timestamp_ticks == other.timestamp_ticks and \ - self.u == other.u + return ( + self.timestamp_seconds == other.timestamp_seconds + and self.timestamp_ticks == other.timestamp_ticks + and self.u == other.u + ) def __repr__(self): return "PendingTimestamp(timestamp_seconds={}, timestamp_ticks={}, u={})".format( @@ -972,13 +984,12 @@ class PendingTimestamp(object): class PendingTimestampFactory: - def parse(self, data, message_info): seconds = bytearray([0x00, 0x00]) + bytearray(data.read(6)) ticks = struct.unpack(">H", data.read(2))[0] timestamp_seconds = struct.unpack(">Q", bytes(seconds))[0] - timestamp_ticks = (ticks >> 1) + timestamp_ticks = ticks >> 1 u = ticks & 0x01 return PendingTimestamp(timestamp_seconds, timestamp_ticks, u) @@ -991,7 +1002,6 @@ class ActiveOperationalDataset: class ActiveOperationalDatasetFactory: - def parse(self, data, message_info): return ActiveOperationalDataset() @@ -1004,13 +1014,11 @@ class PendingOperationalDataset: class PendingOperationalDatasetFactory: - def parse(self, data, message_info): return PendingOperationalDataset() class ThreadDiscovery(object): - def __init__(self, tlvs): self._tlvs = tlvs @@ -1024,8 +1032,8 @@ class ThreadDiscovery(object): def __repr__(self): return "ThreadDiscovery(tlvs={})".format(self.tlvs) -class ThreadDiscoveryFactory: +class ThreadDiscoveryFactory: def __init__(self, thread_discovery_tlvs_factory): self._tlvs_factory = thread_discovery_tlvs_factory @@ -1040,11 +1048,12 @@ class TimeRequest: def __init__(self): print("TimeRequest is not implemented yet.") -class TimeRequestFactory: +class TimeRequestFactory: def parse(self, data, message_info): return TimeRequest() + class TimeParameter: # TODO: Not implemented yet @@ -1053,13 +1062,11 @@ class TimeParameter: class TimeParameterFactory: - def parse(self, data, message_info): return TimeParameter() class MleCommand(object): - def __init__(self, _type, tlvs): self._type = _type self._tlvs = tlvs @@ -1074,7 +1081,9 @@ class MleCommand(object): def __repr__(self): tlvs_str = ", ".join(["{}".format(tlv) for tlv in self.tlvs]) - return "MleCommand(type={}, tlvs=[{}])".format(self.type.name, tlvs_str) + return "MleCommand(type={}, tlvs=[{}])".format( + self.type.name, tlvs_str + ) class MleCommandFactory: @@ -1096,7 +1105,11 @@ class MleCommandFactory: try: return self._tlvs_factories[_type] except KeyError: - raise KeyError("Could not find TLV factory. Unsupported TLV type: {}".format(_type)) + raise KeyError( + "Could not find TLV factory. Unsupported TLV type: {}".format( + _type + ) + ) def _parse_tlv(self, data, message_info): _type = TlvType(ord(data.read(1))) @@ -1119,7 +1132,6 @@ class MleCommandFactory: class MleMessage(object): - def __init__(self, command): self._command = command @@ -1132,7 +1144,6 @@ class MleMessage(object): class MleMessageSecured(MleMessage): - def __init__(self, aux_sec_hdr, command, mic): super(MleMessageSecured, self).__init__(command) self._aux_sec_hdr = aux_sec_hdr @@ -1152,8 +1163,9 @@ class MleMessageSecured(MleMessage): class MleMessageFactory: - - def __init__(self, aux_sec_hdr_factory, mle_command_factory, crypto_engine): + def __init__( + self, aux_sec_hdr_factory, mle_command_factory, crypto_engine + ): self._aux_sec_hdr_factory = aux_sec_hdr_factory self._mle_command_factory = mle_command_factory self._crypto_engine = crypto_engine @@ -1163,12 +1175,18 @@ class MleMessageFactory: enc_data_length = len(data.getvalue()) - enc_data = bytearray(data.read(enc_data_length - data.tell() - self._crypto_engine.mic_length)) + enc_data = bytearray( + data.read( + enc_data_length - data.tell() - self._crypto_engine.mic_length + ) + ) mic = bytearray(data.read()) dec_data = self._crypto_engine.decrypt(enc_data, mic, message_info) - command = self._mle_command_factory.parse(io.BytesIO(dec_data), message_info) + command = self._mle_command_factory.parse( + io.BytesIO(dec_data), message_info + ) return MleMessageSecured(aux_sec_hdr, command, mic) @@ -1188,4 +1206,7 @@ class MleMessageFactory: else: raise RuntimeError( - "Could not create MLE message. Unknown security indicator value: {}".format(security_indicator)) + "Could not create MLE message. Unknown security indicator value: {}".format( + security_indicator + ) + ) diff --git a/tests/scripts/thread-cert/net_crypto.py b/tests/scripts/thread-cert/net_crypto.py index 03d8f71b8..6bdd263a7 100644 --- a/tests/scripts/thread-cert/net_crypto.py +++ b/tests/scripts/thread-cert/net_crypto.py @@ -63,7 +63,8 @@ class CryptoEngine: tuple: Encrypted message (bytearray), MIC (bytearray) """ - key, nonce, auth_data = self._crypto_material_creator.create_key_and_nonce_and_authenticated_data(message_info) + key, nonce, auth_data = self._crypto_material_creator.create_key_and_nonce_and_authenticated_data( + message_info) cipher = AES.new(key, AES.MODE_CCM, nonce, mac_len=self.mic_length) cipher.update(auth_data) @@ -82,7 +83,8 @@ class CryptoEngine: bytearray: Decrypted message. """ - key, nonce, auth_data = self._crypto_material_creator.create_key_and_nonce_and_authenticated_data(message_info) + key, nonce, auth_data = self._crypto_material_creator.create_key_and_nonce_and_authenticated_data( + message_info) cipher = AES.new(key, AES.MODE_CCM, nonce, mac_len=self.mic_length) cipher.update(auth_data) @@ -132,7 +134,6 @@ class CryptoMaterialCreator(object): class MacCryptoMaterialCreator(CryptoMaterialCreator): - def __init__(self, master_key): """ Args: @@ -157,7 +158,9 @@ class MacCryptoMaterialCreator(CryptoMaterialCreator): """ return bytes(eui64 + struct.pack(">LB", frame_counter, security_level)) - def _create_authenticated_data(self, mhr, auxiliary_security_header, nonpayload_fields): + def _create_authenticated_data( + self, mhr, auxiliary_security_header, nonpayload_fields + ): """ Create Authenticated Data Read more: 7.6.3.3 CCM prerequisites - Std 802.15.4-2006 @@ -174,15 +177,21 @@ class MacCryptoMaterialCreator(CryptoMaterialCreator): return bytes(mhr + auxiliary_security_header + nonpayload_fields) def create_key_and_nonce_and_authenticated_data(self, message_info): - _, mac_key = self._generate_keys(message_info.aux_sec_hdr.sequence_counter) + _, mac_key = self._generate_keys( + message_info.aux_sec_hdr.sequence_counter + ) - nonce = self._create_nonce(message_info.source_mac_address, - message_info.aux_sec_hdr.frame_counter, - message_info.aux_sec_hdr.security_level) + nonce = self._create_nonce( + message_info.source_mac_address, + message_info.aux_sec_hdr.frame_counter, + message_info.aux_sec_hdr.security_level, + ) - auth_data = self._create_authenticated_data(message_info.mhr_bytes, - message_info.aux_sec_hdr_bytes, - message_info.nonpayload_fields) + auth_data = self._create_authenticated_data( + message_info.mhr_bytes, + message_info.aux_sec_hdr_bytes, + message_info.nonpayload_fields, + ) return mac_key, nonce, auth_data @@ -192,7 +201,6 @@ class MacCryptoMaterialCreator(CryptoMaterialCreator): class MleCryptoMaterialCreator(CryptoMaterialCreator): - def __init__(self, master_key): """ Args: @@ -215,9 +223,14 @@ class MleCryptoMaterialCreator(CryptoMaterialCreator): bytes: created Nonce """ - return bytes(source_eui64[:8] + struct.pack(">LB", frame_counter, security_level)) + return bytes( + source_eui64[:8] + + struct.pack(">LB", frame_counter, security_level) + ) - def _create_authenticated_data(self, source_address, destination_address, auxiliary_security_header): + def _create_authenticated_data( + self, source_address, destination_address, auxiliary_security_header + ): """ Create Authenticated Data Read more: 4.8 - Thread v1.0 Specification @@ -231,18 +244,28 @@ class MleCryptoMaterialCreator(CryptoMaterialCreator): bytes: Authenticated Data """ - return bytes(source_address.packed + destination_address.packed + auxiliary_security_header) + return bytes( + source_address.packed + + destination_address.packed + + auxiliary_security_header + ) def create_key_and_nonce_and_authenticated_data(self, message_info): - mle_key, _ = self._generate_keys(message_info.aux_sec_hdr.sequence_counter) + mle_key, _ = self._generate_keys( + message_info.aux_sec_hdr.sequence_counter + ) - nonce = self._create_nonce(message_info.source_mac_address.mac_address, - message_info.aux_sec_hdr.frame_counter, - message_info.aux_sec_hdr.security_level) + nonce = self._create_nonce( + message_info.source_mac_address.mac_address, + message_info.aux_sec_hdr.frame_counter, + message_info.aux_sec_hdr.security_level, + ) - auth_data = self._create_authenticated_data(message_info.source_ipv6, - message_info.destination_ipv6, - message_info.aux_sec_hdr_bytes) + auth_data = self._create_authenticated_data( + message_info.source_ipv6, + message_info.destination_ipv6, + message_info.aux_sec_hdr_bytes, + ) return mle_key, nonce, auth_data @@ -252,8 +275,14 @@ class MleCryptoMaterialCreator(CryptoMaterialCreator): class AuxiliarySecurityHeader: - - def __init__(self, key_id_mode, security_level, frame_counter, key_id, big_endian=True): + def __init__( + self, + key_id_mode, + security_level, + frame_counter, + key_id, + big_endian=True, + ): """ Args: key_id_mode (int) @@ -275,14 +304,18 @@ class AuxiliarySecurityHeader: key_source = self.key_id[:8] format = ">Q" if self._big_endian else "> 3) & 0x03 return security_level, key_id_mode @@ -341,18 +374,26 @@ class AuxiliarySecurityHeaderFactory: return self._key_id_lengths[key_id_mode] def parse(self, data, message_info): - security_control_bytes = bytearray(data.read(self._SECURITY_CONTROL_LENGTH)) + security_control_bytes = bytearray( + data.read(self._SECURITY_CONTROL_LENGTH) + ) frame_counter_bytes = bytearray(data.read(self._FRAME_COUNTER_LENGTH)) - security_level, key_id_mode = self._parse_security_control(security_control_bytes[0]) + security_level, key_id_mode = self._parse_security_control( + security_control_bytes[0] + ) frame_counter = self._parse_frame_counter(frame_counter_bytes) key_id_length = self._key_id_length(key_id_mode) key_id_bytes = bytearray(data.read(key_id_length)) - aux_sec_hdr = AuxiliarySecurityHeader(key_id_mode, security_level, frame_counter, key_id_bytes) + aux_sec_hdr = AuxiliarySecurityHeader( + key_id_mode, security_level, frame_counter, key_id_bytes + ) - message_info.aux_sec_hdr_bytes = security_control_bytes + frame_counter_bytes + key_id_bytes + message_info.aux_sec_hdr_bytes = ( + security_control_bytes + frame_counter_bytes + key_id_bytes + ) message_info.aux_sec_hdr = aux_sec_hdr return aux_sec_hdr diff --git a/tests/scripts/thread-cert/network_data.py b/tests/scripts/thread-cert/network_data.py index c0e6e797d..edf40f86f 100644 --- a/tests/scripts/thread-cert/network_data.py +++ b/tests/scripts/thread-cert/network_data.py @@ -49,7 +49,6 @@ class TlvType(IntEnum): class NetworkData(object): - def __init__(self, stable): self._stable = stable @@ -59,7 +58,6 @@ class NetworkData(object): class NetworkDataSubTlvsFactory(SubTlvsFactory): - def parse(self, data, message_info): sub_tlvs = [] @@ -67,7 +65,7 @@ class NetworkDataSubTlvsFactory(SubTlvsFactory): data_byte = ord(data.read(1)) stable = data_byte & 0x01 - _type = (data_byte >> 1) & 0x7f + _type = (data_byte >> 1) & 0x7F length = ord(data.read(1)) value = data.read(length) @@ -83,7 +81,6 @@ class NetworkDataSubTlvsFactory(SubTlvsFactory): class Route(object): - def __init__(self, border_router_16, prf): self._border_router_16 = border_router_16 self._prf = prf @@ -99,14 +96,18 @@ class Route(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.border_router_16 == other.border_router_16 and self.prf == other.prf + return ( + self.border_router_16 == other.border_router_16 + and self.prf == other.prf + ) def __repr__(self): - return "Route(border_router_16={}, prf={})".format(self.border_router_16, self.prf) + return "Route(border_router_16={}, prf={})".format( + self.border_router_16, self.prf + ) class RouteFactory(object): - def parse(self, data, message_info): border_router_16 = struct.unpack(">H", data.read(2))[0] @@ -117,7 +118,6 @@ class RouteFactory(object): class RoutesFactory(object): - def __init__(self, route_factory): self._route_factory = route_factory @@ -133,7 +133,6 @@ class RoutesFactory(object): class HasRoute(NetworkData): - def __init__(self, routes, stable): super(HasRoute, self).__init__(stable) self._routes = routes @@ -149,11 +148,12 @@ class HasRoute(NetworkData): def __repr__(self): routes_str = ", ".join(["{}".format(route) for route in self.routes]) - return "HasRoute(stable={}, routes=[{}])".format(self.stable, routes_str) + return "HasRoute(stable={}, routes=[{}])".format( + self.stable, routes_str + ) class HasRouteFactory(object): - def __init__(self, routes_factory): self._routes_factory = routes_factory @@ -164,7 +164,6 @@ class HasRouteFactory(object): class Prefix(NetworkData): - def __init__(self, domain_id, prefix_length, prefix, sub_tlvs, stable): super(Prefix, self).__init__(stable) self._domain_id = domain_id @@ -191,25 +190,25 @@ class Prefix(NetworkData): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.domain_id == other.domain_id and \ - self.prefix_length == other.prefix_length and \ - self.prefix == other.prefix and \ - self.sub_tlvs == other.sub_tlvs + return ( + self.domain_id == other.domain_id + and self.prefix_length == other.prefix_length + and self.prefix == other.prefix + and self.sub_tlvs == other.sub_tlvs + ) def __repr__(self): sub_tlvs_str = ", ".join(["{}".format(tlv) for tlv in self.sub_tlvs]) return "Prefix(stable={}, domain_id={}, prefix_length={}, prefix={}, sub_tlvs=[{}])".format( - self.stable, self.domain_id, self.prefix_length, hexlify(self.prefix), sub_tlvs_str) + self.stable, self.domain_id, self.prefix_length, hexlify(self.prefix), sub_tlvs_str, ) class PrefixSubTlvsFactory(NetworkDataSubTlvsFactory): - def __init__(self, sub_tlvs_factories): super(PrefixSubTlvsFactory, self).__init__(sub_tlvs_factories) class PrefixFactory(object): - def __init__(self, sub_tlvs_factory): self._sub_tlvs_factory = sub_tlvs_factory @@ -223,13 +222,16 @@ class PrefixFactory(object): prefix = bytearray(data.read(self._bits_to_bytes(prefix_length))) - sub_tlvs = self._sub_tlvs_factory.parse(io.BytesIO(data.read()), message_info) + sub_tlvs = self._sub_tlvs_factory.parse( + io.BytesIO(data.read()), message_info + ) - return Prefix(domain_id, prefix_length, prefix, sub_tlvs, message_info.stable) + return Prefix( + domain_id, prefix_length, prefix, sub_tlvs, message_info.stable + ) class BorderRouter(NetworkData): - def __init__(self, border_router_16, prf, p, s, d, c, r, o, n, stable): super(BorderRouter, self).__init__(stable) self._border_router_16 = border_router_16 @@ -281,28 +283,29 @@ class BorderRouter(NetworkData): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.border_router_16 == other.border_router_16 and \ - self.prf == other.prf and \ - self.p == other.p and \ - self.s == other.s and \ - self.d == other.d and \ - self.c == other.c and \ - self.r == other.r and \ - self.o == other.o and \ - self.n == other.n + return ( + self.border_router_16 == other.border_router_16 + and self.prf == other.prf + and self.p == other.p + and self.s == other.s + and self.d == other.d + and self.c == other.c + and self.r == other.r + and self.o == other.o + and self.n == other.n + ) def __repr__(self): return "BorderRouter(stable={}, border_router_16={}, prf={}, p={}, s={}, d={}, c={}, r={}, o={}, n={})".format( - self.stable, self.border_router_16, self.prf, self.p, self.s, self.d, self.c, self.r, self.o, self.n) + self.stable, self.border_router_16, self.prf, self.p, self.s, self.d, self.c, self.r, self.o, self.n, ) class BorderRouterFactory(object): - def parse(self, data, message_info): border_router_16 = struct.unpack(">H", data.read(2))[0] data_byte = ord(data.read(1)) - o = (data_byte & 0x01) + o = data_byte & 0x01 r = (data_byte >> 1) & 0x01 c = (data_byte >> 2) & 0x01 d = (data_byte >> 3) & 0x01 @@ -313,11 +316,12 @@ class BorderRouterFactory(object): data_byte = ord(data.read(1)) n = (data_byte >> 7) & 0x01 - return BorderRouter(border_router_16, prf, p, s, d, c, r, o, n, message_info.stable) + return BorderRouter( + border_router_16, prf, p, s, d, c, r, o, n, message_info.stable + ) class LowpanId(NetworkData): - def __init__(self, c, cid, context_length, stable): super(LowpanId, self).__init__(stable) self._c = c @@ -339,21 +343,23 @@ class LowpanId(NetworkData): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.c == other.c and \ - self.cid == other.cid and \ - self.context_length == other.context_length + return ( + self.c == other.c + and self.cid == other.cid + and self.context_length == other.context_length + ) def __repr__(self): return "LowpanId(stable={}, c={}, cid={}, context_length={})".format( - self.stable, self.c, self.cid, self.context_length) + self.stable, self.c, self.cid, self.context_length + ) class LowpanIdFactory(object): - def parse(self, data, message_info): data_byte = ord(data.read(1)) - cid = (data_byte & 0x0f) + cid = data_byte & 0x0F c = (data_byte >> 4) & 0x01 context_length = ord(data.read(1)) @@ -362,7 +368,6 @@ class LowpanIdFactory(object): class CommissioningData(NetworkData): - def __init__(self, sub_tlvs, stable): super(CommissioningData, self).__init__(stable) self._sub_tlvs = sub_tlvs @@ -374,33 +379,47 @@ class CommissioningData(NetworkData): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.sub_tlvs == other.sub_tlvs + return self.sub_tlvs == other.sub_tlvs def __repr__(self): - sub_tlvs_str = ", ".format(["{}".format(tlv) for tlv in self._sub_tlvs]) + sub_tlvs_str = ", ".format( + ["{}".format(tlv) for tlv in self._sub_tlvs] + ) return "CommissioningData(stable={}, sub_tlvs=[{}])".format( - self._stable, sub_tlvs_str) + self._stable, sub_tlvs_str + ) class CommissioningDataSubTlvsFactory(SubTlvsFactory): - def __init__(self, sub_tlvs_factories): - super(CommissioningDataSubTlvsFactory, self).__init__(sub_tlvs_factories) + super(CommissioningDataSubTlvsFactory, self).__init__( + sub_tlvs_factories + ) class CommissioningDataFactory(object): - def __init__(self, sub_tlvs_factory): self._sub_tlvs_factory = sub_tlvs_factory def parse(self, data, message_info): - sub_tlvs = self._sub_tlvs_factory.parse(io.BytesIO(data.read()), message_info) + sub_tlvs = self._sub_tlvs_factory.parse( + io.BytesIO(data.read()), message_info + ) return CommissioningData(sub_tlvs, message_info.stable) -class Service(NetworkData): - def __init__(self, t, _id, enterprise_number, service_data_length, service_data, sub_tlvs, stable): +class Service(NetworkData): + def __init__( + self, + t, + _id, + enterprise_number, + service_data_length, + service_data, + sub_tlvs, + stable, + ): super(Service, self).__init__(stable) self._t = t self._id = _id @@ -436,46 +455,57 @@ class Service(NetworkData): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.t == other.t and \ - self.id == other.id and \ - self.enterprise_number == other.enterprise_number and \ - self.service_data_length == other.service_data_length and \ - self.service_data == other.service_data and \ - self.sub_tlvs == other.sub_tlvs + return ( + self.t == other.t + and self.id == other.id + and self.enterprise_number == other.enterprise_number + and self.service_data_length == other.service_data_length + and self.service_data == other.service_data + and self.sub_tlvs == other.sub_tlvs + ) def __repr__(self): sub_tlvs_str = ", ".format(["{}".format(tlv) for tlv in self.sub_tlvs]) - return "LowpanId(stable={}, t={}, id={}, enterprise_number={}, service_data_length={}, service_data={}, sub_tlvs=[{}])".format( - self.stable, self.t, self.id, self.enterprise_number, self.service_data_length, self.service_data, sub_tlvs_str) + return ("LowpanId(stable={}, t={}, id={}, enterprise_number={}, service_data_length={}, service_data={},", + "sub_tlvs=[{}])").format( + self.stable, self.t, self.id, self.enterprise_number, self.service_data_length, self.service_data, + sub_tlvs_str, ) class ServiceSubTlvsFactory(NetworkDataSubTlvsFactory): - def __init__(self, sub_tlvs_factories): super(ServiceSubTlvsFactory, self).__init__(sub_tlvs_factories) class ServiceFactory(object): - def __init__(self, sub_tlvs_factory): self._sub_tlvs_factory = sub_tlvs_factory def parse(self, data, message_info): data_byte = ord(data.read(1)) t = (data_byte >> 7) & 0x01 - _id = (data_byte & 0x0f) + _id = data_byte & 0x0F enterprise_number = struct.unpack(">L", data.read(4))[0] service_data_length = ord(data.read(1)) service_data = data.read(service_data_length) - sub_tlvs = self._sub_tlvs_factory.parse(io.BytesIO(data.read()), message_info) + sub_tlvs = self._sub_tlvs_factory.parse( + io.BytesIO(data.read()), message_info + ) - return Service(t, _id, enterprise_number, service_data_length, service_data, sub_tlvs, message_info.stable) + return Service( + t, + _id, + enterprise_number, + service_data_length, + service_data, + sub_tlvs, + message_info.stable, + ) class Server(NetworkData): - def __init__(self, server_16, server_data, stable): super(Server, self).__init__(stable) self._server_16 = server_16 @@ -492,16 +522,18 @@ class Server(NetworkData): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.server_16 == other.server_16 and \ - self.server_data == other.server_data + return ( + self.server_16 == other.server_16 + and self.server_data == other.server_data + ) def __repr__(self): return "LowpanId(stable={}, server_16={}, server_data=b'{}')".format( - self.stable, self.server_16, hexlify(self.server_data)) + self.stable, self.server_16, hexlify(self.server_data) + ) class ServerFactory(object): - def parse(self, data, message_info): server_16 = struct.unpack(">H", data.read(2))[0] server_data = bytearray(data.read()) @@ -510,6 +542,5 @@ class ServerFactory(object): class NetworkDataTlvsFactory(NetworkDataSubTlvsFactory): - def __init__(self, sub_tlvs_factories): super(NetworkDataTlvsFactory, self).__init__(sub_tlvs_factories) diff --git a/tests/scripts/thread-cert/network_layer.py b/tests/scripts/thread-cert/network_layer.py index 796b3af18..99081fb7f 100644 --- a/tests/scripts/thread-cert/network_layer.py +++ b/tests/scripts/thread-cert/network_layer.py @@ -27,7 +27,6 @@ # POSSIBILITY OF SUCH DAMAGE. # -import io import struct from binascii import hexlify @@ -60,7 +59,6 @@ class StatusValues(IntEnum): class TargetEid(object): - def __init__(self, eid): self._eid = eid @@ -77,7 +75,6 @@ class TargetEid(object): class TargetEidFactory(object): - def parse(self, data, message_info): eid = bytearray(data.read(16)) @@ -85,7 +82,6 @@ class TargetEidFactory(object): class MacExtendedAddress(object): - def __init__(self, mac_address): self._mac_address = mac_address @@ -98,11 +94,12 @@ class MacExtendedAddress(object): return self.mac_address == other.mac_address def __repr__(self): - return "MacExtendedAddress(mac_address={})".format(hexlify(self.mac_address)) + return "MacExtendedAddress(mac_address={})".format( + hexlify(self.mac_address) + ) class MacExtendedAddressFactory(object): - def parse(self, data, message_info): mac_address = bytearray(data.read(8)) @@ -110,7 +107,6 @@ class MacExtendedAddressFactory(object): class Rloc16(object): - def __init__(self, rloc16): self._rloc16 = rloc16 @@ -127,7 +123,6 @@ class Rloc16(object): class Rloc16Factory(object): - def parse(self, data, message_info): rloc16 = struct.unpack(">H", data.read(2))[0] @@ -135,7 +130,6 @@ class Rloc16Factory(object): class MlEid(object): - def __init__(self, ml_eid): self._ml_eid = ml_eid @@ -152,7 +146,6 @@ class MlEid(object): class MlEidFactory(object): - def parse(self, data, message_info): ml_eid = bytearray(data.read(8)) @@ -160,7 +153,6 @@ class MlEidFactory(object): class Status(object): - def __init__(self, status): self._status = status @@ -177,7 +169,6 @@ class Status(object): class StatusFactory(object): - def parse(self, data, message_info): status = StatusValues(ord(data.read(1))) @@ -185,7 +176,6 @@ class StatusFactory(object): class TimeSinceLastTransaction(object): - def __init__(self, seconds): self._seconds = seconds @@ -202,7 +192,6 @@ class TimeSinceLastTransaction(object): class TimeSinceLastTransactionFactory(object): - def parse(self, data, message_info): seconds = struct.unpack(">L", data.read(4))[0] @@ -210,7 +199,6 @@ class TimeSinceLastTransactionFactory(object): class RouterMask(object): - def __init__(self, id_sequence, router_id_mask): self._id_sequence = id_sequence self._router_id_mask = router_id_mask @@ -225,14 +213,18 @@ class RouterMask(object): def __eq__(self, other): common.expect_the_same_class(self, other) - return self.id_sequence == other.id_sequence and self.router_id_mask == other.router_id_mask + return ( + self.id_sequence == other.id_sequence + and self.router_id_mask == other.router_id_mask + ) def __repr__(self): - return "RouterMask(id_sequence={}, router_id_mask={})".format(self.id_sequence, hex(self.router_id_mask)) + return "RouterMask(id_sequence={}, router_id_mask={})".format( + self.id_sequence, hex(self.router_id_mask) + ) class RouterMaskFactory(object): - def parse(self, data, message_info): id_sequence = ord(data.read(1)) router_id_mask = struct.unpack(">Q", data.read(8))[0] @@ -241,7 +233,6 @@ class RouterMaskFactory(object): class NdOption(object): - def __init__(self, options): self._options = options @@ -254,11 +245,12 @@ class NdOption(object): return self.options == other.options def __repr__(self): - return "NdOption(options=[{}])".format(", ".join([str(opt) for opt in self.options])) + return "NdOption(options=[{}])".format( + ", ".join([str(opt) for opt in self.options]) + ) class NdOptionFactory(object): - def parse(self, data, message_info): options = [opt for opt in bytearray(data.read())] return NdOption(options) @@ -275,6 +267,7 @@ class NdDataFactory(object): def parse(self, data, message_info): raise NotImplementedError("TODO: Not implemented yet") + class XtalAccuracy: # TODO: Not implemented yet @@ -283,13 +276,11 @@ class XtalAccuracy: class XtalAccuracyFactory: - def parse(self, data, message_info): return XtalAccuracy() class ThreadNetworkData(object): - def __init__(self, tlvs): self._tlvs = tlvs @@ -302,15 +293,15 @@ class ThreadNetworkData(object): return self.tlvs == other.tlvs def __repr__(self): - return "ThreadNetworkData(tlvs=[{}])".format(", ".join([str(tlv) for tlv in self.tlvs])) + return "ThreadNetworkData(tlvs=[{}])".format( + ", ".join([str(tlv) for tlv in self.tlvs]) + ) class ThreadNetworkDataFactory(object): - def __init__(self, network_data_tlvs_factory): self._network_data_tlvs_factory = network_data_tlvs_factory def parse(self, data, message_info): tlvs = self._network_data_tlvs_factory.parse(data, message_info) return ThreadNetworkData(tlvs) - diff --git a/tests/scripts/thread-cert/node.py b/tests/scripts/thread-cert/node.py index bc7800da1..c484d9ddb 100755 --- a/tests/scripts/thread-cert/node.py +++ b/tests/scripts/thread-cert/node.py @@ -39,6 +39,7 @@ import socket import time import unittest + class Node: def __init__(self, nodeid, is_mtd=False, simulator=None): self.nodeid = nodeid @@ -48,7 +49,7 @@ class Node: if self.simulator: self.simulator.add_node(self) - mode = os.environ.get('USE_MTD') is '1' and is_mtd and 'mtd' or 'ftd' + mode = os.environ.get('USE_MTD') == '1' and is_mtd and 'mtd' or 'ftd' if self.node_type == 'soc': self.__init_soc(nodeid) @@ -81,7 +82,7 @@ class Node: os.environ['NODE_ID'] = str(nodeid) cmd += ' %d' % nodeid - print ("%s" % cmd) + print("%s" % cmd) self.pexpect = pexpect.popen_spawn.PopenSpawn(cmd, timeout=4) @@ -104,14 +105,21 @@ class Node: args = '' if 'OT_NCP_PATH' in os.environ.keys(): - cmd = 'spinel-cli.py -p "%s%s" -n' % (os.environ['OT_NCP_PATH'], args) + cmd = 'spinel-cli.py -p "%s%s" -n' % ( + os.environ['OT_NCP_PATH'], + args, + ) elif "top_builddir" in os.environ.keys(): builddir = os.environ['top_builddir'] - cmd = 'spinel-cli.py -p "%s/examples/apps/ncp/ot-ncp-%s%s" -n' % (builddir, mode, args) + cmd = 'spinel-cli.py -p "%s/examples/apps/ncp/ot-ncp-%s%s" -n' % ( + builddir, + mode, + args, + ) else: cmd = 'spinel-cli.py -p "./ot-ncp-%s%s" -n' % (mode, args) cmd += ' %d' % nodeid - print ("%s" % cmd) + print("%s" % cmd) self.pexpect = pexpect.spawn(cmd, timeout=4) @@ -139,8 +147,11 @@ class Node: def __init_soc(self, nodeid): """ Initialize a System-on-a-chip node connected via UART. """ import fdpexpect - serialPort = '/dev/ttyUSB%d' % ((nodeid-1)*2) - self.pexpect = fdpexpect.fdspawn(os.open(serialPort, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY)) + + serialPort = '/dev/ttyUSB%d' % ((nodeid - 1) * 2) + self.pexpect = fdpexpect.fdspawn( + os.open(serialPort, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY) + ) def __del__(self): self.destroy() @@ -149,8 +160,12 @@ class Node: if not self._initialized: return - if hasattr(self.pexpect, 'proc') and self.pexpect.proc.poll() is None or \ - not hasattr(self.pexpect, 'proc') and self.pexpect.isalive(): + if ( + hasattr(self.pexpect, 'proc') + and self.pexpect.proc.poll() is None + or not hasattr(self.pexpect, 'proc') + and self.pexpect.isalive() + ): print("%d: exit" % self.nodeid) self.pexpect.send('exit\n') self.pexpect.expect(pexpect.EOF) @@ -166,7 +181,17 @@ class Node: dummy_format_str = br"\[THCI\].*?type=%s.*?" join_ent_ntf = dummy_format_str % br"JOIN_ENT\.ntf" join_ent_rsp = dummy_format_str % br"JOIN_ENT\.rsp" - pattern = (b"(" + join_fin_req + b")|(" + join_fin_rsp + b")|("+ join_ent_ntf + b")|(" + join_ent_rsp + b")") + pattern = ( + b"(" + + join_fin_req + + b")|(" + + join_fin_rsp + + b")|(" + + join_ent_ntf + + b")|(" + + join_ent_rsp + + b")" + ) messages = [] # There are at most 4 cert messages both for joiner and commissioner @@ -175,7 +200,7 @@ class Node: self._expect(pattern, timeout=timeout) log = self.pexpect.match.group(0) messages.append(self._extract_cert_message(log)) - except: + except BaseException: break return messages @@ -200,9 +225,13 @@ class Node: res = re.search(hex_pattern, log) if not res: break - data = [int(hex, 16) for hex in res.group(0)[1:-1].split(b' ') if hex and hex != b'..'] + data = [ + int(hex, 16) + for hex in res.group(0)[1:-1].split(b' ') + if hex and hex != b'..' + ] payload += bytearray(data) - log = log[res.end()-1:] + log = log[res.end() - 1:] assert len(payload) == payload_len return (direction, type, payload) @@ -292,7 +321,7 @@ class Node: def add_whitelist(self, addr, rssi=None): cmd = 'macfilter addr add %s' % addr - if rssi != None: + if rssi is not None: cmd += ' %s' % rssi self.send_command(cmd) @@ -313,7 +342,7 @@ class Node: def get_router_id(self): rloc16 = self.get_addr16() - return (rloc16 >> 10) + return rloc16 >> 10 def get_addr64(self): self.send_command('extaddr') @@ -413,7 +442,7 @@ class Node: self._expect('Done') return panid - def set_panid(self, panid = config.PANID): + def set_panid(self, panid=config.PANID): cmd = 'panid %d' % panid self.send_command(cmd) self._expect('Done') @@ -526,7 +555,12 @@ class Node: addrs = self.get_addrs() for addr in addrs: segs = addr.split(':') - if segs[4] == '0' and segs[5] == 'ff' and segs[6] == 'fe00' and segs[7] != 'fc00': + if ( + segs[4] == '0' + and segs[5] == 'ff' + and segs[6] == 'fe00' + and segs[7] != 'fc00' + ): return addr return None @@ -534,7 +568,12 @@ class Node: addrs = self.get_addrs() for addr in addrs: segs = addr.split(':') - if segs[4] == '0' and segs[5] == 'ff' and segs[6] == 'fe00' and segs[7] == 'fc00': + if ( + segs[4] == '0' + and segs[5] == 'ff' + and segs[6] == 'fe00' + and segs[7] == 'fc00' + ): return addr return None @@ -554,7 +593,11 @@ class Node: return eidcaches def add_service(self, enterpriseNumber, serviceData, serverData): - cmd = 'service add %s %s %s' % (enterpriseNumber, serviceData, serverData) + cmd = 'service add %s %s %s' % ( + enterpriseNumber, + serviceData, + serverData, + ) self.send_command(cmd) self._expect('Done') @@ -573,35 +616,58 @@ class Node: def __getGlobalAddress(self): global_address = [] for ip6Addr in self.get_addrs(): - if (not re.match(config.LINK_LOCAL_REGEX_PATTERN, ip6Addr, re.I)) and \ - (not re.match(config.MESH_LOCAL_PREFIX_REGEX_PATTERN, ip6Addr, re.I)) and \ - (not re.match(config.ROUTING_LOCATOR_REGEX_PATTERN, ip6Addr, re.I)): + if ( + (not re.match(config.LINK_LOCAL_REGEX_PATTERN, ip6Addr, re.I)) + and ( + not re.match( + config.MESH_LOCAL_PREFIX_REGEX_PATTERN, ip6Addr, re.I + ) + ) + and ( + not re.match( + config.ROUTING_LOCATOR_REGEX_PATTERN, ip6Addr, re.I + ) + ) + ): global_address.append(ip6Addr) return global_address def __getRloc(self): for ip6Addr in self.get_addrs(): - if re.match(config.MESH_LOCAL_PREFIX_REGEX_PATTERN, ip6Addr, re.I) and \ - re.match(config.ROUTING_LOCATOR_REGEX_PATTERN, ip6Addr, re.I) and \ - not(re.match(config.ALOC_FLAG_REGEX_PATTERN, ip6Addr, re.I)): + if ( + re.match(config.MESH_LOCAL_PREFIX_REGEX_PATTERN, ip6Addr, re.I) + and re.match( + config.ROUTING_LOCATOR_REGEX_PATTERN, ip6Addr, re.I + ) + and not ( + re.match(config.ALOC_FLAG_REGEX_PATTERN, ip6Addr, re.I) + ) + ): return ip6Addr return None def __getAloc(self): aloc = [] for ip6Addr in self.get_addrs(): - if re.match(config.MESH_LOCAL_PREFIX_REGEX_PATTERN, ip6Addr, re.I) and \ - re.match(config.ROUTING_LOCATOR_REGEX_PATTERN, ip6Addr, re.I) and \ - re.match(config.ALOC_FLAG_REGEX_PATTERN, ip6Addr, re.I): + if ( + re.match(config.MESH_LOCAL_PREFIX_REGEX_PATTERN, ip6Addr, re.I) + and re.match( + config.ROUTING_LOCATOR_REGEX_PATTERN, ip6Addr, re.I + ) + and re.match(config.ALOC_FLAG_REGEX_PATTERN, ip6Addr, re.I) + ): aloc.append(ip6Addr) return aloc def __getMleid(self): for ip6Addr in self.get_addrs(): - if re.match(config.MESH_LOCAL_PREFIX_REGEX_PATTERN, ip6Addr, re.I) and \ - not(re.match(config.ROUTING_LOCATOR_REGEX_PATTERN, ip6Addr, re.I)): + if re.match( + config.MESH_LOCAL_PREFIX_REGEX_PATTERN, ip6Addr, re.I + ) and not ( + re.match(config.ROUTING_LOCATOR_REGEX_PATTERN, ip6Addr, re.I) + ): return ip6Addr return None @@ -643,7 +709,7 @@ class Node: self.send_command(cmd) self._expect('Done') - def add_prefix(self, prefix, flags, prf = 'med'): + def add_prefix(self, prefix, flags, prf='med'): cmd = 'prefix add %s %s %s' % (prefix, flags, prf) self.send_command(cmd) self._expect('Done') @@ -653,7 +719,7 @@ class Node: self.send_command(cmd) self._expect('Done') - def add_route(self, prefix, prf = 'med'): + def add_route(self, prefix, prf='med'): cmd = 'route add %s %s' % (prefix, prf) self.send_command(cmd) self._expect('Done') @@ -668,7 +734,13 @@ class Node: self._expect('Done') def energy_scan(self, mask, count, period, scan_duration, ipaddr): - cmd = 'commissioner energy %d %d %d %d %s' % (mask, count, period, scan_duration, ipaddr) + cmd = 'commissioner energy %d %d %d %d %s' % ( + mask, + count, + period, + scan_duration, + ipaddr, + ) self.send_command(cmd) if isinstance(self.simulator, simulator.VirtualTime): @@ -696,8 +768,12 @@ class Node: results = [] while True: - i = self._expect([r'\|\s(\S+)\s+\|\s(\S+)\s+\|\s([0-9a-fA-F]{4})\s\|\s([0-9a-fA-F]{16})\s\|\s(\d+)\r?\n', - 'Done']) + i = self._expect( + [ + r'\|\s(\S+)\s+\|\s(\S+)\s+\|\s([0-9a-fA-F]{4})\s\|\s([0-9a-fA-F]{16})\s\|\s(\d+)\r?\n', + 'Done', + ] + ) if i == 0: results.append(self.pexpect.match.groups()) else: @@ -707,7 +783,7 @@ class Node: def ping(self, ipaddr, num_responses=1, size=None, timeout=5): cmd = 'ping %s' % ipaddr - if size != None: + if size is not None: cmd += ' %d' % size self.send_command(cmd) @@ -739,7 +815,14 @@ class Node: self.send_command(cmd) self._expect('Done') - def set_active_dataset(self, timestamp, panid=None, channel=None, channel_mask=None, master_key=None): + def set_active_dataset( + self, + timestamp, + panid=None, + channel=None, + channel_mask=None, + master_key=None, + ): self.send_command('dataset clear') self._expect('Done') @@ -747,22 +830,22 @@ class Node: self.send_command(cmd) self._expect('Done') - if panid != None: + if panid is not None: cmd = 'dataset panid %d' % panid self.send_command(cmd) self._expect('Done') - if channel != None: + if channel is not None: cmd = 'dataset channel %d' % channel self.send_command(cmd) self._expect('Done') - if channel_mask != None: + if channel_mask is not None: cmd = 'dataset channelmask %d' % channel_mask self.send_command(cmd) self._expect('Done') - if master_key != None: + if master_key is not None: cmd = 'dataset masterkey %s' % master_key self.send_command(cmd) self._expect('Done') @@ -770,7 +853,9 @@ class Node: self.send_command('dataset commit active') self._expect('Done') - def set_pending_dataset(self, pendingtimestamp, activetimestamp, panid=None, channel=None): + def set_pending_dataset( + self, pendingtimestamp, activetimestamp, panid=None, channel=None + ): self.send_command('dataset clear') self._expect('Done') @@ -782,12 +867,12 @@ class Node: self.send_command(cmd) self._expect('Done') - if panid != None: + if panid is not None: cmd = 'dataset panid %d' % panid self.send_command(cmd) self._expect('Done') - if channel != None: + if channel is not None: cmd = 'dataset channel %d' % channel self.send_command(cmd) self._expect('Done') @@ -796,69 +881,93 @@ class Node: self._expect('Done') def announce_begin(self, mask, count, period, ipaddr): - cmd = 'commissioner announce %d %d %d %s' % (mask, count, period, ipaddr) + cmd = 'commissioner announce %d %d %d %s' % ( + mask, + count, + period, + ipaddr, + ) self.send_command(cmd) self._expect('Done') - def send_mgmt_active_set(self, active_timestamp=None, channel=None, channel_mask=None, extended_panid=None, - panid=None, master_key=None, mesh_local=None, network_name=None, binary=None): + def send_mgmt_active_set( + self, + active_timestamp=None, + channel=None, + channel_mask=None, + extended_panid=None, + panid=None, + master_key=None, + mesh_local=None, + network_name=None, + binary=None, + ): cmd = 'dataset mgmtsetcommand active ' - if active_timestamp != None: + if active_timestamp is not None: cmd += 'activetimestamp %d ' % active_timestamp - if channel != None: + if channel is not None: cmd += 'channel %d ' % channel - if channel_mask != None: + if channel_mask is not None: cmd += 'channelmask %d ' % channel_mask - if extended_panid != None: + if extended_panid is not None: cmd += 'extpanid %s ' % extended_panid - if panid != None: + if panid is not None: cmd += 'panid %d ' % panid - if master_key != None: + if master_key is not None: cmd += 'masterkey %s ' % master_key - if mesh_local != None: + if mesh_local is not None: cmd += 'localprefix %s ' % mesh_local - if network_name != None: + if network_name is not None: cmd += 'networkname %s ' % network_name - if binary != None: + if binary is not None: cmd += 'binary %s ' % binary self.send_command(cmd) self._expect('Done') - def send_mgmt_pending_set(self, pending_timestamp=None, active_timestamp=None, delay_timer=None, channel=None, - panid=None, master_key=None, mesh_local=None, network_name=None): + def send_mgmt_pending_set( + self, + pending_timestamp=None, + active_timestamp=None, + delay_timer=None, + channel=None, + panid=None, + master_key=None, + mesh_local=None, + network_name=None, + ): cmd = 'dataset mgmtsetcommand pending ' - if pending_timestamp != None: + if pending_timestamp is not None: cmd += 'pendingtimestamp %d ' % pending_timestamp - if active_timestamp != None: + if active_timestamp is not None: cmd += 'activetimestamp %d ' % active_timestamp - if delay_timer != None: + if delay_timer is not None: cmd += 'delaytimer %d ' % delay_timer - if channel != None: + if channel is not None: cmd += 'channel %d ' % channel - if panid != None: + if panid is not None: cmd += 'panid %d ' % panid - if master_key != None: + if master_key is not None: cmd += 'masterkey %s ' % master_key - if mesh_local != None: + if mesh_local is not None: cmd += 'localprefix %s ' % mesh_local - if network_name != None: + if network_name is not None: cmd += 'networkname %s ' % network_name self.send_command(cmd) @@ -943,5 +1052,6 @@ class Node: payload += tlv.to_hex() self.commissioner_mgmtset(self.bytes_to_hex_str(payload)) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/pcap.py b/tests/scripts/thread-cert/pcap.py index 61026bcde..51e88c80a 100644 --- a/tests/scripts/thread-cert/pcap.py +++ b/tests/scripts/thread-cert/pcap.py @@ -33,7 +33,7 @@ import struct import time DLT_IEEE802_15_4 = 195 -PCAP_MAGIC_NUMBER = 0xa1b2c3d4 +PCAP_MAGIC_NUMBER = 0xA1B2C3D4 PCAP_VERSION_MAJOR = 2 PCAP_VERSION_MINOR = 4 @@ -48,12 +48,16 @@ class PcapCodec(object): def encode_header(self): """ Returns a pcap file header. """ - return struct.pack(" self._pause_time and self.current_nodeid): + if ( + self.current_event + or len(self.awake_devices) + or ( + self._next_event_time() > self._pause_time + and self.current_nodeid + ) + ): self.sock.settimeout(self.BLOCK_TIMEOUT) try: msg, addr = self.sock.recvfrom(self.MAX_MESSAGE) @@ -258,7 +277,7 @@ class VirtualTime(BaseSimulator): self.devices[addr]['msgs'] = [] self.devices[addr]['time'] = self.current_time self.awake_devices.discard(addr) - #print "New device:", addr, self.devices + # print "New device:", addr, self.devices delay, type, datalen = struct.unpack('=QBH', msg[:11]) data = msg[11:] @@ -266,7 +285,14 @@ class VirtualTime(BaseSimulator): event_time = self.current_time + delay if data: - dbg_print("New event: ", event_time, addr, type, datalen, binascii.hexlify(data)) + dbg_print( + "New event: ", + event_time, + addr, + type, + datalen, + binascii.hexlify(data), + ) else: dbg_print("New event: ", event_time, addr, type, datalen) @@ -274,19 +300,22 @@ class VirtualTime(BaseSimulator): # remove any existing alarm event for device if self.devices[addr]['alarm']: self.event_queue.remove(self.devices[addr]['alarm']) - #print "-- Remove\t", self.devices[addr]['alarm'] + # print "-- Remove\t", self.devices[addr]['alarm'] # add alarm event to event queue event = (event_time, self.event_sequence, addr, type, datalen) self.event_sequence += 1 - #print "-- Enqueue\t", event, delay, self.current_time + # print "-- Enqueue\t", event, delay, self.current_time bisect.insort(self.event_queue, event) self.devices[addr]['alarm'] = event self.awake_devices.discard(addr) - if self.current_event and self.current_event[self.EVENT_ADDR] == addr: - #print "Done\t", self.current_event + if ( + self.current_event + and self.current_event[self.EVENT_ADDR] == addr + ): + # print "Done\t", self.current_event self.current_event = None elif type == self.OT_SIM_EVENT_RADIO_RECEIVED: @@ -294,16 +323,32 @@ class VirtualTime(BaseSimulator): # add radio receive events event queue for device in self.devices: if device != addr and self._is_radio(device): - event = (event_time, self.event_sequence, device, type, datalen, data) + event = ( + event_time, + self.event_sequence, + device, + type, + datalen, + data, + ) self.event_sequence += 1 - #print "-- Enqueue\t", event + # print "-- Enqueue\t", event bisect.insort(self.event_queue, event) - self._pcap.append(data, (event_time // 1000000, event_time % 1000000)) + self._pcap.append( + data, (event_time // 1000000, event_time % 1000000) + ) self._add_message(addr[1] - self.port, data) # add radio transmit done events to event queue - event = (event_time, self.event_sequence, addr, type, datalen, data) + event = ( + event_time, + self.event_sequence, + addr, + type, + datalen, + data, + ) self.event_sequence += 1 bisect.insort(self.event_queue, event) @@ -312,10 +357,17 @@ class VirtualTime(BaseSimulator): elif type == self.OT_SIM_EVENT_RADIO_SPINEL_WRITE: assert not self._is_radio(addr) radio_addr = self._to_radio_addr(addr) - if not radio_addr in self.devices: + if radio_addr not in self.devices: self.awake_devices.add(radio_addr) - event = (event_time, self.event_sequence, radio_addr, self.OT_SIM_EVENT_UART_WRITE, datalen, data) + event = ( + event_time, + self.event_sequence, + radio_addr, + self.OT_SIM_EVENT_UART_WRITE, + datalen, + data, + ) self.event_sequence += 1 bisect.insort(self.event_queue, event) @@ -324,10 +376,17 @@ class VirtualTime(BaseSimulator): elif type == self.OT_SIM_EVENT_UART_WRITE: assert self._is_radio(addr) core_addr = self._to_core_addr(addr) - if not core_addr in self.devices: + if core_addr not in self.devices: self.awake_devices.add(core_addr) - event = (event_time, self.event_sequence, core_addr, self.OT_SIM_EVENT_RADIO_SPINEL_WRITE, datalen, data) + event = ( + event_time, + self.event_sequence, + core_addr, + self.OT_SIM_EVENT_RADIO_SPINEL_WRITE, + datalen, + data, + ) self.event_sequence += 1 bisect.insort(self.event_queue, event) @@ -362,11 +421,18 @@ class VirtualTime(BaseSimulator): dbg_print("Pop event: ", event_time, addr, type, datalen) else: event_time, sequence, addr, type, datalen, data = event - dbg_print("Pop event: ", event_time, addr, type, datalen, binascii.hexlify(data)) + dbg_print( + "Pop event: ", + event_time, + addr, + type, + datalen, + binascii.hexlify(data), + ) self.current_event = event - assert(event_time >= self.current_time) + assert event_time >= self.current_time self.current_time = event_time elapsed = event_time - self.devices[addr]['time'] @@ -395,7 +461,9 @@ class VirtualTime(BaseSimulator): continue dbg_print('syncing', addr, elapsed) self.devices[addr]['time'] = self.current_time - message = struct.pack('=QBH', elapsed, self.OT_SIM_EVENT_ALARM_FIRED, 0) + message = struct.pack( + '=QBH', elapsed, self.OT_SIM_EVENT_ALARM_FIRED, 0 + ) self._send_message(message, addr) self.awake_devices.add(addr) self.receive_events() diff --git a/tests/scripts/thread-cert/sniffer.py b/tests/scripts/thread-cert/sniffer.py index cc659c9f0..bb546c20e 100644 --- a/tests/scripts/thread-cert/sniffer.py +++ b/tests/scripts/thread-cert/sniffer.py @@ -46,7 +46,9 @@ import sniffer_transport class Sniffer: - """ Class representing the Sniffing node, whose main task is listening and logging message exchange performed by other nodes. """ + """ Class representing the Sniffing node, whose main task is listening + and logging message exchange performed by other nodes. + """ logger = logging.getLogger("sniffer.Sniffer") @@ -125,7 +127,8 @@ class Sniffer: def get_messages_sent_by(self, nodeid): """ Get sniffed messages. - Note! This method flushes the message queue so calling this method again will return only the newly logged messages. + Note! This method flushes the message queue so calling this + method again will return only the newly logged messages. Args: nodeid (int): node id diff --git a/tests/scripts/thread-cert/sniffer_transport.py b/tests/scripts/thread-cert/sniffer_transport.py index 9eb0bf7db..d88820a28 100644 --- a/tests/scripts/thread-cert/sniffer_transport.py +++ b/tests/scripts/thread-cert/sniffer_transport.py @@ -30,13 +30,13 @@ import ctypes import os import socket -import sys + class SnifferTransport(object): """ Interface for transport that allows eavesdrop other nodes. """ def open(self): - """ Open transport. + """ Open transport. Raises: RuntimeError: when transport is already opened or when transport opening failed. @@ -44,7 +44,7 @@ class SnifferTransport(object): raise NotImplementedError def close(self): - """ Close transport. + """ Close transport. Raises: RuntimeError: when transport is already closed. @@ -53,7 +53,7 @@ class SnifferTransport(object): @property def is_opened(self): - """ Check if transport is opened. + """ Check if transport is opened. Returns: bool: True if the transport is opened, False in otherwise @@ -79,7 +79,7 @@ class SnifferTransport(object): bufsize (int): size of buffer for incoming data. Returns: - A tuple contains data and node id. + A tuple contains data and node id. For example: (bytearray([0x00, 0x01...], 1) @@ -107,11 +107,18 @@ class SnifferSocketTransport(SnifferTransport): self.close() def _nodeid_to_address(self, nodeid, ip_address=""): - return ip_address, self.BASE_PORT + (self.PORT_OFFSET * self.WELLKNOWN_NODE_ID) + nodeid + return ( + ip_address, + self.BASE_PORT + + (self.PORT_OFFSET * self.WELLKNOWN_NODE_ID) + + nodeid, + ) def _address_to_nodeid(self, address): _, port = address - return (port - self.BASE_PORT - (self.PORT_OFFSET * self.WELLKNOWN_NODE_ID)) + return ( + port - self.BASE_PORT - (self.PORT_OFFSET * self.WELLKNOWN_NODE_ID) + ) def open(self): if self.is_opened: @@ -149,11 +156,13 @@ class SnifferSocketTransport(SnifferTransport): class MacFrame(ctypes.Structure): - _fields_ = [("buffer", ctypes.c_ubyte * 128), - ("length", ctypes.c_ubyte), - ("nodeid", ctypes.c_uint)] + _fields_ = [ + ("buffer", ctypes.c_ubyte * 128), + ("length", ctypes.c_ubyte), + ("nodeid", ctypes.c_uint), + ] + class SnifferTransportFactory(object): - def create_transport(self, nodeid): return SnifferSocketTransport(nodeid) diff --git a/tests/scripts/thread-cert/test_coap.py b/tests/scripts/thread-cert/test_coap.py index d7ebba818..63cb2c6f1 100755 --- a/tests/scripts/thread-cert/test_coap.py +++ b/tests/scripts/thread-cert/test_coap.py @@ -33,7 +33,6 @@ import string import unittest import coap -import config def any_delta(): @@ -107,8 +106,8 @@ def any_uri_path(): class TestCoapMessageOptionHeader(unittest.TestCase): - - def test_should_return_passed_on_value_when_read_extended_value_is_called_with_value_different_than_13_and_14(self): + def test_should_return_passed_on_value_when_read_extended_value_is_called_with_value_different_than_13_and_14( + self): # GIVEN value = any_4bits_value_different_than_13_and_14() @@ -118,7 +117,8 @@ class TestCoapMessageOptionHeader(unittest.TestCase): # THEN self.assertEqual(value, actual_value) - def test_should_return_value_stored_in_first_byte_plus_13_when_read_extended_value_is_called_with_value_equal_13(self): + def test_should_return_value_stored_in_first_byte_plus_13_when_read_extended_value_is_called_with_value_equal_13( + self): # GIVEN value = 13 extended_value = any_value() @@ -131,7 +131,8 @@ class TestCoapMessageOptionHeader(unittest.TestCase): # THEN self.assertEqual(extended_value + 13, actual_value) - def test_should_return_value_stored_in_first_byte_plus_269_when_read_extended_value_is_called_with_value_equal_14(self): + def test_should_return_value_stored_in_first_byte_plus_269_when_read_extended_value_is_called_with_value_equal_14( + self): # GIVEN value = 14 extended_value = any_value() @@ -144,7 +145,8 @@ class TestCoapMessageOptionHeader(unittest.TestCase): # THEN self.assertEqual(extended_value + 269, actual_value) - def test_should_create_CoapOptionHeader_when_from_bytes_classmethod_is_called(self): + def test_should_create_CoapOptionHeader_when_from_bytes_classmethod_is_called( + self): # GIVEN delta = any_4bits_value_different_than_13_and_14() length = any_4bits_value_different_than_13_and_14() @@ -158,7 +160,8 @@ class TestCoapMessageOptionHeader(unittest.TestCase): self.assertEqual(delta, option_header.delta) self.assertEqual(length, option_header.length) - def test_should_return_True_when_is_payload_marker_property_called_with_delta_and_length_equal_15(self): + def test_should_return_True_when_is_payload_marker_property_called_with_delta_and_length_equal_15( + self): # GIVEN delta = 15 length = 15 @@ -173,7 +176,6 @@ class TestCoapMessageOptionHeader(unittest.TestCase): class TestCoapOption(unittest.TestCase): - def test_should_return_type_value_when_type_property_is_called(self): # GIVEN _type = any_coap_option_type() @@ -200,8 +202,8 @@ class TestCoapOption(unittest.TestCase): class TestCoapOptionsFactory(unittest.TestCase): - - def test_should_create_list_of_CoapOption_from_bytearray_when_parse_method_is_called(self): + def test_should_create_list_of_CoapOption_from_bytearray_when_parse_method_is_called( + self): # GIVEN delta = any_4bits_value_lower_or_equal_than_12() length = any_4bits_value_lower_or_equal_than_12() @@ -221,7 +223,6 @@ class TestCoapOptionsFactory(unittest.TestCase): class TestCoapCode(unittest.TestCase): - def test_should_return_code_value_when_code_property_is_called(self): # GIVEN code = any_code() @@ -256,7 +257,7 @@ class TestCoapCode(unittest.TestCase): actual_detail = code_obj.detail # THEN - self.assertEqual(code & 0x1f, actual_detail) + self.assertEqual(code & 0x1F, actual_detail) def test_should_return_dotted_value_when_dotted_property_is_called(self): # GIVEN @@ -271,12 +272,13 @@ class TestCoapCode(unittest.TestCase): _class, detail = actual_dotted.split(".") self.assertEqual(code, (int(_class) << 5) | int(detail)) - def test_should_create_CoapCode_when_from_class_and_detail_classmethod_is_called(self): + def test_should_create_CoapCode_when_from_class_and_detail_classmethod_is_called( + self): # GIVEN code = any_code() _class = (code >> 5) & 0x7 - detail = code & 0x1f + detail = code & 0x1F # WHEN actual_coap_obj = coap.CoapCode.from_class_and_detail(_class, detail) @@ -284,7 +286,8 @@ class TestCoapCode(unittest.TestCase): # THEN self.assertEqual(code, actual_coap_obj.code) - def test_should_create_CoapCode_when_from_dotted_string_classmethod_is_called(self): + def test_should_create_CoapCode_when_from_dotted_string_classmethod_is_called( + self): # GIVEN code = any_code() @@ -298,13 +301,19 @@ class TestCoapCode(unittest.TestCase): class TestCoapMessage(unittest.TestCase): - def test_should_return_version_value_when_version_property_is_called(self): # GIVEN version = any_version() - coap_message = coap.CoapMessage(version, any_type(), any_code(), any_message_id(), - any_token(), any_options(), any_payload()) + coap_message = coap.CoapMessage( + version, + any_type(), + any_code(), + any_message_id(), + any_token(), + any_options(), + any_payload(), + ) # WHEN actual_version = coap_message.version @@ -316,8 +325,15 @@ class TestCoapMessage(unittest.TestCase): # GIVEN _type = any_type() - coap_message = coap.CoapMessage(any_version(), _type, any_code(), any_message_id(), - any_token(), any_options(), any_payload()) + coap_message = coap.CoapMessage( + any_version(), + _type, + any_code(), + any_message_id(), + any_token(), + any_options(), + any_payload(), + ) # WHEN actual_type = coap_message.type @@ -329,8 +345,15 @@ class TestCoapMessage(unittest.TestCase): # GIVEN code = any_code() - coap_message = coap.CoapMessage(any_version(), any_type(), code, any_message_id(), - any_token(), any_options(), any_payload()) + coap_message = coap.CoapMessage( + any_version(), + any_type(), + code, + any_message_id(), + any_token(), + any_options(), + any_payload(), + ) # WHEN actual_code = coap_message.code @@ -338,12 +361,21 @@ class TestCoapMessage(unittest.TestCase): # THEN self.assertEqual(code, actual_code) - def test_should_return_message_id_value_when_message_id_property_is_called(self): + def test_should_return_message_id_value_when_message_id_property_is_called( + self + ): # GIVEN message_id = any_message_id() - coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), message_id, - any_token(), any_options(), any_payload()) + coap_message = coap.CoapMessage( + any_version(), + any_type(), + any_code(), + message_id, + any_token(), + any_options(), + any_payload(), + ) # WHEN actual_message_id = coap_message.message_id @@ -355,8 +387,15 @@ class TestCoapMessage(unittest.TestCase): # GIVEN token = any_token() - coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), any_message_id(), - token, any_options(), any_payload()) + coap_message = coap.CoapMessage( + any_version(), + any_type(), + any_code(), + any_message_id(), + token, + any_options(), + any_payload(), + ) # WHEN actual_token = coap_message.token @@ -368,8 +407,15 @@ class TestCoapMessage(unittest.TestCase): # GIVEN token = any_token() - coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), any_message_id(), - token, any_options(), any_payload()) + coap_message = coap.CoapMessage( + any_version(), + any_type(), + any_code(), + any_message_id(), + token, + any_options(), + any_payload(), + ) # WHEN actual_tkl = coap_message.tkl @@ -381,8 +427,15 @@ class TestCoapMessage(unittest.TestCase): # GIVEN options = any_options() - coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), any_message_id(), - any_token(), options, any_payload()) + coap_message = coap.CoapMessage( + any_version(), + any_type(), + any_code(), + any_message_id(), + any_token(), + options, + any_payload(), + ) # WHEN actual_options = coap_message.options @@ -394,8 +447,15 @@ class TestCoapMessage(unittest.TestCase): # GIVEN payload = any_payload() - coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), any_message_id(), - any_token(), any_options(), payload) + coap_message = coap.CoapMessage( + any_version(), + any_type(), + any_code(), + any_message_id(), + any_token(), + any_options(), + payload, + ) # WHEN actual_payload = coap_message.payload @@ -403,12 +463,22 @@ class TestCoapMessage(unittest.TestCase): # THEN self.assertEqual(payload, actual_payload) - def test_should_return_uri_path_value_when_uri_path_property_is_called(self): + def test_should_return_uri_path_value_when_uri_path_property_is_called( + self + ): # GIVEN uri_path = any_uri_path() - coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), any_message_id(), - any_token(), any_options(), any_payload(), uri_path) + coap_message = coap.CoapMessage( + any_version(), + any_type(), + any_code(), + any_message_id(), + any_token(), + any_options(), + any_payload(), + uri_path, + ) # WHEN actual_uri_path = coap_message.uri_path @@ -418,8 +488,8 @@ class TestCoapMessage(unittest.TestCase): class TestCoapMessageIdToUriPathBinder(unittest.TestCase): - - def test_should_add_uri_path_to_binds_when_add_uri_path_for_method_is_called(self): + def test_should_add_uri_path_to_binds_when_add_uri_path_for_method_is_called( + self): # GIVEN message_id = any_message_id() token = any_token() @@ -433,23 +503,24 @@ class TestCoapMessageIdToUriPathBinder(unittest.TestCase): # THEN self.assertEqual(uri_path, binder.get_uri_path_for(message_id, token)) - def test_should_raise_KeyError_when_get_uri_path_for_is_called_but_it_is_not_present_in_database(self): + def test_should_raise_KeyError_when_get_uri_path_for_is_called_but_it_is_not_present_in_database( + self): # GIVEN message_id = any_message_id() token = any_token() - uri_path = any_uri_path() + any_uri_path() binder = coap.CoapMessageIdToUriPathBinder() # THEN - self.assertRaises(RuntimeError, binder.get_uri_path_for, message_id, token) + self.assertRaises( + RuntimeError, binder.get_uri_path_for, message_id, token + ) class TestCoapMessageFactory(unittest.TestCase): - def _create_dummy_payload_factory(self): class DummyPayloadFactory: - def parse(self, data, message_info): return data.read() @@ -461,14 +532,20 @@ class TestCoapMessageFactory(unittest.TestCase): uri_path_based_payload_factories={ "/a/as": self._create_dummy_payload_factory() }, - message_id_to_uri_path_binder=coap.CoapMessageIdToUriPathBinder()) + message_id_to_uri_path_binder=coap.CoapMessageIdToUriPathBinder(), + ) - def test_should_create_CoapMessage_from_solicit_request_data_when_parse_method_is_called(self): + def test_should_create_CoapMessage_from_solicit_request_data_when_parse_method_is_called( + self): # GIVEN - data = bytearray([0x42, 0x02, 0x00, 0xbd, 0x65, 0xee, 0xb1, 0x61, - 0x02, 0x61, 0x73, 0xff, 0x01, 0x08, 0x16, 0x6e, - 0x0a, 0x00, 0x00, 0x00, 0x00, 0x02, 0x04, 0x01, - 0x02]) + data = bytearray( + [ + 0x42, 0x02, 0x00, 0xBD, 0x65, 0xee, 0xB1, 0x61, + 0x02, 0x61, 0x73, 0xff, 0x01, 0x08, 0x16, 0x6E, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x02, 0x04, 0x01, + 0x02, + ] + ) factory = self._create_coap_message_factory() @@ -485,15 +562,27 @@ class TestCoapMessageFactory(unittest.TestCase): self.assertEqual("a", coap_message.options[0].value.decode("utf-8")) self.assertEqual("as", coap_message.options[1].value.decode("utf-8")) self.assertEqual("/a/as", coap_message.uri_path) - self.assertEqual(bytearray([0x01, 0x08, 0x16, 0x6e, 0x0a, 0x00, 0x00, 0x00, - 0x00, 0x02, 0x04, 0x01, 0x02]), coap_message.payload) + self.assertEqual( + bytearray( + [ + 0x01, 0x08, 0x16, 0x6E, 0x0A, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x04, 0x01, 0x02, + ] + ), + coap_message.payload, + ) - def test_should_create_CoapMessage_from_solicit_response_data_when_parse_method_is_called(self): + def test_should_create_CoapMessage_from_solicit_response_data_when_parse_method_is_called( + self): # GIVEN - data = bytearray([0x62, 0x44, 0x00, 0xbd, 0x65, 0xee, 0xff, 0x04, - 0x01, 0x00, 0x02, 0x02, 0x00, 0x00, 0x07, 0x09, - 0x76, 0x80, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00]) + data = bytearray( + [ + 0x62, 0x44, 0x00, 0xBD, 0x65, 0xee, 0xff, 0x04, + 0x01, 0x00, 0x02, 0x02, 0x00, 0x00, 0x07, 0x09, + 0x76, 0x80, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, + ] + ) mid_binder = coap.CoapMessageIdToUriPathBinder() mid_binder.add_uri_path_for(189, bytearray([0x65, 0xee]), "/a/as") @@ -503,7 +592,8 @@ class TestCoapMessageFactory(unittest.TestCase): uri_path_based_payload_factories={ "/a/as": self._create_dummy_payload_factory() }, - message_id_to_uri_path_binder=mid_binder) + message_id_to_uri_path_binder=mid_binder, + ) # WHEN coap_message = factory.parse(io.BytesIO(data), None) @@ -516,9 +606,17 @@ class TestCoapMessageFactory(unittest.TestCase): self.assertEqual(189, coap_message.message_id) self.assertEqual(bytearray([0x65, 0xee]), coap_message.token) self.assertEqual(None, coap_message.uri_path) - self.assertEqual(bytearray([0x04, 0x01, 0x00, 0x02, 0x02, 0x00, 0x00, 0x07, - 0x09, 0x76, 0x80, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00]), coap_message.payload) + self.assertEqual( + bytearray( + [ + 0x04, 0x01, 0x00, 0x02, 0x02, 0x00, 0x00, 0x07, + 0x09, 0x76, 0x80, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x00, + ] + ), + coap_message.payload, + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/scripts/thread-cert/test_coaps.py b/tests/scripts/thread-cert/test_coaps.py index 285f91b49..a134087ba 100755 --- a/tests/scripts/thread-cert/test_coaps.py +++ b/tests/scripts/thread-cert/test_coaps.py @@ -27,12 +27,9 @@ # POSSIBILITY OF SUCH DAMAGE. # -import time import unittest import config -import mle -import network_layer import node LEADER = 1 @@ -40,7 +37,6 @@ ROUTER = 2 class TestCoaps(unittest.TestCase): - def setUp(self): self.simulator = config.create_default_simulator() @@ -60,9 +56,9 @@ class TestCoaps(unittest.TestCase): self.nodes[ROUTER].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def test(self): @@ -86,7 +82,7 @@ class TestCoaps(unittest.TestCase): self.nodes[LEADER].coaps_stop() self.nodes[LEADER].coaps_start_x509() - #self.nodes[LEADER].coaps_set_resource_path('test') + # self.nodes[LEADER].coaps_set_resource_path('test') self.nodes[ROUTER].coaps_start_x509() self.nodes[ROUTER].coaps_connect(mleid) self.nodes[ROUTER].coaps_get() @@ -94,5 +90,6 @@ class TestCoaps(unittest.TestCase): self.nodes[ROUTER].coaps_stop() self.nodes[LEADER].coaps_stop() + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/test_common.py b/tests/scripts/thread-cert/test_common.py index 4ce4c3799..8a80b054e 100755 --- a/tests/scripts/thread-cert/test_common.py +++ b/tests/scripts/thread-cert/test_common.py @@ -51,8 +51,8 @@ def any_ipv6_address(): class TestMessageInfo(unittest.TestCase): - - def test_should_return_source_ipv6_value_when_source_ipv6_property_is_called(self): + def test_should_return_source_ipv6_value_when_source_ipv6_property_is_called( + self): # GIVEN source_ipv6 = any_ipv6_address() @@ -63,9 +63,12 @@ class TestMessageInfo(unittest.TestCase): actual_source_ipv6 = message_info.source_ipv6 # THEN - self.assertEqual(ipaddress.ip_address(bytes(source_ipv6)), actual_source_ipv6) + self.assertEqual( + ipaddress.ip_address(bytes(source_ipv6)), actual_source_ipv6 + ) - def test_should_return_destination_ipv6_value_when_destination_ipv6_property_is_called(self): + def test_should_return_destination_ipv6_value_when_destination_ipv6_property_is_called( + self): # GIVEN destination_ipv6 = any_ipv6_address() @@ -76,9 +79,13 @@ class TestMessageInfo(unittest.TestCase): actual_destination_ipv6 = message_info.destination_ipv6 # THEN - self.assertEqual(ipaddress.ip_address(bytes(destination_ipv6)), actual_destination_ipv6) + self.assertEqual( + ipaddress.ip_address(bytes(destination_ipv6)), + actual_destination_ipv6, + ) - def test_should_return_source_eui64_value_when_source_eui64_property_is_called(self): + def test_should_return_source_eui64_value_when_source_eui64_property_is_called( + self): # GIVEN source_mac_address = any_eui64() @@ -91,7 +98,8 @@ class TestMessageInfo(unittest.TestCase): # THEN self.assertEqual(source_mac_address, actual_source_mac_address) - def test_should_return_destination_eui64_value_when_destination_eui64_property_is_called(self): + def test_should_return_destination_eui64_value_when_destination_eui64_property_is_called( + self): # GIVEN destination_mac_address = any_eui64() @@ -102,12 +110,14 @@ class TestMessageInfo(unittest.TestCase): actual_destination_mac_address = message_info.destination_mac_address # THEN - self.assertEqual(destination_mac_address, actual_destination_mac_address) + self.assertEqual( + destination_mac_address, actual_destination_mac_address + ) class TestMacAddress(unittest.TestCase): - - def test_should_create_MacAddress_from_eui64_when_from_eui64_classmethod_is_called(self): + def test_should_create_MacAddress_from_eui64_when_from_eui64_classmethod_is_called( + self): # GIVEN eui64 = any_eui64() @@ -118,7 +128,8 @@ class TestMacAddress(unittest.TestCase): self.assertEqual(common.MacAddressType.LONG, mac_address.type) self.assertEqual(eui64, mac_address.mac_address) - def test_should_create_MacAddress_from_rloc16_int_when_from_rloc16_classmethod_is_called(self): + def test_should_create_MacAddress_from_rloc16_int_when_from_rloc16_classmethod_is_called( + self): # GIVEN rloc16 = any_rloc16_int() @@ -129,7 +140,8 @@ class TestMacAddress(unittest.TestCase): self.assertEqual(common.MacAddressType.SHORT, mac_address.type) self.assertEqual(struct.pack(">H", rloc16), mac_address.mac_address) - def test_should_create_MacAddress_from_rloc16_bytearray_when_from_rloc16_classmethod_is_called(self): + def test_should_create_MacAddress_from_rloc16_bytearray_when_from_rloc16_classmethod_is_called( + self): # GIVEN rloc16 = any_rloc16_bytearray() @@ -140,7 +152,8 @@ class TestMacAddress(unittest.TestCase): self.assertEqual(common.MacAddressType.SHORT, mac_address.type) self.assertEqual(rloc16, mac_address.mac_address) - def test_should_convert_short_MacAddress_to_iid_when_convert_method_is_called(self): + def test_should_convert_short_MacAddress_to_iid_when_convert_method_is_called( + self): # GIVEN rloc16 = any_rloc16_bytearray() @@ -150,9 +163,12 @@ class TestMacAddress(unittest.TestCase): iid = mac_address.convert_to_iid() # THEN - self.assertEqual(bytearray([0x00, 0x00, 0x00, 0xff, 0xfe, 0x00]) + rloc16, iid) + self.assertEqual( + bytearray([0x00, 0x00, 0x00, 0xff, 0xfe, 0x00]) + rloc16, iid + ) - def test_should_convert_short_MacAddress_to_iid_when_convert_method_is_called(self): + def test_should_convert_eui64_MacAddress_to_iid_when_convert_method_is_called( + self): # GIVEN eui64 = any_eui64() diff --git a/tests/scripts/thread-cert/test_crypto.py b/tests/scripts/thread-cert/test_crypto.py index 64f863ba8..633d208a9 100755 --- a/tests/scripts/thread-cert/test_crypto.py +++ b/tests/scripts/thread-cert/test_crypto.py @@ -35,7 +35,6 @@ import ipaddress import common import net_crypto -import mle master_key = bytearray([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]) @@ -306,7 +305,7 @@ class TestMleCryptoMaterialCreator(unittest.TestCase): self.assertEqual(destination_address.packed, authenticated_data_bytes.read(16)) self.assertEqual(auxiliary_security_header_bytes, authenticated_data_bytes.read(10)) - def test_should_create_key_and_nonce_and_authenticated_data_when_create_key_and_nonce_and_authenticated_data_is_called(self): + def test_should_create_key_and_nonce_and_auth_data_when_create_key_and_nonce_and_auth_data_is_called(self): # GIVEN message_info = common.MessageInfo() message_info.source_mac_address = common.MacAddress.from_eui64(any_eui64()) @@ -323,14 +322,22 @@ class TestMleCryptoMaterialCreator(unittest.TestCase): key, nonce, auth_data = creator.create_key_and_nonce_and_authenticated_data(message_info) # THEN - self.assertEqual(message_info.source_mac_address.mac_address + - struct.pack(">LB", - message_info.aux_sec_hdr.frame_counter, - message_info.aux_sec_hdr.security_level), nonce) + self.assertEqual( + message_info.source_mac_address.mac_address + + struct.pack( + ">LB", + message_info.aux_sec_hdr.frame_counter, + message_info.aux_sec_hdr.security_level + ), + nonce + ) - self.assertEqual(message_info.source_ipv6.packed + - message_info.destination_ipv6.packed + - message_info.aux_sec_hdr_bytes, auth_data) + self.assertEqual( + message_info.source_ipv6.packed + + message_info.destination_ipv6.packed + + message_info.aux_sec_hdr_bytes, + auth_data + ) class TestAuxiliarySecurityHeader(unittest.TestCase): @@ -427,5 +434,6 @@ class TestAuxiliarySecurityHeaderFactory(unittest.TestCase): self.assertEqual(sec_lvl, aux_sec_hdr.security_level) self.assertEqual(frame_counter, aux_sec_hdr.frame_counter) + if __name__ == "__main__": unittest.main() diff --git a/tests/scripts/thread-cert/test_diag.py b/tests/scripts/thread-cert/test_diag.py index e6a9228b2..709d7f0cd 100755 --- a/tests/scripts/thread-cert/test_diag.py +++ b/tests/scripts/thread-cert/test_diag.py @@ -32,6 +32,7 @@ import unittest import node import config + class TestDiag(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() @@ -62,21 +63,29 @@ class TestDiag(unittest.TestCase): ('diag power\n', 'tx power: -10 dBm\r\n'), ('diag stats\n', - 'received packets: 0\r\nsent packets: 0\r\nfirst received packet: rssi=0, lqi=0\r\n'), + 'received packets: 0\r\nsent packets: 0\r\nfirst received packet: rssi=0, lqi=0\r\n', + ), ('diag send 20 100\n', - 'sending 0x14 packet\(s\), length 0x64\r\nstatus 0x00\r\n'), + r'sending 0x14 packet\(s\), length 0x64\r\nstatus 0x00\r\n', + ), (' diag \t send \t 20\t100', - 'sending 0x14 packet\(s\), length 0x64\r\nstatus 0x00\r\n'), + r'sending 0x14 packet\(s\), length 0x64\r\nstatus 0x00\r\n', + ), ('diag repeat 100 100\n', - 'sending packets of length 0x64 at the delay of 0x64 ms\r\nstatus 0x00\r\n'), + 'sending packets of length 0x64 at the delay of 0x64 ms\r\nstatus 0x00\r\n', + ), ('diag repeat stop\n', - 'repeated packet transmission is stopped\r\nstatus 0x00\r\n'), + 'repeated packet transmission is stopped\r\nstatus 0x00\r\n', + ), ('diag stop\n', - 'received packets: 0\r\nsent packets: ([1-9]\d*)\r\nfirst received packet: rssi=0, lqi=0\r\n\nstop diagnostics mode\r\nstatus 0x00\r\n'), + r'received packets: 0\r\nsent packets: ([1-9]\d*)\r\nfirst received packet: rssi=0, lqi=0\r\n\n' + r'stop diagnostics mode\r\nstatus 0x00\r\n', + ), ('diag', 'diagnostics mode is disabled\r\n'), ('diag 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', - 'Error: too many args \(max 32\)\r\n'), + r'Error: too many args \(max 32\)\r\n', + ), ] for case in cases: @@ -84,5 +93,6 @@ class TestDiag(unittest.TestCase): self.simulator.go(1) self.node._expect(case[1]) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/test_ipv6.py b/tests/scripts/thread-cert/test_ipv6.py index 803799753..2a188ff2c 100755 --- a/tests/scripts/thread-cert/test_ipv6.py +++ b/tests/scripts/thread-cert/test_ipv6.py @@ -35,11 +35,33 @@ import unittest from ipaddress import ip_address -from ipv6 import ICMPv6Header, UDPHeader, IPv6Header, IPv6PacketFactory, UDPDatagram, \ - UDPDatagramFactory, ICMPv6Factory, HopByHopFactory, MPLOptionFactory, ICMPv6, HopByHopOptionHeader, HopByHopOption, \ - HopByHop, MPLOption, HopByHopFactory, IPv6Packet, ICMPv6EchoBody, BytesPayload, ICMPv6EchoBodyFactory, \ - UpperLayerProtocol, UDPHeaderFactory, HopByHopOptionsFactory, ICMPv6DestinationUnreachableFactory, \ - BytesPayloadFactory, ICMPv6DestinationUnreachable, UdpBasedOnSrcDstPortsPayloadFactory +from ipv6 import ( + ICMPv6Header, + UDPHeader, + IPv6Header, + IPv6PacketFactory, + UDPDatagram, + UDPDatagramFactory, + ICMPv6Factory, + HopByHopFactory, + MPLOptionFactory, + ICMPv6, + HopByHopOptionHeader, + HopByHopOption, + HopByHop, + MPLOption, + IPv6Packet, + ICMPv6EchoBody, + BytesPayload, + ICMPv6EchoBodyFactory, + UpperLayerProtocol, + UDPHeaderFactory, + HopByHopOptionsFactory, + ICMPv6DestinationUnreachableFactory, + BytesPayloadFactory, + ICMPv6DestinationUnreachable, + UdpBasedOnSrcDstPortsPayloadFactory, +) import common @@ -136,15 +158,15 @@ def any_checksum(): def any_icmp_payload(_type, code, checksum, body): - return bytearray([_type, code, (checksum >> 8) & 0xFF, checksum & 0xFF]) + body + return bytearray([_type, code, (checksum >> 8) & 0xff, checksum & 0xff]) + body def any_udp_payload(src_port, dst_port, payload, checksum): payload_len = len(payload) + 8 - return bytearray([(src_port >> 8) & 0xFF, src_port & 0xFF, - (dst_port >> 8) & 0xFF, dst_port & 0xFF, - (payload_len >> 8) & 0xFF, payload_len & 0xFF, - (checksum >> 8) & 0xFF, checksum & 0xFF]) + payload + return bytearray([(src_port >> 8) & 0xff, src_port & 0xff, + (dst_port >> 8) & 0xff, dst_port & 0xff, + (payload_len >> 8) & 0xff, payload_len & 0xff, + (checksum >> 8) & 0xff, checksum & 0xff]) + payload def any_hop_by_hop_payload(next_header, hdr_ext_len, payload): @@ -326,9 +348,10 @@ class TestIPv6Header(unittest.TestCase): # THEN self.assertEqual(6, data[0] >> 4) - self.assertEqual(traffic_class, ((data[0] << 8 | data[1]) >> 4) & 0xFF) - self.assertEqual(flow_label, ((data[1] & 0x0F) << 16) | - (data[2] << 8) | data[3]) + self.assertEqual(traffic_class, ((data[0] << 8 | data[1]) >> 4) & 0xff) + self.assertEqual( + flow_label, ((data[1] & 0x0F) << 16) | (data[2] << 8) | data[3] + ) self.assertEqual(payload_length, struct.unpack("!H", data[4:6])[0]) self.assertEqual(next_header, data[6]) self.assertEqual(hop_limit, data[7]) @@ -347,8 +370,8 @@ class TestIPv6Header(unittest.TestCase): data = bytearray([(6 << 4) | (traffic_class >> 4), (traffic_class & 0xF) << 4 | (flow_label >> 16) & 0xF, - (flow_label >> 8) & 0xFF, flow_label & 0xFF, - payload_length >> 8, payload_length & 0xFF, + (flow_label >> 8) & 0xff, flow_label & 0xff, + payload_length >> 8, payload_length & 0xff, next_header, hop_limit]) data += ip_address(bytes(source_address)).packed + ip_address(bytes(destination_address)).packed @@ -484,31 +507,55 @@ class TestIPv6Packet(unittest.TestCase): def test_should_build_IPv6Packet_with_ICMP_payload_from_well_know_values_when_to_bytes_method_is_called(self): # GIVEN - ipv6_packet = IPv6Packet(IPv6Header(source_address="fd00:1234:4555::ff:fe00:1800", - destination_address="ff03::1"), - ICMPv6(ICMPv6Header(128, 0), - ICMPv6EchoBody(0, 2, bytearray([0x80, 0x00, 0xc7, 0xbf, 0x00, 0x00, 0x00, 0x01, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41]))), - [HopByHop(options=[ - HopByHopOption(HopByHopOptionHeader(_type=0x6d), - MPLOption(S=1, M=0, V=0, sequence=2, seed_id=bytearray([0x00, 0x18]))) - ])]) + ipv6_packet = IPv6Packet( + IPv6Header( + source_address="fd00:1234:4555::ff:fe00:1800", + destination_address="ff03::1" + ), + ICMPv6( + ICMPv6Header(128, 0), + ICMPv6EchoBody( + 0, + 2, + bytearray( + [ + 0x80, 0x00, 0xc7, 0xbf, 0x00, 0x00, 0x00, 0x01, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41 + ] + ) + ) + ), + [ + HopByHop( + options=[ + HopByHopOption( + HopByHopOptionHeader(_type=0x6d), + MPLOption(S=1, M=0, V=0, sequence=2, seed_id=bytearray([0x00, 0x18])) + ) + ] + ) + ] + ) # WHEN ipv6_packet_bytes = ipv6_packet.to_bytes() # THEN - expected_ipv6_packet_bytes = bytearray([0x60, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 0x40, - 0xfd, 0x00, 0x12, 0x34, 0x45, 0x55, 0x00, 0x00, - 0x00, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x18, 0x00, - 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x3a, 0x00, 0x6d, 0x04, 0x40, 0x02, 0x00, 0x18, - 0x80, 0x00, 0x87, 0x12, 0x00, 0x00, 0x00, 0x02, - 0x80, 0x00, 0xc7, 0xbf, 0x00, 0x00, 0x00, 0x01, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41]) + expected_ipv6_packet_bytes = bytearray( + [ + 0x60, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 0x40, + 0xfd, 0x00, 0x12, 0x34, 0x45, 0x55, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x18, 0x00, + 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x3a, 0x00, 0x6d, 0x04, 0x40, 0x02, 0x00, 0x18, + 0x80, 0x00, 0x87, 0x12, 0x00, 0x00, 0x00, 0x02, + 0x80, 0x00, 0xc7, 0xbf, 0x00, 0x00, 0x00, 0x01, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41 + ] + ) self.assertEqual(expected_ipv6_packet_bytes, ipv6_packet_bytes) @@ -518,11 +565,19 @@ class TestIPv6Packet(unittest.TestCase): destination_address="ff02::2", hop_limit=255) - udp_dgram = UDPDatagram(UDPHeader(src_port=19788, dst_port=19788), - BytesPayload(bytearray([0x00, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x01, 0x09, 0x01, 0x01, 0x0b, 0x03, - 0x04, 0xc6, 0x69, 0x73, 0x51, 0x0e, 0x01, 0x80, - 0x12, 0x02, 0x00, 0x01, 0xde, 0xad, 0xbe, 0xef]))) + udp_dgram = UDPDatagram( + UDPHeader(src_port=19788, dst_port=19788), + BytesPayload( + bytearray( + [ + 0x00, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x01, 0x09, 0x01, 0x01, 0x0b, 0x03, + 0x04, 0xc6, 0x69, 0x73, 0x51, 0x0e, 0x01, 0x80, + 0x12, 0x02, 0x00, 0x01, 0xde, 0xad, 0xbe, 0xef + ] + ) + ) + ) ipv6_packet = IPv6Packet(ipv6_header, udp_dgram) @@ -546,7 +601,7 @@ class TestIPv6Packet(unittest.TestCase): class TestIPv6PacketFactory(unittest.TestCase): - def test_should_create_IPv6Packet_with_MPL_extension_header_and_ICMP_upper_layer_protocol_when_to_bytes_method_is_called(self): + def test_should_create_IPv6Packet_with_MPL_and_ICMP_when_to_bytes_method_is_called(self): # GIVEN ipv6_packet_bytes = bytearray([0x60, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 0x40, 0xfd, 0x00, 0x12, 0x34, 0x45, 0x55, 0x00, 0x00, @@ -579,7 +634,7 @@ class TestIPv6PacketFactory(unittest.TestCase): ipv6_packet = ipv6_factory.parse(io.BytesIO(ipv6_packet_bytes), any_message_info()) # THEN - self.assertEqual('fd00:1234:4555::ff:fe00:1800', ipv6_packet.ipv6_header.source_address.compressed) + self.assertEqual('fd00:1234:4555::ff:fe00:1800', ipv6_packet.ipv6_header.source_address.compressed) self.assertEqual('ff03::1', ipv6_packet.ipv6_header.destination_address.compressed) self.assertEqual(64, ipv6_packet.ipv6_header.hop_limit) self.assertEqual(0, ipv6_packet.ipv6_header.next_header) @@ -601,7 +656,7 @@ class TestIPv6PacketFactory(unittest.TestCase): self.assertEqual(2, ipv6_packet.upper_layer_protocol.body.sequence_number) self.assertEqual(b'\x80\x00\xc7\xbf\x00\x00\x00\x01AAAAAAAAAA', ipv6_packet.upper_layer_protocol.body.data) - def test_should_create_IPv6Packet_without_any_extension_header_with_ICMP_upper_layer_protocol_when_to_bytes_method_is_called(self): + def test_should_create_IPv6Packet_without_any_extension_header_with_ICMP_when_to_bytes_method_is_called(self): # GIVEN ipv6_packet_bytes = bytearray([0x60, 0x00, 0x00, 0x00, 0x00, 0x1A, 0x3A, 0x40, 0xfd, 0x00, 0x12, 0x34, 0x45, 0x55, 0x00, 0x00, @@ -967,7 +1022,6 @@ class TestHopByHopFactory(unittest.TestCase): def test_should_raise_RuntimeError_when_no_option_factory_is_set_and_parse_method_is_called(self): # GIVEN hop_by_hop_option = any_hop_by_hop_mpl_option() - hop_by_hop_option_type = hop_by_hop_option.header.type next_header = any_next_header() hdr_ext_len = self._calculate_hdr_ext_len(2 + len(hop_by_hop_option)) @@ -1072,10 +1126,10 @@ class TestUDPDatagramFactory(unittest.TestCase): payload = any_payload() payload_length = len(payload) + len(UDPHeader(0, 0)) - data = bytearray([(src_port >> 8), (src_port & 0xFF), - (dst_port >> 8), (dst_port & 0xFF), - (payload_length >> 8), (payload_length & 0xFF), - (checksum >> 8), (checksum & 0xFF)]) + payload + data = bytearray([(src_port >> 8), (src_port & 0xff), + (dst_port >> 8), (dst_port & 0xff), + (payload_length >> 8), (payload_length & 0xff), + (checksum >> 8), (checksum & 0xff)]) + payload factory = UDPDatagramFactory(UDPHeaderFactory(), BytesPayloadFactory()) @@ -1100,15 +1154,26 @@ class TestUDPDatagramFactory(unittest.TestCase): payload = any_payload() payload_length = len(payload) + len(UDPHeader(0, 0)) - data = bytearray([(src_port >> 8), (src_port & 0xFF), - (dst_port >> 8), (dst_port & 0xFF), - (payload_length >> 8), (payload_length & 0xFF), - (checksum >> 8), (checksum & 0xFF)]) + payload + data = ( + bytearray( + [ + (src_port >> 8), + (src_port & 0xff), + (dst_port >> 8), + (dst_port & 0xff), + (payload_length >> 8), + (payload_length & 0xff), + (checksum >> 8), + (checksum & 0xff), + ] + ) + + payload + ) factory = UDPDatagramFactory(UDPHeaderFactory(), BytesPayloadFactory()) # WHEN - udp_dgram = factory.parse(io.BytesIO(data), message_info) + factory.parse(io.BytesIO(data), message_info) # THEN self.assertEqual(src_port, message_info.src_port) @@ -1124,7 +1189,7 @@ class TestICMPv6Factory(unittest.TestCase): checksum = any_checksum() body = any_body() - data = bytearray([_type, code, (checksum >> 8), (checksum & 0xFF)]) + body + data = bytearray([_type, code, (checksum >> 8), (checksum & 0xff)]) + body factory = ICMPv6Factory(body_factories={_type: ICMPv6BytesBodyFactory()}) @@ -1144,7 +1209,7 @@ class TestICMPv6Factory(unittest.TestCase): checksum = any_checksum() body = any_body() - data = bytes([_type, code, (checksum >> 8), (checksum & 0xFF)]) + body + data = bytes([_type, code, (checksum >> 8), (checksum & 0xff)]) + body factory = ICMPv6Factory() @@ -1175,7 +1240,7 @@ class TestBytesPayload(unittest.TestCase): # THEN self.assertEqual(data, actual) - def test_should_return_the_same_length_as_data_passed_to_constructor_when_len_is_called_on_BytesPayload_object(self): + def test_should_return_the_same_len_as_data_passed_to_constructor_when_len_is_called_on_BytesPayload_object(self): # GIVEN data = any_data() payload = BytesPayload(data) @@ -1201,7 +1266,7 @@ class TestICMPv6EchoBody(unittest.TestCase): actual = body.to_bytes() # THEN - expected = bytearray([identifier >> 8, identifier & 0xFF, sequence_number >> 8, sequence_number & 0xFF]) + data + expected = bytearray([identifier >> 8, identifier & 0xff, sequence_number >> 8, sequence_number & 0xff]) + data self.assertEqual(expected, actual) def test_should_create_ICMPv6EchoBody_from_data_when_from_bytes_classmethod_is_called(self): @@ -1211,9 +1276,9 @@ class TestICMPv6EchoBody(unittest.TestCase): body_data = any_data() data = bytearray([(identifier >> 8), - (identifier & 0xFF), + (identifier & 0xff), (sequence_number >> 8), - (sequence_number & 0xFF)]) + (sequence_number & 0xff)]) data += body_data # WHEN @@ -1249,8 +1314,8 @@ class TestICMPv6EchoBodyFactory(unittest.TestCase): sequence_number = any_sequence_number() body_data = any_data() - data = bytearray([(identifier >> 8) & 0xFF, identifier & 0xFF, - (sequence_number >> 8) & 0xFF, sequence_number & 0xFF]) + body_data + data = bytearray([(identifier >> 8) & 0xff, identifier & 0xff, + (sequence_number >> 8) & 0xff, sequence_number & 0xff]) + body_data factory = ICMPv6EchoBodyFactory() @@ -1312,7 +1377,7 @@ class TestICMPv6DestinationUnreachableFactory(unittest.TestCase): data = bytearray([0x00, 0x00, 0x00, 0x00]) + icmp_data # WHEN - icmpv6_dest_unreachable=factory.parse(io.BytesIO(data), any_message_info()) + icmpv6_dest_unreachable = factory.parse(io.BytesIO(data), any_message_info()) # THEN self.assertEqual(icmp_data, icmpv6_dest_unreachable.data) @@ -1322,18 +1387,18 @@ class TestUDPHeaderFactory(unittest.TestCase): def test_should_create_UDPHeader_when_to_bytes_method_is_called(self): # GIVEN - factory=UDPHeaderFactory() + factory = UDPHeaderFactory() - src_port=any_port() - dst_port=any_port() - payload_length=any_payload_length() - checksum=any_checksum() + src_port = any_port() + dst_port = any_port() + payload_length = any_payload_length() + checksum = any_checksum() - data=struct.pack("!H", src_port) + struct.pack("!H", dst_port) + \ + data = struct.pack("!H", src_port) + struct.pack("!H", dst_port) + \ struct.pack("!H", payload_length) + struct.pack("!H", checksum) # WHEN - udp_header=factory.parse(io.BytesIO(data), any_message_info()) + udp_header = factory.parse(io.BytesIO(data), any_message_info()) # THEN self.assertEqual(src_port, udp_header.src_port) @@ -1352,12 +1417,12 @@ class TestHopByHopOptionsFactory(unittest.TestCase): def parse(self, data, message_info): return data.read() - factory=HopByHopOptionsFactory(options_factories = {2: DummyOptionFactory()}) + factory = HopByHopOptionsFactory(options_factories={2: DummyOptionFactory()}) - data=bytearray([0x02, 0x03, 0x11, 0x22, 0x33, 0x01, 0x00]) + data = bytearray([0x02, 0x03, 0x11, 0x22, 0x33, 0x01, 0x00]) # WHEN - actual_options=factory.parse(io.BytesIO(data), any_message_info()) + actual_options = factory.parse(io.BytesIO(data), any_message_info()) # THEN self.assertEqual(1, len(actual_options)) diff --git a/tests/scripts/thread-cert/test_lowpan.py b/tests/scripts/thread-cert/test_lowpan.py index f9f5b22e4..5142b79a6 100755 --- a/tests/scripts/thread-cert/test_lowpan.py +++ b/tests/scripts/thread-cert/test_lowpan.py @@ -230,7 +230,7 @@ def any_datagram_offset(): class TestLowpanIPHC(unittest.TestCase): - def test_should_create_LowpanIPHC_object_when_from_bytes_classmethod_is_called(self): + def test_should_create_LowpanIPHC_object_when_from_bytes_classmethod_called(self): # GIVEN tf = any_tf() nh = any_nh() @@ -264,7 +264,7 @@ class TestLowpanIPHC(unittest.TestCase): class TestLowpanParser(unittest.TestCase): - def test_should_parse_6lowpan_packet_with_mesh_header_that_contains_hop_limit_stored_on_two_bytes_when_decompress_method_is_called(self): + def test_should_parse_6lo_with_mesh_hdr_that_contains_hlim_stored_on_2_bytes_when_decompress_method_called(self): # GIVEN lowpan_packet = bytearray([0xbf, 0x13, 0x90, 0x00, 0x48, 0x01, 0x7c, 0x77, 0x3f, 0xf2, 0xbf, 0xc0, 0x00, 0x24, 0xb1, 0x62, @@ -300,7 +300,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_not_compressed_udp_and_without_hop_by_hop_extension_header_when_decompress_method_is_called(self): + def test_should_parse_6lo_with_uncompressed_udp_and_without_hbh_when_decompress_method_called(self): # GIVEN lowpan_packet = bytearray([0x7a, 0x33, 0x11, 0x16, 0x33, 0x16, 0x34, 0x00, 0x14, 0xcf, 0x63, 0x80, 0x00, 0xfa, 0xa5, 0x0b, @@ -329,7 +329,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_udp_and_without_hop_by_hop_extension_header_when_decompress_method_is_called(self): + def test_should_parse_6lo_with_compressed_udp_and_without_hbh_when_decompress_method_called(self): # GIVEN lowpan_packet = bytearray([0x7e, 0x33, 0xf0, 0x16, 0x33, 0x16, 0x34, 0x04, 0xd2, 0x80, 0x00, 0xfa, 0xa5, 0x0b, 0xc0, 0x00, @@ -358,7 +358,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_not_compressed_udp_and_with_not_compressed_hop_by_hop_extension_header_when_decompress_method_is_called(self): + def test_should_parse_6lo_with_uncompressed_udp_and_with_uncompressed_hbh_when_decompress_method_called(self): # GIVEN lowpan_packet = bytearray([0x7a, 0x33, 0x00, 0x11, 0x00, 0x6d, 0x04, 0x40, 0x02, 0x00, 0x18, 0x16, 0x33, 0x16, 0x34, 0x00, @@ -389,7 +389,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_not_compressed_udp_and_with_compressed_hop_by_hop_extension_header_when_decompress_method_is_called(self): + def test_should_parse_6lo_with_uncompressed_udp_and_with_compressed_hbh_when_decompress_method_called(self): # GIVEN lowpan_packet = bytearray([0x7e, 0x33, 0xe0, 0x11, 0x06, 0x6d, 0x04, 0x40, 0x02, 0x00, 0x18, 0x16, 0x33, 0x16, 0x34, 0x00, @@ -420,7 +420,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_udp_and_with_compressed_hop_by_hop_extension_header_when_decompress_method_is_called(self): + def test_should_parse_6lo_with_compressed_udp_and_with_compressed_hbh_when_decompress_method_called(self): # GIVEN lowpan_packet = bytearray([0x7e, 0x33, 0xe1, 0x06, 0x6d, 0x04, 0x40, 0x02, 0x00, 0x18, 0xf0, 0x16, 0x33, 0x16, 0x34, 0x04, @@ -451,7 +451,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_icmp_and_without_compressed_hop_by_hop_extension_header_when_decompress_method_is_called(self): + def test_should_parse_6lo_with_compressed_icmp_and_without_compressed_hbh_when_decompress_method_called(self): # GIVEN lowpan_packet = bytearray([0x7a, 0xd5, 0xaa, 0x3a, 0x02, 0x99, 0x99, 0xff, 0xfe, 0x22, 0x11, 0x01, 0x36, 0x29, 0x96, 0xff, @@ -483,7 +483,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_icmp_and_without_compressed_hop_by_hop_extension_header_when_decompress_method_is_called_1(self): + def test_should_parse_6lo_with_compressed_icmp_and_without_compressed_hbh_when_decompress_method_called_1(self): # GIVEN lowpan_packet = bytearray([0x7a, 0xd5, 0xaa, 0x3a, 0x02, 0x99, 0x99, 0xff, 0xfe, 0x22, 0x11, 0x01, 0x36, 0x29, 0x96, 0xff, @@ -515,7 +515,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_icmp_and_without_compressed_hop_by_hop_extension_header_when_decompress_method_is_called_2(self): + def test_should_parse_6lo_with_compressed_icmp_and_without_compressed_hbh_when_decompress_method_called_2(self): # GIVEN lowpan_packet = bytearray([0x7a, 0xf0, 0xa0, 0x3a, 0x20, 0x0d, 0x14, 0x56, 0x12, 0x55, 0x00, 0x00, 0x25, 0x14, 0x46, 0xff, @@ -547,7 +547,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_icmp_and_without_compressed_hop_by_hop_extension_header_when_decompress_method_is_called_3(self): + def test_should_parse_6lo_with_compressed_icmp_and_without_compressed_hbh_when_decompress_method_called_3(self): # GIVEN lowpan_packet = bytearray([0x7a, 0xd5, 0xaa, 0x3a, 0x02, 0x99, 0x99, 0xff, 0xfe, 0x22, 0x11, 0x01, 0x36, 0x29, 0x96, 0xff, @@ -579,7 +579,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_icmp_and_without_compressed_hop_by_hop_extension_header_when_decompress_method_is_called_4(self): + def test_should_parse_6lo_with_compressed_icmp_and_without_compressed_hbh_when_decompress_method_called_4(self): # GIVEN lowpan_packet = bytearray([0x7a, 0xf5, 0xaa, 0x3a, 0x36, 0x29, 0x96, 0xff, 0xfe, 0xac, 0xff, 0x18, 0x80, 0x00, 0xfa, 0xa5, @@ -610,7 +610,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_icmp_and_without_compressed_hop_by_hop_extension_header_when_decompress_method_is_called_5(self): + def test_should_parse_6lo_with_compressed_icmp_and_without_compressed_hbh_when_decompress_method_called_5(self): # GIVEN lowpan_packet = bytearray([0x7a, 0xf7, 0xac, 0x3a, 0x80, 0x00, 0xfa, 0xa5, 0x0b, 0xc0, 0x00, 0x04, 0x4e, 0x92, 0xbb, 0x53]) @@ -641,7 +641,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_icmp_and_without_compressed_hop_by_hop_extension_header_when_decompress_method_is_called_6(self): + def test_should_parse_6lo_with_compressed_icmp_and_without_compressed_hbh_when_decompress_method_called_6(self): # GIVEN lowpan_packet = bytearray([0x7a, 0xf0, 0xc0, 0x3a, 0x20, 0x0d, 0x14, 0x56, 0x12, 0x54, 0x00, 0x00, 0x12, 0x54, 0x11, 0xff, @@ -673,7 +673,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_icmp_and_without_compressed_hop_by_hop_extension_header_when_decompress_method_is_called_7(self): + def test_should_parse_6lo_with_compressed_icmp_and_without_compressed_hbh_when_decompress_method_called_7(self): # GIVEN lowpan_packet = bytearray([0x7a, 0xd0, 0xd0, 0x3a, 0x00, 0x02, 0x98, 0xff, 0xfe, 0x22, 0x12, 0x00, 0x20, 0x0d, 0x14, 0x56, @@ -706,7 +706,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_icmp_and_without_compressed_hop_by_hop_extension_header_when_decompress_method_is_called_8(self): + def test_should_parse_6lo_with_compressed_icmp_and_without_compressed_hbh_when_decompress_method_called_8(self): # GIVEN lowpan_packet = bytearray([0x7a, 0xf0, 0xd0, 0x3a, 0x20, 0x0d, 0x14, 0x56, 0x12, 0x55, 0x00, 0x00, 0x25, 0x14, 0x46, 0xff, @@ -738,7 +738,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_parse_6lowpan_packet_with_compressed_icmp_and_without_compressed_hop_by_hop_extension_header_when_decompress_method_is_called_9(self): + def test_should_parse_6lo_with_compressed_icmp_and_without_compressed_hbh_when_decompress_method_called_9(self): # GIVEN lowpan_packet = bytearray([0x7a, 0xf0, 0xd0, 0x3a, 0x20, 0x0d, 0x14, 0x56, 0x12, 0x55, 0x00, 0x00, 0x25, 0x14, 0x46, 0xff, @@ -769,7 +769,7 @@ class TestLowpanParser(unittest.TestCase): # THEN self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_defragment_big_IPv6_packet_when_parse_method_is_called_with_fragments_in_random_order(self): + def test_should_defragment_big_IPv6_packet_when_parse_method_called_with_fragments_in_random_order(self): # GIVEN fragment_1 = bytearray([0xC5, 0x00, 0x31, 0x9F, 0x7A, 0x33, 0x3A, 0x80, 0x00, 0xFA, 0xA5, 0x0B, 0xC0, 0x00, 0x04, @@ -1138,7 +1138,7 @@ class TestLowpanParser(unittest.TestCase): 0x44, 0x54, 0x12, 0xD3, 0x53, 0x11, 0x44, 0x66]) self.assertEqual(ipv6_packet, actual_ipv6_packet.to_bytes()) - def test_should_defragment_IPv6_packet_when_parse_method_is_called_with_fragments(self): + def test_should_defragment_IPv6_packet_when_parse_method_called_with_fragments(self): # GIVEN message_info = common.MessageInfo() message_info.source_mac_address = common.MacAddress.from_eui64( @@ -1171,7 +1171,7 @@ class TestLowpanParser(unittest.TestCase): class TestLowpanUdpHeaderFactory(unittest.TestCase): - def test_should_parse_udp_datagram_ports_when_decompress_udp_ports_method_is_called_with_udphc_p_equal_0(self): + def test_should_parse_udp_datagram_ports_when_decompress_udp_ports_method_called_with_udphc_p_eq_0(self): # GIVEN factory = lowpan.LowpanUdpHeaderFactory() @@ -1192,7 +1192,7 @@ class TestLowpanUdpHeaderFactory(unittest.TestCase): self.assertEqual(dst_port, actual_dst_port) self.assertEqual(0, p) - def test_should_parse_udp_datagram_ports_when_decompress_udp_ports_method_is_called_with_udphc_p_equal_1(self): + def test_should_parse_udp_datagram_ports_when_decompress_udp_ports_method_called_with_udphc_p_eq_1(self): # GIVEN factory = lowpan.LowpanUdpHeaderFactory() @@ -1213,7 +1213,7 @@ class TestLowpanUdpHeaderFactory(unittest.TestCase): self.assertEqual(src_port, actual_src_port) self.assertEqual(dst_port, actual_dst_port) - def test_should_parse_udp_datagram_ports_when_decompress_udp_ports_method_is_called_with_udphc_p_equal_2(self): + def test_should_parse_udp_datagram_ports_when_decompress_udp_ports_method_called_with_udphc_p_eq_2(self): # GIVEN factory = lowpan.LowpanUdpHeaderFactory() @@ -1234,7 +1234,7 @@ class TestLowpanUdpHeaderFactory(unittest.TestCase): self.assertEqual(src_port, actual_src_port) self.assertEqual(dst_port, actual_dst_port) - def test_should_parse_udp_datagram_ports_when_decompress_udp_ports_method_is_called_with_udphc_p_equal_3(self): + def test_should_parse_udp_datagram_ports_when_decompress_udp_ports_method_called_with_udphc_p_eq_3(self): # GIVEN factory = lowpan.LowpanUdpHeaderFactory() @@ -1255,7 +1255,7 @@ class TestLowpanUdpHeaderFactory(unittest.TestCase): self.assertEqual(src_port, actual_src_port) self.assertEqual(dst_port, actual_dst_port) - def test_should_parse_udp_datagram_checksum_when_decompress_udp_checksum_is_called_with_udphc_c_equal_0(self): + def test_should_parse_udp_datagram_checksum_when_decompress_udp_checksum_called_with_udphc_c_eq_0(self): # GIVEN factory = lowpan.LowpanUdpHeaderFactory() @@ -1274,7 +1274,7 @@ class TestLowpanUdpHeaderFactory(unittest.TestCase): self.assertEqual(0, c) self.assertEqual(checksum, actual_checksum) - def test_should_parse_udp_datagram_checksum_when_decompress_udp_checksum_is_called_with_udphc_c_equal_1(self): + def test_should_parse_udp_datagram_checksum_when_decompress_udp_checksum_called_with_udphc_c_eq_1(self): # GIVEN factory = lowpan.LowpanUdpHeaderFactory() @@ -1296,7 +1296,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): IPV6_LINKLOCAL_PREFIX = bytearray([0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) - def test_should_parse_traffic_class_and_flow_label_when_decompress_tf_method_is_called_with_iphc_tf_equal_0(self): + def test_should_parse_traffic_class_and_flow_label_when_decompress_tf_method_called_with_iphc_tf_eq_0(self): # GIVEN ecn = any_ecn() dscp = any_dscp() @@ -1322,7 +1322,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual((dscp << 2) | ecn, actual_traffic_class) self.assertEqual(flow_label, actual_flow_label) - def test_should_parse_traffic_class_and_flow_label_when_decompress_tf_method_is_called_with_iphc_tf_equal_1(self): + def test_should_parse_traffic_class_and_flow_label_when_decompress_tf_method_called_with_iphc_tf_eq_1(self): # GIVEN ecn = any_ecn() flow_label = any_flow_label() @@ -1346,11 +1346,10 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(ecn, actual_traffic_class) self.assertEqual(flow_label, actual_flow_label) - def test_should_parse_traffic_class_and_flow_label_when_decompress_tf_method_is_called_with_iphc_tf_equal_2(self): + def test_should_parse_traffic_class_and_flow_label_when_decompress_tf_method_called_with_iphc_tf_eq_2(self): # GIVEN ecn = any_ecn() dscp = any_dscp() - flow_label = any_flow_label() data_bytes = bytearray([(ecn << 6) | dscp]) @@ -1368,10 +1367,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual((dscp << 2) | ecn, actual_traffic_class) self.assertEqual(0, actual_flow_label) - def test_should_parse_traffic_class_and_flow_label_when_decompress_tf_method_is_called_with_iphc_tf_equal_3(self): - # GIVEN - flow_label = any_flow_label() - + def test_should_parse_traffic_class_and_flow_label_when_decompress_tf_method_called_with_iphc_tf_eq_3(self): data_bytes = bytearray() factory = lowpan.LowpanIpv6HeaderFactory() @@ -1388,7 +1384,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(0, actual_traffic_class) self.assertEqual(0, actual_flow_label) - def test_should_parse_traffic_class_and_flow_label_when_decompress_nh_method_is_called_with_iphc_nh_equal_0(self): + def test_should_parse_traffic_class_and_flow_label_when_decompress_nh_method_called_with_iphc_nh_eq_0(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1407,7 +1403,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(0, nh) self.assertEqual(next_header, actual_next_header) - def test_should_parse_traffic_class_and_flow_label_when_decompress_nh_method_is_called_with_iphc_nh_equal_1(self): + def test_should_parse_traffic_class_and_flow_label_when_decompress_nh_method_called_with_iphc_nh_eq_1(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1424,7 +1420,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(1, nh) self.assertEqual(None, actual_next_header) - def test_should_parse_hop_limit_when_decompress_hlim_is_called_with_iphc_hlim_equal_0(self): + def test_should_parse_hop_limit_when_decompress_hlim_called_with_iphc_hlim_eq_0(self): # GIVEN hop_limit = any_hop_limit() @@ -1443,7 +1439,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(0, hlim) self.assertEqual(hop_limit, actual_hop_limit) - def test_should_parse_hop_limit_when_decompress_hlim_is_called_with_iphc_hlim_equal_1(self): + def test_should_parse_hop_limit_when_decompress_hlim_called_with_iphc_hlim_eq_1(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1460,7 +1456,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(1, hlim) self.assertEqual(1, actual_hop_limit) - def test_should_parse_hop_limit_when_decompress_hlim_is_called_with_iphc_hlim_equal_2(self): + def test_should_parse_hop_limit_when_decompress_hlim_called_with_iphc_hlim_eq_2(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1477,7 +1473,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(2, hlim) self.assertEqual(64, actual_hop_limit) - def test_should_parse_hop_limit_when_decompress_hlim_is_called_with_iphc_hlim_equal_3(self): + def test_should_parse_hop_limit_when_decompress_hlim_called_with_iphc_hlim_eq_3(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1494,7 +1490,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(3, hlim) self.assertEqual(255, actual_hop_limit) - def test_should_parse_source_address_when_decompress_src_addr_is_called_with_sac_equal_0_and_sam_equal_0(self): + def test_should_parse_source_address_when_decompress_src_addr_called_with_sac_eq_0_and_sam_eq_0(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1514,7 +1510,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(0, sam) self.assertEqual(bytes(src_addr), actual_src_addr) - def test_should_parse_source_address_when_decompress_src_addr_is_called_with_sac_equal_0_and_sam_equal_1(self): + def test_should_parse_source_address_when_decompress_src_addr_called_with_sac_eq_0_and_sam_eq_1(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1534,7 +1530,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(1, sam) self.assertEqual(self.IPV6_LINKLOCAL_PREFIX + eui64, actual_src_addr) - def test_should_parse_source_address_when_decompress_src_addr_is_called_with_sac_equal_0_and_sam_equal_2(self): + def test_should_parse_source_address_when_decompress_src_addr_called_with_sac_eq_0_and_sam_eq_2(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1552,10 +1548,14 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): # THEN self.assertEqual(0, sac) self.assertEqual(2, sam) - self.assertEqual(self.IPV6_LINKLOCAL_PREFIX + - bytearray([0x00, 0x00, 0x00, 0xff, 0xfe, 0x00]) + rloc16, actual_src_addr) + self.assertEqual( + self.IPV6_LINKLOCAL_PREFIX + + bytearray([0x00, 0x00, 0x00, 0xff, 0xfe, 0x00]) + + rloc16, + actual_src_addr + ) - def test_should_parse_source_address_when_decompress_src_addr_is_called_with_sac_equal_0_and_sam_equal_3(self): + def test_should_parse_source_address_when_decompress_src_addr_called_with_sac_eq_0_and_sam_eq_3(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1575,9 +1575,12 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): # THEN self.assertEqual(0, sac) self.assertEqual(3, sam) - self.assertEqual(self.IPV6_LINKLOCAL_PREFIX + - bytearray([src_mac_addr.mac_address[0] ^ 0x02]) + - src_mac_addr.mac_address[1:], actual_src_addr) + self.assertEqual( + self.IPV6_LINKLOCAL_PREFIX + + bytearray([src_mac_addr.mac_address[0] ^ 0x02]) + + src_mac_addr.mac_address[1:], + actual_src_addr + ) def _merge_prefix_and_address(self, prefix, prefix_length, address): total_bytes = 16 @@ -1595,7 +1598,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): return prefix[:prefix_length_in_bytes] + bytearray([0x00] * total_bytes) + address - def test_should_parse_source_address_when_decompress_src_addr_is_called_with_sac_equal_1_and_sam_equal_0(self): + def test_should_parse_source_address_when_decompress_src_addr_called_with_sac_eq_1_and_sam_eq_0(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory(None) @@ -1615,7 +1618,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(0, sam) self.assertEqual(bytearray([0x00] * 16), actual_src_addr) - def test_should_parse_source_address_when_decompress_src_addr_is_called_with_sac_equal_1_and_sam_equal_1(self): + def test_should_parse_source_address_when_decompress_src_addr_called_with_sac_eq_1_and_sam_eq_1(self): # GIVEN sci = any_sci() @@ -1644,7 +1647,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(1, sam) self.assertEqual(src_addr, actual_src_addr) - def test_should_parse_source_address_when_decompress_src_addr_is_called_with_sac_equal_1_and_sam_equal_2(self): + def test_should_parse_source_address_when_decompress_src_addr_called_with_sac_eq_1_and_sam_eq_2(self): # GIVEN sci = any_sci() @@ -1675,7 +1678,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(2, sam) self.assertEqual(src_addr, actual_src_addr) - def test_should_parse_source_address_when_decompress_src_addr_is_called_with_sac_equal_1_and_sam_equal_3(self): + def test_should_parse_source_address_when_decompress_src_addr_called_with_sac_eq_1_and_sam_eq_3(self): # GIVEN sci = any_sci() @@ -1708,7 +1711,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(3, sam) self.assertEqual(src_addr, actual_src_addr) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_0_and_dac_equal_0_and_dam_equal_0(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_0_and_dac_eq_0_and_dam_eq_0(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1732,7 +1735,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(0, dam) self.assertEqual(ipv6_addr, actual_dst_addr) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_0_and_dac_equal_0_and_dam_equal_1(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_0_and_dac_eq_0_and_dam_eq_1(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1754,7 +1757,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(1, dam) self.assertEqual(self.IPV6_LINKLOCAL_PREFIX + eui64, actual_dst_addr) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_0_and_dac_equal_0_and_dam_equal_2(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_0_and_dac_eq_0_and_dam_eq_2(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1774,10 +1777,14 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(0, m) self.assertEqual(0, dac) self.assertEqual(2, dam) - self.assertEqual(self.IPV6_LINKLOCAL_PREFIX + - bytearray([0x00, 0x00, 0x00, 0xff, 0xfe, 0x00]) + rloc16, actual_dst_addr) + self.assertEqual( + self.IPV6_LINKLOCAL_PREFIX + + bytearray([0x00, 0x00, 0x00, 0xff, 0xfe, 0x00]) + + rloc16, + actual_dst_addr + ) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_0_and_dac_equal_0_and_dam_equal_3(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_0_and_dac_eq_0_and_dam_eq_3(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1799,11 +1806,14 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(0, m) self.assertEqual(0, dac) self.assertEqual(3, dam) - self.assertEqual(self.IPV6_LINKLOCAL_PREFIX + - bytearray([dst_mac_addr.mac_address[0] ^ 0x02]) + - dst_mac_addr.mac_address[1:], actual_dst_addr) + self.assertEqual( + self.IPV6_LINKLOCAL_PREFIX + + bytearray([dst_mac_addr.mac_address[0] ^ 0x02]) + + dst_mac_addr.mac_address[1:], + actual_dst_addr + ) - def test_should_raise_RuntimeError_when_decompress_dst_addr_is_called_with_m_equal_0_and_dac_equal_1_and_dam_equal_0(self): + def test_should_raise_RuntimeError_when_decompress_dst_addr_called_with_m_eq_0_and_dac_eq_1_and_dam_eq_0(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1820,7 +1830,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertRaises(RuntimeError, factory._decompress_dst_addr, iphc, any_dst_mac_addr(), any_dci(), io.BytesIO(ipv6_addr)) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_0_and_dac_equal_1_and_dam_equal_1(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_0_and_dac_eq_1_and_dam_eq_1(self): # GIVEN dci = any_dci() @@ -1851,7 +1861,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(1, dam) self.assertEqual(dst_addr, actual_dst_addr) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_0_and_dac_equal_1_and_dam_equal_2(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_0_and_dac_eq_1_and_dam_eq_2(self): # GIVEN dci = any_dci() @@ -1884,7 +1894,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(2, dam) self.assertEqual(dst_addr, actual_dst_addr) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_0_and_dac_equal_1_and_dam_equal_3(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_0_and_dac_eq_1_and_dam_eq_3(self): # GIVEN dci = any_dci() @@ -1919,7 +1929,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(3, dam) self.assertEqual(dst_addr, actual_dst_addr) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_1_and_dac_equal_0_and_dam_equal_0(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_1_and_dac_eq_0_and_dam_eq_0(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1941,7 +1951,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(0, dam) self.assertEqual(ipv6_addr, actual_dst_addr) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_1_and_dac_equal_0_and_dam_equal_1(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_1_and_dac_eq_0_and_dam_eq_1(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1966,7 +1976,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(1, dam) self.assertEqual(expected_dst_addr, actual_dst_addr) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_1_and_dac_equal_0_and_dam_equal_2(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_1_and_dac_eq_0_and_dam_eq_2(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -1991,7 +2001,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(2, dam) self.assertEqual(expected_dst_addr, actual_dst_addr) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_1_and_dac_equal_0_and_dam_equal_3(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_1_and_dac_eq_0_and_dam_eq_3(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -2016,7 +2026,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(3, dam) self.assertEqual(expected_dst_addr, actual_dst_addr) - def test_should_raise_RuntimeError_when_decompress_dst_addr_is_called_with_m_equal_1_and_dac_equal_1_and_dam_equal_0(self): + def test_should_raise_RuntimeError_when_decompress_dst_addr_called_with_m_eq_1_and_dac_eq_1_and_dam_eq_0(self): # GIVEN dci = any_dci() @@ -2055,7 +2065,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): self.assertEqual(0, dam) self.assertEqual(dst_addr, actual_dst_addr) - def test_should_raise_RuntimeError_when_decompress_dst_addr_is_called_with_m_equal_1_and_dac_equal_1_and_dam_equal_1(self): + def test_should_raise_RuntimeError_when_decompress_dst_addr_called_with_m_eq_1_and_dac_eq_1_and_dam_eq_1(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -2068,14 +2078,11 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): iphc = lowpan.LowpanIPHC(any_tf(), any_nh(), any_hlim(), any_cid(), any_sac(), any_sam(), m, dac, dam) - expected_dst_addr = bytearray([0xff, addr48b[0], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, addr48b[1], addr48b[2], addr48b[3], addr48b[4], addr48b[5]]) - # WHEN self.assertRaises(RuntimeError, factory._decompress_dst_addr, iphc, any_dst_mac_addr(), any_dci(), io.BytesIO(addr48b)) - def test_should_raise_RuntimeError_when_decompress_dst_addr_is_called_with_m_equal_1_and_dac_equal_1_and_dam_equal_2(self): + def test_should_raise_RuntimeError_when_decompress_dst_addr_called_with_m_eq_1_and_dac_eq_1_and_dam_eq_2(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -2088,14 +2095,11 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): iphc = lowpan.LowpanIPHC(any_tf(), any_nh(), any_hlim(), any_cid(), any_sac(), any_sam(), m, dac, dam) - expected_dst_addr = bytearray([0xff, addr32b[0], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, addr32b[1], addr32b[2], addr32b[3]]) - # WHEN self.assertRaises(RuntimeError, factory._decompress_dst_addr, iphc, any_dst_mac_addr(), any_dci(), io.BytesIO(addr32b)) - def test_should_parse_destination_address_when_decompress_dst_addr_is_called_with_m_equal_1_and_dac_equal_1_and_dam_equal_3(self): + def test_should_parse_dst_addr_when_decompress_dst_addr_called_with_m_eq_1_and_dac_eq_1_and_dam_eq_3(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -2108,14 +2112,11 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): iphc = lowpan.LowpanIPHC(any_tf(), any_nh(), any_hlim(), any_cid(), any_sac(), any_sam(), m, dac, dam) - expected_dst_addr = bytearray([0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, addr8b[0]]) - # WHEN self.assertRaises(RuntimeError, factory._decompress_dst_addr, iphc, any_dst_mac_addr(), any_dci(), io.BytesIO(addr8b)) - def test_should_merge_prefix_with_address_bytes_when_merge_method_is_called_with_prefix_shorter_than_missing_bits(self): + def test_should_merge_pfx_with_addr_bytes_when_merge_method_called_with_pfx_shorter_than_missing_bits(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -2132,7 +2133,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): # THEN self.assertEqual(addr, actual_addr) - def test_should_merge_prefix_with_address_bytes_when_merge_method_is_called_with_prefix_longer_than_missing_bits_overlapping(self): + def test_should_merge_pfx_with_addr_bytes_when_merge_method_called_with_pfx_longer_than_missing_bits_overlap(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -2149,7 +2150,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): # THEN self.assertEqual(addr, actual_addr) - def test_should_merge_prefix_with_address_bytes_when_merge_method_is_called_with_prefix_longer_than_missing_bits(self): + def test_should_merge_pfx_with_address_bytes_when_merge_method_called_with_pfx_longer_than_missing_bits(self): # GIVEN factory = lowpan.LowpanIpv6HeaderFactory() @@ -2170,7 +2171,7 @@ class TestLowpanIpv6HeaderFactory(unittest.TestCase): class TestContext(unittest.TestCase): - def test_should_extract_context_from_str_representation_when_constructor_is_called(self): + def test_should_extract_context_from_str_representation_when_constructor_called(self): # GIVEN prefix = "2000:db8::/64" @@ -2182,7 +2183,7 @@ class TestContext(unittest.TestCase): self.assertEqual(64, c.prefix_length) self.assertEqual(8, c.prefix_length_full_bytes) - def test_should_extract_context_from_bytearray_when_construct_is_called(self): + def test_should_extract_context_from_bytearray_when_construct_called(self): # GIVEN prefix = bytearray([0x20, 0x00, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00]) @@ -2228,7 +2229,7 @@ class TestContextManager(unittest.TestCase): class TestLowpanMeshHeader(unittest.TestCase): - def test_should_return_hops_left_value_when_hops_left_property_is_called(self): + def test_should_return_hops_left_value_when_hops_left_property_called(self): # GIVEN hops_left = any_hops_left() @@ -2240,7 +2241,7 @@ class TestLowpanMeshHeader(unittest.TestCase): # THEN self.assertEqual(hops_left, actual_hops_left) - def test_should_return_originator_address_value_when_originator_address_property_is_called(self): + def test_should_return_originator_address_value_when_originator_address_property_called(self): # GIVEN originator_address = any_mac_address() @@ -2252,7 +2253,7 @@ class TestLowpanMeshHeader(unittest.TestCase): # THEN self.assertEqual(originator_address, actual_originator_address) - def test_should_return_final_destination_address_value_when_final_destination_address_property_is_called(self): + def test_should_return_final_destination_address_value_when_final_destination_address_property_called(self): # GIVEN final_destination_address = any_mac_address() @@ -2267,7 +2268,7 @@ class TestLowpanMeshHeader(unittest.TestCase): class TestLowpanMeshHeaderFactory(unittest.TestCase): - def test_should_create_LowpanMeshHeader_when_parse_method_is_called(self): + def test_should_create_LowpanMeshHeader_when_parse_method_called(self): # GIVEN hops_left = any_hops_left() @@ -2299,7 +2300,7 @@ class TestLowpanMeshHeaderFactory(unittest.TestCase): class TestLowpanFragmentationHeader(unittest.TestCase): - def test_should_return_datagram_size_value_when_datagram_size_property_is_called(self): + def test_should_return_datagram_size_value_when_datagram_size_property_called(self): # GIVEN datagram_size = any_datagram_size() @@ -2312,7 +2313,7 @@ class TestLowpanFragmentationHeader(unittest.TestCase): # THEN self.assertEqual(datagram_size, actual_datagram_size) - def test_should_return_datagram_tag_value_when_datagram_tag_property_is_called(self): + def test_should_return_datagram_tag_value_when_datagram_tag_property_called(self): # GIVEN datagram_tag = any_datagram_tag() @@ -2325,7 +2326,7 @@ class TestLowpanFragmentationHeader(unittest.TestCase): # THEN self.assertEqual(datagram_tag, actual_datagram_tag) - def test_should_return_datagram_offset_value_when_datagram_offset_property_is_called(self): + def test_should_return_datagram_offset_value_when_datagram_offset_property_called(self): # GIVEN datagram_offset = any_datagram_offset() @@ -2338,7 +2339,7 @@ class TestLowpanFragmentationHeader(unittest.TestCase): # THEN self.assertEqual(datagram_offset, actual_datagram_offset) - def test_should_return_False_when_is_first_property_is_called_and_datagram_offset_is_not_equal_0(self): + def test_should_return_False_when_is_first_property_called_and_datagram_offset_is_not_eq_0(self): # GIVEN datagram_offset = random.randint(1, (1 << 8) - 1) @@ -2351,7 +2352,7 @@ class TestLowpanFragmentationHeader(unittest.TestCase): # THEN self.assertFalse(is_first) - def test_should_to_bytes_LowpanFragmentationHeader_from_bytes_when_from_bytes_class_method_is_called(self): + def test_should_to_bytes_LowpanFragmentationHeader_from_bytes_when_from_bytes_class_method_called(self): # GIVEN datagram_size = any_datagram_size() datagram_tag = any_datagram_tag() @@ -2371,7 +2372,7 @@ class TestLowpanFragmentationHeader(unittest.TestCase): class TestLowpanDecompressor(unittest.TestCase): - def test_should_parse_parent_request_when_decompress_method_is_called(self): + def test_should_parse_parent_request_when_decompress_method_called(self): # GIVEN data = bytearray([0x7f, 0x3b, 0x02, 0xf0, 0x4d, 0x4c, 0x4d, 0x4c, 0x5e, 0xaf, 0x00, 0x15, 0x00, 0x00, 0x00, 0x00, @@ -2397,7 +2398,7 @@ class TestLowpanDecompressor(unittest.TestCase): self.assertEqual([], extension_headers) - def test_should_parse_parent_response_when_decompress_method_is_called(self): + def test_should_parse_parent_response_when_decompress_method_called(self): # GIVEN data = bytearray([0x7f, 0x33, 0xf0, 0x4d, 0x4c, 0x4d, 0x4c, 0x0f, 0xe8, 0x00, 0x15, 0x04, 0x00, 0x00, 0x00, 0x00, @@ -2434,7 +2435,7 @@ class TestLowpanDecompressor(unittest.TestCase): self.assertEqual(19788, udp_header.src_port) self.assertEqual(19788, udp_header.dst_port) - def test_should_parse_child_id_request_when_decompress_method_is_called(self): + def test_should_parse_child_id_request_when_decompress_method_called(self): # GIVEN data = bytearray([0x7f, 0x33, 0xf0, 0x4d, 0x4c, 0x4d, 0x4c, 0x9a, 0x62, 0x00, 0x15, 0x01, 0x00, 0x00, 0x00, 0x00, @@ -2469,7 +2470,7 @@ class TestLowpanDecompressor(unittest.TestCase): self.assertEqual(19788, udp_header.src_port) self.assertEqual(19788, udp_header.dst_port) - def test_should_parse_child_id_response_when_decompress_method_is_called(self): + def test_should_parse_child_id_response_when_decompress_method_called(self): # GIVEN data = bytearray([0x7f, 0x33, 0xf0, 0x4d, 0x4c, 0x4d, 0x4c, 0x7b, 0xe3, 0x00, 0x15, 0x05, 0x00, 0x00, 0x00, 0x00, @@ -2503,7 +2504,7 @@ class TestLowpanDecompressor(unittest.TestCase): self.assertEqual(19788, udp_header.src_port) self.assertEqual(19788, udp_header.dst_port) - def test_should_parse_advertisement_when_decompress_method_is_called(self): + def test_should_parse_advertisement_when_decompress_method_called(self): # GIVEN data = bytearray([0x7f, 0x3b, 0x01, 0xf0, 0x4d, 0x4c, 0x4d, 0x4c, 0x35, 0x9f, 0x00, 0x15, 0x07, 0x00, 0x00, 0x00, @@ -2536,7 +2537,7 @@ class TestLowpanDecompressor(unittest.TestCase): class TestLowpanFragmentsBuffer(unittest.TestCase): - def test_should_raise_ValueError_when_write_method_is_called_with_data_length_bigger_than_buffer_length(self): + def test_should_raise_ValueError_when_write_method_called_with_data_length_bigger_than_buffer_length(self): # GIVEN length = random.randint(1, 1280) @@ -2545,7 +2546,7 @@ class TestLowpanFragmentsBuffer(unittest.TestCase): # THEN self.assertRaises(ValueError, fragments_buffer.write, any_data(length)) - def test_should_move_write_position_by_the_data_length_when_write_method_is_called(self): + def test_should_move_write_position_by_the_data_length_when_write_method_called(self): # GIVEN length = random.randint(1, 1280) @@ -2561,7 +2562,7 @@ class TestLowpanFragmentsBuffer(unittest.TestCase): # THEN self.assertEqual(fragments_buffer.tell() - start_position, len(data)) - def test_should_raise_ValueError_when_read_method_is_called_but_not_whole_packet_has_been_stored_in_buffer(self): + def test_should_raise_ValueError_when_read_method_called_but_not_whole_packet_has_been_stored_in_buffer(self): # GIVEN data = any_data(length=3) @@ -2571,7 +2572,7 @@ class TestLowpanFragmentsBuffer(unittest.TestCase): # WHEN self.assertRaises(ValueError, fragments_buffer.read) - def test_should_raise_ValueError_when_seek_method_is_called_with_offset_bigger_than_buffer_length(self): + def test_should_raise_ValueError_when_seek_method_called_with_offset_bigger_than_buffer_length(self): # GIVEN offset = random.randint(1281, 2500) @@ -2580,7 +2581,7 @@ class TestLowpanFragmentsBuffer(unittest.TestCase): # THEN self.assertRaises(ValueError, fragments_buffer.seek, offset) - def test_should_set_write_position_when_seek_method_is_called(self): + def test_should_set_write_position_when_seek_method_called(self): # GIVEN length = random.randint(1, 1280) offset = random.randint(0, length - 1) @@ -2593,7 +2594,7 @@ class TestLowpanFragmentsBuffer(unittest.TestCase): # THEN self.assertEqual(offset, fragments_buffer.tell()) - def test_should_write_whole_packet_to_buffer_when_write_method_is_called(self): + def test_should_write_whole_packet_to_buffer_when_write_method_called(self): # GIVEN data = any_data(length=random.randint(1, 1280)) @@ -2605,7 +2606,7 @@ class TestLowpanFragmentsBuffer(unittest.TestCase): # THEN self.assertEqual(data, fragments_buffer.read()) - def test_should_write_many_fragments_to_the_buffer_and_return_whole_message_when_write_method_is_called_many_times(self): + def test_should_write_many_frags_to_the_buffer_and_return_whole_message_when_write_method_called_many_times(self): # GIVEN buffer_size = 42 fragments_buffer = lowpan.LowpanFragmentsBuffer(buffer_size=buffer_size) @@ -2659,7 +2660,7 @@ class TestLowpanFragmentsBuffer(unittest.TestCase): class TestLowpanFragmentsBuffersManager(unittest.TestCase): - def test_should_raise_ValueError_when_get_fragments_buffer_method_is_called_with_invalid_datagram_size(self): + def test_should_raise_ValueError_when_get_fragments_buffer_method_called_with_invalid_dgram_size(self): # GIVEN message_info = common.MessageInfo() message_info.source_mac_address = any_mac_address() @@ -2673,7 +2674,7 @@ class TestLowpanFragmentsBuffersManager(unittest.TestCase): self.assertRaises(ValueError, manager.get_fragments_buffer, message_info, any_datagram_tag(), None) self.assertRaises(ValueError, manager.get_fragments_buffer, message_info, any_datagram_tag(), negative_int) - def test_should_return_LowpanFragmentsBuffer_when_get_fragments_buffer_method_is_called_with_valid_datagram_size(self): + def test_should_return_LowpanFragmentsBuffer_when_get_fragments_buffer_method_called_with_valid_dgram_size(self): # GIVEN message_info = common.MessageInfo() message_info.source_mac_address = any_mac_address() @@ -2690,5 +2691,6 @@ class TestLowpanFragmentsBuffersManager(unittest.TestCase): self.assertIsInstance(fragments_buffer, lowpan.LowpanFragmentsBuffer) self.assertEqual(datagram_size, len(fragments_buffer)) + if __name__ == "__main__": unittest.main(verbosity=1) diff --git a/tests/scripts/thread-cert/test_mac802154.py b/tests/scripts/thread-cert/test_mac802154.py index f8404d245..7f2794cdd 100755 --- a/tests/scripts/thread-cert/test_mac802154.py +++ b/tests/scripts/thread-cert/test_mac802154.py @@ -45,7 +45,9 @@ class TestMacParser(unittest.TestCase): frame = mac802154.MacFrame() frame.parse(io.BytesIO(bytearray([0x12, 0x00, 0x12, 0x34, 0x56]))) - self.assertEqual(mac802154.MacHeader.FrameType.ACK, frame.header.frame_type) + self.assertEqual( + mac802154.MacHeader.FrameType.ACK, + frame.header.frame_type) self.assertEqual(True, frame.header.frame_pending) self.assertEqual(False, frame.header.ack_request) self.assertEqual(0, frame.header.frame_version) @@ -58,7 +60,9 @@ class TestMacParser(unittest.TestCase): frame.parse(io.BytesIO(bytearray([0x61, 0x88, 0x34, 0xce, 0xfa, 0xad, 0xde, 0xef, 0xbe, 0x12, 0x34, 0xfe, 0xdc]))) - self.assertEqual(mac802154.MacHeader.FrameType.DATA, frame.header.frame_type) + self.assertEqual( + mac802154.MacHeader.FrameType.DATA, + frame.header.frame_type) self.assertEqual(False, frame.header.frame_pending) self.assertEqual(True, frame.header.ack_request) self.assertEqual(0, frame.header.frame_version) @@ -81,18 +85,30 @@ class TestMacParser(unittest.TestCase): 0x12, 0x34, 0xfe, 0xdc]))) - self.assertEqual(mac802154.MacHeader.FrameType.DATA, frame.header.frame_type) + self.assertEqual( + mac802154.MacHeader.FrameType.DATA, + frame.header.frame_type) self.assertEqual(False, frame.header.frame_pending) self.assertEqual(True, frame.header.ack_request) self.assertEqual(0, frame.header.frame_version) self.assertEqual(0x56, frame.header.seq) self.assertEqual(bytearray([0xfe, 0xdc]), frame.header.fcs) self.assertEqual(0xface, frame.header.dest_pan_id) - self.assertEqual(bytearray(reversed([0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef])), - frame.header.dest_address.mac_address) + self.assertEqual( + bytearray( + reversed( + [ + 0xde, 0xad, 0xbe, 0xef, + 0xde, 0xad, 0xbe, 0xef])), + frame.header.dest_address.mac_address) self.assertEqual(0xface, frame.header.src_pan_id) - self.assertEqual(bytearray(reversed([0x0b, 0xad, 0xf0, 0x0d, 0xba, 0xd0, 0xd0, 0x0d])), - frame.header.src_address.mac_address) + self.assertEqual( + bytearray( + reversed( + [ + 0x0b, 0xad, 0xf0, 0x0d, + 0xba, 0xd0, 0xd0, 0x0d])), + frame.header.src_address.mac_address) self.assertEqual(bytearray([0x12, 0x34]), frame.payload.data) @@ -106,7 +122,9 @@ class TestMacParser(unittest.TestCase): 0x12, 0x34, 0xfe, 0xdc]))) - self.assertEqual(mac802154.MacHeader.FrameType.DATA, frame.header.frame_type) + self.assertEqual( + mac802154.MacHeader.FrameType.DATA, + frame.header.frame_type) self.assertEqual(False, frame.header.frame_pending) self.assertEqual(True, frame.header.ack_request) self.assertEqual(0, frame.header.frame_version) @@ -115,8 +133,13 @@ class TestMacParser(unittest.TestCase): self.assertEqual(0xface, frame.header.dest_pan_id) self.assertEqual(0xdead, frame.header.dest_address.rloc) self.assertEqual(0xface, frame.header.src_pan_id) - self.assertEqual(bytearray(reversed([0x0b, 0xad, 0xf0, 0x0d, 0xba, 0xd0, 0xd0, 0x0d])), - frame.header.src_address.mac_address) + self.assertEqual( + bytearray( + reversed( + [ + 0x0b, 0xad, 0xf0, 0x0d, + 0xba, 0xd0, 0xd0, 0x0d])), + frame.header.src_address.mac_address) self.assertEqual(bytearray([0x12, 0x34]), frame.payload.data) @@ -125,20 +148,28 @@ class TestMacParser(unittest.TestCase): frame.parse(io.BytesIO(bytearray([0x61, 0x8c, 0x56, 0xce, 0xfa, - 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, + 0xde, 0xad, 0xbe, 0xef, + 0xde, 0xad, 0xbe, 0xef, 0x0d, 0xf0, 0x12, 0x34, 0xfe, 0xdc]))) - self.assertEqual(mac802154.MacHeader.FrameType.DATA, frame.header.frame_type) + self.assertEqual( + mac802154.MacHeader.FrameType.DATA, + frame.header.frame_type) self.assertEqual(False, frame.header.frame_pending) self.assertEqual(True, frame.header.ack_request) self.assertEqual(0, frame.header.frame_version) self.assertEqual(0x56, frame.header.seq) self.assertEqual(bytearray([0xfe, 0xdc]), frame.header.fcs) self.assertEqual(0xface, frame.header.dest_pan_id) - self.assertEqual(bytearray(reversed([0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef])), - frame.header.dest_address.mac_address) + self.assertEqual( + bytearray( + reversed( + [ + 0xde, 0xad, 0xbe, 0xef, + 0xde, 0xad, 0xbe, 0xef])), + frame.header.dest_address.mac_address) self.assertEqual(0xface, frame.header.src_pan_id) self.assertEqual(0xf00d, frame.header.src_address.rloc) @@ -154,7 +185,9 @@ class TestMacParser(unittest.TestCase): 0x04, 0xfe, 0xdc]))) - self.assertEqual(mac802154.MacHeader.FrameType.COMMAND, frame.header.frame_type) + self.assertEqual( + mac802154.MacHeader.FrameType.COMMAND, + frame.header.frame_type) self.assertEqual(False, frame.header.frame_pending) self.assertEqual(True, frame.header.ack_request) self.assertEqual(0, frame.header.frame_version) @@ -169,8 +202,8 @@ class TestMacParser(unittest.TestCase): def test_should_decrypt_data_frame(self): - mac802154.DeviceDescriptors.add(0x2001, MacAddress(bytearray([0x16, 0x6e, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x07]), - MacAddressType.LONG)) + mac802154.DeviceDescriptors.add(0x2001, MacAddress(bytearray( + [0x16, 0x6e, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x07]), MacAddressType.LONG)) frame = mac802154.MacFrame() frame.parse(io.BytesIO(bytearray([0x69, 0x98, 0x68, # FC, seq @@ -182,11 +215,13 @@ class TestMacParser(unittest.TestCase): 0xc4, 0x6f, 0x7d, 0x6b, 0xb5, 0x4a, 0x87, 0x14, 0xae, 0xdd, 0x8e, 0xb7, 0x37, 0x62, 0x27, 0x48, 0xc9, 0x53, 0x0c, 0x44, 0x31, 0x59, 0x8b, 0xa2, - 0x83, 0x59, 0xa1, 0x43, - 0x74, 0xe0, 0x2a, 0xf6, # MIC (valid) + 0x83, 0x59, 0xa1, 0x43, # MIC (valid) + 0x74, 0xe0, 0x2a, 0xf6, 0x99, 0xfc]))) # FCS (valid) - self.assertEqual(mac802154.MacHeader.FrameType.DATA, frame.header.frame_type) + self.assertEqual( + mac802154.MacHeader.FrameType.DATA, + frame.header.frame_type) self.assertEqual(False, frame.header.frame_pending) self.assertEqual(True, frame.header.ack_request) self.assertEqual(1, frame.header.frame_version) @@ -200,31 +235,44 @@ class TestMacParser(unittest.TestCase): self.assertEqual(0, frame.header.aux_sec_header.frame_counter) self.assertEqual(5, frame.header.aux_sec_header.security_level) - self.assertEqual(bytes(bytearray([0x7c, 0x77, 0x80, 0xf0, 0x4d, 0x4d, 0x4d, 0x4d, - 0xe0, 0x04, 0x44, 0x02, 0x44, 0x66, 0x13, 0x5f, - 0x22, 0x80, 0xb1, 0x61, 0x02, 0x61, 0x73, 0x11, - 0x2a, 0xff, 0x01, 0x08, 0x16, 0x6e, 0x0a, 0x00, - 0x00, 0x00, 0x00, 0x07])), frame.payload.data) + self.assertEqual(bytes(bytearray([0x7c, 0x77, 0x80, 0xf0, + 0x4d, 0x4d, 0x4d, 0x4d, + 0xe0, 0x04, 0x44, 0x02, + 0x44, 0x66, 0x13, 0x5f, + 0x22, 0x80, 0xb1, 0x61, + 0x02, 0x61, 0x73, 0x11, + 0x2a, 0xff, 0x01, 0x08, + 0x16, 0x6e, 0x0a, 0x00, + 0x00, 0x00, 0x00, 0x07])), + frame.payload.data) def test_should_decrypt_command_frame(self): frame = mac802154.MacFrame() - frame.parse(io.BytesIO(bytearray([0x6b, 0xdc, 0xce, 0xce, 0xfa, 0x02, 0x00, 0x00, - 0x00, 0x00, 0x0a, 0x6e, 0x16, 0x03, 0x00, 0x00, - 0x00, 0x00, 0x0a, 0x6e, 0x16, 0x0d, 0x00, 0x00, - 0x00, 0x00, 0x01, 0x04, 0x2d, 0xbc, 0x12, 0xbe, + frame.parse(io.BytesIO(bytearray([0x6b, 0xdc, 0xce, 0xce, + 0xfa, 0x02, 0x00, 0x00, + 0x00, 0x00, 0x0a, 0x6e, + 0x16, 0x03, 0x00, 0x00, + 0x00, 0x00, 0x0a, 0x6e, + 0x16, 0x0d, 0x00, 0x00, + 0x00, 0x00, 0x01, 0x04, + 0x2d, 0xbc, 0x12, 0xbe, 0x0a, 0x4f]))) - self.assertEqual(mac802154.MacHeader.FrameType.COMMAND, frame.header.frame_type) + self.assertEqual( + mac802154.MacHeader.FrameType.COMMAND, + frame.header.frame_type) self.assertEqual(False, frame.header.frame_pending) self.assertEqual(True, frame.header.ack_request) self.assertEqual(1, frame.header.frame_version) self.assertEqual(206, frame.header.seq) self.assertEqual(bytearray([0x0a, 0x4f]), frame.header.fcs) self.assertEqual(0xface, frame.header.dest_pan_id) - self.assertEqual(bytearray([0x16, 0x6e, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x02]), + self.assertEqual(bytearray([0x16, 0x6e, 0x0a, 0x00, + 0x00, 0x00, 0x00, 0x02]), frame.header.dest_address.mac_address) self.assertEqual(0xface, frame.header.src_pan_id) - self.assertEqual(bytearray([0x16, 0x6e, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x03]), + self.assertEqual(bytearray([0x16, 0x6e, 0x0a, 0x00, + 0x00, 0x00, 0x00, 0x03]), frame.header.src_address.mac_address) self.assertEqual(0, frame.header.aux_sec_header.frame_counter) diff --git a/tests/scripts/thread-cert/test_mle.py b/tests/scripts/thread-cert/test_mle.py index 38ba25b15..9c5b0a8d0 100755 --- a/tests/scripts/thread-cert/test_mle.py +++ b/tests/scripts/thread-cert/test_mle.py @@ -34,12 +34,9 @@ import unittest import common import config -import net_crypto import mle import network_data -from ipaddress import ip_address - def any_address(): return random.getrandbits(16) @@ -60,6 +57,7 @@ def any_device_type(): def any_network_data(): return random.getrandbits(1) + mode_map = { 0x00: {"receiver": 0, "secure": 0, "device_type": 0, "network_data": 0}, 0x08: {"receiver": 1, "secure": 0, "device_type": 0, "network_data": 0}, @@ -118,10 +116,6 @@ def any_route(): return random.getrandbits(4) -def any_id_sequence(): - return random.getrandbits(1) - - def any_router_id_mask(): return random.getrandbits(64) @@ -150,6 +144,7 @@ def any_stable_data_version(): def any_leader_router_id(): return random.getrandbits(8) + scan_mask_map = { 0x00: {"router": 0, "end_device": 0}, 0x40: {"router": 0, "end_device": 1}, @@ -1188,8 +1183,8 @@ class TestConnectivityFactory(unittest.TestCase): leader_cost = any_leader_cost() id_sequence = any_id_sequence() active_routers = any_active_routers() - sed_buffer_size = any_sed_buffer_size() - sed_datagram_count = any_sed_datagram_count() + any_sed_buffer_size() + any_sed_datagram_count() factory = mle.ConnectivityFactory() diff --git a/tests/scripts/thread-cert/test_network_data.py b/tests/scripts/thread-cert/test_network_data.py index 3c4373145..e72b9c70f 100755 --- a/tests/scripts/thread-cert/test_network_data.py +++ b/tests/scripts/thread-cert/test_network_data.py @@ -39,7 +39,9 @@ import network_data def convert_route_to_bytearray(route): - return struct.pack(">HB", route.border_router_16, ((route.prf & 0x03) << 6)) + return struct.pack( + ">HB", route.border_router_16, ((route.prf & 0x03) << 6) + ) def convert_routes_to_bytearray(routes): @@ -55,21 +57,26 @@ def convert_has_route_to_bytearray(has_route): def convert_border_router_to_bytearray(border_router): - data = struct.pack(">HBB", border_router.border_router_16, - (border_router.o & 0x01) | - ((border_router.r & 0x01) << 1) | - ((border_router.c & 0x01) << 2) | - ((border_router.d & 0x01) << 3) | - ((border_router.s & 0x01) << 4) | - ((border_router.p & 0x01) << 5) | - ((border_router.prf & 0x03) << 6), - ((border_router.n & 0x01) << 7)) + data = struct.pack( + ">HBB", + border_router.border_router_16, + (border_router.o & 0x01) + | ((border_router.r & 0x01) << 1) + | ((border_router.c & 0x01) << 2) + | ((border_router.d & 0x01) << 3) + | ((border_router.s & 0x01) << 4) + | ((border_router.p & 0x01) << 5) + | ((border_router.prf & 0x03) << 6), + ((border_router.n & 0x01) << 7), + ) return data def convert_lowpan_id_to_bytearray(lowpan_id): - return bytearray([lowpan_id.cid | (lowpan_id.c << 4), lowpan_id.context_length]) + return bytearray( + [lowpan_id.cid | (lowpan_id.c << 4), lowpan_id.context_length] + ) def convert_prefix_sub_tlvs_to_bytearray(sub_tlvs): @@ -78,15 +85,15 @@ def convert_prefix_sub_tlvs_to_bytearray(sub_tlvs): for sub_tlv in sub_tlvs: if isinstance(sub_tlv, network_data.HasRoute): value = convert_has_route_to_bytearray(sub_tlv) - _type = sub_tlv.stable | ((0 & 0x7f) << 1) + _type = sub_tlv.stable | ((0 & 0x7F) << 1) elif isinstance(sub_tlv, network_data.BorderRouter): value = convert_border_router_to_bytearray(sub_tlv) - _type = sub_tlv.stable | ((2 & 0x7f) << 1) + _type = sub_tlv.stable | ((2 & 0x7F) << 1) elif isinstance(sub_tlv, network_data.LowpanId): value = convert_lowpan_id_to_bytearray(sub_tlv) - _type = sub_tlv.stable | ((3 & 0x7f) << 1) + _type = sub_tlv.stable | ((3 & 0x7F) << 1) else: raise ValueError @@ -106,7 +113,7 @@ def convert_service_sub_tlvs_to_bytearray(sub_tlvs): for sub_tlv in sub_tlvs: if isinstance(sub_tlv, network_data.Server): value = convert_server_to_bytearray(sub_tlv) - _type = sub_tlv.stable | ((6 & 0x7f) << 1) + _type = sub_tlv.stable | ((6 & 0x7F) << 1) else: raise ValueError @@ -117,11 +124,16 @@ def convert_service_sub_tlvs_to_bytearray(sub_tlvs): def convert_service_to_bytearray(service): - return struct.pack(">BLB", ((service.t & 0x01) << 7) | ((service.id) & 0x0f), - service.enterprise_number, - service.service_data_length) + \ - service.service_data + \ - convert_service_sub_tlvs_to_bytearray(service.sub_tlvs) + return ( + struct.pack( + ">BLB", + ((service.t & 0x01) << 7) | ((service.id) & 0x0F), + service.enterprise_number, + service.service_data_length, + ) + + service.service_data + + convert_service_sub_tlvs_to_bytearray(service.sub_tlvs) + ) def any_border_router_16(): @@ -159,7 +171,12 @@ def any_prefix(prefix_length=None): if prefix_length is None: prefix_length = any_prefix_length() - return bytearray([random.getrandbits(8) for _ in range(int(math.ceil(prefix_length / 8)))]) + return bytearray( + [ + random.getrandbits(8) + for _ in range(int(math.ceil(prefix_length / 8))) + ] + ) def any_p(): @@ -199,19 +216,28 @@ def any_context_length(): def any_border_router(): - return network_data.BorderRouter(any_border_router_16(), any_prf(), any_p(), any_s(), any_d(), any_c(), any_r(), any_o(), any_n(), any_stable()) + return network_data.BorderRouter( + any_border_router_16(), + any_prf(), + any_p(), + any_s(), + any_d(), + any_c(), + any_r(), + any_o(), + any_n(), + any_stable(), + ) def any_lowpan_id(): - return network_data.LowpanId(any_c(), any_cid(), any_context_length(), any_stable()) + return network_data.LowpanId( + any_c(), any_cid(), any_context_length(), any_stable() + ) def any_prefix_sub_tlvs(): - creator = [ - any_has_route, - any_border_router, - any_lowpan_id - ] + creator = [any_has_route, any_border_router, any_lowpan_id] sub_tlvs = [] @@ -257,13 +283,13 @@ def any_server_data(data_length=None): def any_server(): - return network_data.Server(any_server_16(), any_server_data(), any_stable()) + return network_data.Server( + any_server_16(), any_server_data(), any_stable() + ) def any_service_sub_tlvs(): - creator = [ - any_server - ] + creator = [any_server] sub_tlvs = [] @@ -279,8 +305,8 @@ def any_stable(): class TestRoute(unittest.TestCase): - - def test_should_return_border_router_16_value_when_border_router_16_property_is_called(self): + def test_should_return_border_router_16_value_when_border_router_16_property_is_called( + self): # GIVEN border_router_16 = any_border_router_16() @@ -306,15 +332,18 @@ class TestRoute(unittest.TestCase): class TestRouteFactory(unittest.TestCase): - - def test_should_create_Route_from_bytearray_when_parse_method_is_called(self): + def test_should_create_Route_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN border_router_16 = any_border_router_16() prf = any_prf() factory = network_data.RouteFactory() - data = convert_route_to_bytearray(network_data.Route(border_router_16, prf)) + data = convert_route_to_bytearray( + network_data.Route(border_router_16, prf) + ) # WHEN actual_route = factory.parse(io.BytesIO(data), None) @@ -326,8 +355,8 @@ class TestRouteFactory(unittest.TestCase): class TestRoutesFactory(unittest.TestCase): - - def test_should_create_Route_list_from_bytearray_when_parse_method_is_called(self): + def test_should_create_Route_list_from_bytearray_when_parse_method_is_called( + self): # GIVEN routes = any_routes() @@ -343,7 +372,6 @@ class TestRoutesFactory(unittest.TestCase): class TestHasRoute(unittest.TestCase): - def test_should_return_routes_value_when_routes_property_is_called(self): # GIVEN routes = any_routes() @@ -370,13 +398,16 @@ class TestHasRoute(unittest.TestCase): class TestHasRouteFactory(unittest.TestCase): - - def test_should_create_HasRoute_from_bytearray_when_parse_method_is_called(self): + def test_should_create_HasRoute_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN routes = any_routes() stable = any_stable() - factory = network_data.HasRouteFactory(network_data.RoutesFactory(network_data.RouteFactory())) + factory = network_data.HasRouteFactory( + network_data.RoutesFactory(network_data.RouteFactory()) + ) data = convert_routes_to_bytearray(routes) @@ -393,12 +424,19 @@ class TestHasRouteFactory(unittest.TestCase): class TestPrefix(unittest.TestCase): - - def test_should_return_domain_id_value_when_domain_id_property_is_called(self): + def test_should_return_domain_id_value_when_domain_id_property_is_called( + self + ): # GIVEN domain_id = any_domain_id() - prefix = network_data.Prefix(domain_id, any_prefix_length(), any_prefix(), any_prefix_sub_tlvs(), any_stable()) + prefix = network_data.Prefix( + domain_id, + any_prefix_length(), + any_prefix(), + any_prefix_sub_tlvs(), + any_stable(), + ) # WHEN actual_domain_id = prefix.domain_id @@ -406,11 +444,18 @@ class TestPrefix(unittest.TestCase): # THEN self.assertEqual(domain_id, actual_domain_id) - def test_should_return_prefix_length_value_when_prefix_length_property_is_called(self): + def test_should_return_prefix_length_value_when_prefix_length_property_is_called( + self): # GIVEN prefix_length = any_prefix_length() - prefix = network_data.Prefix(any_domain_id(), prefix_length, any_prefix(), any_prefix_sub_tlvs(), any_stable()) + prefix = network_data.Prefix( + any_domain_id(), + prefix_length, + any_prefix(), + any_prefix_sub_tlvs(), + any_stable(), + ) # WHEN actual_prefix_length = prefix.prefix_length @@ -422,8 +467,13 @@ class TestPrefix(unittest.TestCase): # GIVEN prefix = any_prefix() - prefix_obj = network_data.Prefix(any_domain_id(), any_prefix_length(), - prefix, any_prefix_sub_tlvs(), any_stable()) + prefix_obj = network_data.Prefix( + any_domain_id(), + any_prefix_length(), + prefix, + any_prefix_sub_tlvs(), + any_stable(), + ) # WHEN actual_prefix = prefix_obj.prefix @@ -431,11 +481,19 @@ class TestPrefix(unittest.TestCase): # THEN self.assertEqual(prefix, actual_prefix) - def test_should_return_sub_tlvs_value_when_sub_tlvs_property_is_called(self): + def test_should_return_sub_tlvs_value_when_sub_tlvs_property_is_called( + self + ): # GIVEN sub_tlvs = any_prefix_sub_tlvs() - prefix_obj = network_data.Prefix(any_domain_id(), any_prefix_length(), any_prefix(), sub_tlvs, any_stable()) + prefix_obj = network_data.Prefix( + any_domain_id(), + any_prefix_length(), + any_prefix(), + sub_tlvs, + any_stable(), + ) # WHEN actual_sub_tlvs = prefix_obj.sub_tlvs @@ -447,8 +505,13 @@ class TestPrefix(unittest.TestCase): # GIVEN stable = any_stable() - prefix_obj = network_data.Prefix(any_domain_id(), any_prefix_length(), - any_prefix(), any_prefix_sub_tlvs(), stable) + prefix_obj = network_data.Prefix( + any_domain_id(), + any_prefix_length(), + any_prefix(), + any_prefix_sub_tlvs(), + stable, + ) # WHEN actual_stable = prefix_obj.stable @@ -458,12 +521,15 @@ class TestPrefix(unittest.TestCase): class TestPrefixSubTlvsFactory(unittest.TestCase): - - def test_should_create_SubTlvs_from_bytearray_when_parse_method_is_called(self): + def test_should_create_SubTlvs_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN sub_tlvs = any_prefix_sub_tlvs() - factory = network_data.PrefixSubTlvsFactory(config.create_default_network_data_prefix_sub_tlvs_factories()) + factory = network_data.PrefixSubTlvsFactory( + config.create_default_network_data_prefix_sub_tlvs_factories() + ) data = convert_prefix_sub_tlvs_to_bytearray(sub_tlvs) @@ -476,17 +542,24 @@ class TestPrefixSubTlvsFactory(unittest.TestCase): class TestPrefixFactory(unittest.TestCase): - - def test_should_create_Prefix_from_bytearray_when_parse_method_is_called(self): + def test_should_create_Prefix_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN domain_id = any_domain_id() prefix_length = any_prefix_length() prefix = any_prefix(prefix_length) sub_tlvs = any_prefix_sub_tlvs() - factory = network_data.PrefixFactory(config.create_default_network_data_prefix_sub_tlvs_factory()) + factory = network_data.PrefixFactory( + config.create_default_network_data_prefix_sub_tlvs_factory() + ) - data = bytearray([domain_id, prefix_length]) + prefix + convert_prefix_sub_tlvs_to_bytearray(sub_tlvs) + data = ( + bytearray([domain_id, prefix_length]) + + prefix + + convert_prefix_sub_tlvs_to_bytearray(sub_tlvs) + ) message_info = common.MessageInfo() @@ -502,13 +575,23 @@ class TestPrefixFactory(unittest.TestCase): class TestBorderRouter(unittest.TestCase): - - def test_should_return_border_router_16_value_when_border_router_16_property_is_called(self): + def test_should_return_border_router_16_value_when_border_router_16_property_is_called( + self): # GIVEN border_router_16 = any_border_router_16() - border_router = network_data.BorderRouter(border_router_16, any_prf( - ), any_p(), any_s(), any_d(), any_c(), any_r(), any_o(), any_n(), any_stable()) + border_router = network_data.BorderRouter( + border_router_16, + any_prf(), + any_p(), + any_s(), + any_d(), + any_c(), + any_r(), + any_o(), + any_n(), + any_stable(), + ) # WHEN actual_border_router_16 = border_router.border_router_16 @@ -520,8 +603,18 @@ class TestBorderRouter(unittest.TestCase): # GIVEN prf = any_prf() - border_router = network_data.BorderRouter(any_border_router_16( - ), prf, any_p(), any_s(), any_d(), any_c(), any_r(), any_o(), any_n(), any_stable()) + border_router = network_data.BorderRouter( + any_border_router_16(), + prf, + any_p(), + any_s(), + any_d(), + any_c(), + any_r(), + any_o(), + any_n(), + any_stable(), + ) # WHEN actual_prf = border_router.prf @@ -533,8 +626,18 @@ class TestBorderRouter(unittest.TestCase): # GIVEN p = any_p() - border_router = network_data.BorderRouter(any_border_router_16(), any_prf( - ), p, any_s(), any_d(), any_c(), any_r(), any_o(), any_n(), any_stable()) + border_router = network_data.BorderRouter( + any_border_router_16(), + any_prf(), + p, + any_s(), + any_d(), + any_c(), + any_r(), + any_o(), + any_n(), + any_stable(), + ) # WHEN actual_p = border_router.p @@ -546,8 +649,18 @@ class TestBorderRouter(unittest.TestCase): # GIVEN s = any_s() - border_router = network_data.BorderRouter(any_border_router_16(), any_prf( - ), any_p(), s, any_d(), any_c(), any_r(), any_o(), any_n(), any_stable()) + border_router = network_data.BorderRouter( + any_border_router_16(), + any_prf(), + any_p(), + s, + any_d(), + any_c(), + any_r(), + any_o(), + any_n(), + any_stable(), + ) # WHEN actual_s = border_router.s @@ -559,8 +672,18 @@ class TestBorderRouter(unittest.TestCase): # GIVEN d = any_d() - border_router = network_data.BorderRouter(any_border_router_16(), any_prf( - ), any_p(), any_s(), d, any_c(), any_r(), any_o(), any_n(), any_stable()) + border_router = network_data.BorderRouter( + any_border_router_16(), + any_prf(), + any_p(), + any_s(), + d, + any_c(), + any_r(), + any_o(), + any_n(), + any_stable(), + ) # WHEN actual_d = border_router.d @@ -572,8 +695,18 @@ class TestBorderRouter(unittest.TestCase): # GIVEN c = any_c() - border_router = network_data.BorderRouter(any_border_router_16(), any_prf( - ), any_p(), any_s(), any_d(), c, any_r(), any_o(), any_n(), any_stable()) + border_router = network_data.BorderRouter( + any_border_router_16(), + any_prf(), + any_p(), + any_s(), + any_d(), + c, + any_r(), + any_o(), + any_n(), + any_stable(), + ) # WHEN actual_c = border_router.c @@ -585,8 +718,18 @@ class TestBorderRouter(unittest.TestCase): # GIVEN r = any_r() - border_router = network_data.BorderRouter(any_border_router_16(), any_prf( - ), any_p(), any_s(), any_d(), any_c(), r, any_o(), any_n(), any_stable()) + border_router = network_data.BorderRouter( + any_border_router_16(), + any_prf(), + any_p(), + any_s(), + any_d(), + any_c(), + r, + any_o(), + any_n(), + any_stable(), + ) # WHEN actual_r = border_router.r @@ -598,8 +741,18 @@ class TestBorderRouter(unittest.TestCase): # GIVEN o = any_o() - border_router = network_data.BorderRouter(any_border_router_16(), any_prf( - ), any_p(), any_s(), any_d(), any_c(), any_r(), o, any_n(), any_stable()) + border_router = network_data.BorderRouter( + any_border_router_16(), + any_prf(), + any_p(), + any_s(), + any_d(), + any_c(), + any_r(), + o, + any_n(), + any_stable(), + ) # WHEN actual_o = border_router.o @@ -611,8 +764,18 @@ class TestBorderRouter(unittest.TestCase): # GIVEN n = any_n() - border_router = network_data.BorderRouter(any_border_router_16(), any_prf( - ), any_p(), any_s(), any_d(), any_c(), any_r(), any_o(), n, any_stable()) + border_router = network_data.BorderRouter( + any_border_router_16(), + any_prf(), + any_p(), + any_s(), + any_d(), + any_c(), + any_r(), + any_o(), + n, + any_stable(), + ) # WHEN actual_n = border_router.n @@ -624,8 +787,18 @@ class TestBorderRouter(unittest.TestCase): # GIVEN stable = any_stable() - border_router = network_data.BorderRouter(any_border_router_16(), any_prf( - ), any_p(), any_s(), any_d(), any_c(), any_r(), any_o(), any_n(), stable) + border_router = network_data.BorderRouter( + any_border_router_16(), + any_prf(), + any_p(), + any_s(), + any_d(), + any_c(), + any_r(), + any_o(), + any_n(), + stable, + ) # WHEN actual_stable = border_router.stable @@ -635,8 +808,8 @@ class TestBorderRouter(unittest.TestCase): class TestBorderRouterFactory(unittest.TestCase): - - def test_should_create_BorderRouter_from_bytearray_when_parse_method_is_called(self): + def test_should_create_BorderRouter_from_bytearray_when_parse_method_is_called( + self): # GIVEN border_router_16 = any_border_router_16() prf = any_prf() @@ -652,7 +825,10 @@ class TestBorderRouterFactory(unittest.TestCase): factory = network_data.BorderRouterFactory() data = convert_border_router_to_bytearray( - network_data.BorderRouter(border_router_16, prf, p, s, d, c, r, o, n, stable)) + network_data.BorderRouter( + border_router_16, prf, p, s, d, c, r, o, n, stable + ) + ) message_info = common.MessageInfo() message_info.stable = stable @@ -661,8 +837,12 @@ class TestBorderRouterFactory(unittest.TestCase): actual_border_router = factory.parse(io.BytesIO(data), message_info) # THEN - self.assertTrue(isinstance(actual_border_router, network_data.BorderRouter)) - self.assertEqual(border_router_16, actual_border_router.border_router_16) + self.assertTrue( + isinstance(actual_border_router, network_data.BorderRouter) + ) + self.assertEqual( + border_router_16, actual_border_router.border_router_16 + ) self.assertEqual(prf, actual_border_router.prf) self.assertEqual(p, actual_border_router.p) self.assertEqual(s, actual_border_router.s) @@ -675,12 +855,13 @@ class TestBorderRouterFactory(unittest.TestCase): class TestLowpanId(unittest.TestCase): - def test_should_return_c_value_when_c_property_is_called(self): # GIVEN c = any_c() - lowpan_id = network_data.LowpanId(c, any_cid(), any_context_length(), any_stable()) + lowpan_id = network_data.LowpanId( + c, any_cid(), any_context_length(), any_stable() + ) # WHEN actual_c = lowpan_id.c @@ -692,7 +873,9 @@ class TestLowpanId(unittest.TestCase): # GIVEN cid = any_cid() - lowpan_id = network_data.LowpanId(any_c(), cid, any_context_length(), any_stable()) + lowpan_id = network_data.LowpanId( + any_c(), cid, any_context_length(), any_stable() + ) # WHEN actual_cid = lowpan_id.cid @@ -700,11 +883,14 @@ class TestLowpanId(unittest.TestCase): # THEN self.assertEqual(cid, actual_cid) - def test_should_return_context_length_value_when_context_length_property_is_called(self): + def test_should_return_context_length_value_when_context_length_property_is_called( + self): # GIVEN context_length = any_context_length() - lowpan_id = network_data.LowpanId(any_c(), any_cid(), context_length, any_stable()) + lowpan_id = network_data.LowpanId( + any_c(), any_cid(), context_length, any_stable() + ) # WHEN actual_context_length = lowpan_id.context_length @@ -716,7 +902,9 @@ class TestLowpanId(unittest.TestCase): # GIVEN stable = any_stable() - lowpan_id = network_data.LowpanId(any_c(), any_cid(), any_context_length(), stable) + lowpan_id = network_data.LowpanId( + any_c(), any_cid(), any_context_length(), stable + ) # WHEN actual_stable = lowpan_id.stable @@ -726,8 +914,9 @@ class TestLowpanId(unittest.TestCase): class TestLowpanIdFactory(unittest.TestCase): - - def test_should_create_LowpanId_from_bytearray_when_parse_method_is_called(self): + def test_should_create_LowpanId_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN c = any_c() cid = any_cid() @@ -736,7 +925,9 @@ class TestLowpanIdFactory(unittest.TestCase): factory = network_data.LowpanIdFactory() - data = convert_lowpan_id_to_bytearray(network_data.LowpanId(c, cid, context_length, stable)) + data = convert_lowpan_id_to_bytearray( + network_data.LowpanId(c, cid, context_length, stable) + ) message_info = common.MessageInfo() message_info.stable = stable @@ -752,13 +943,19 @@ class TestLowpanIdFactory(unittest.TestCase): class TestService(unittest.TestCase): - def test_should_return_t_value_when_t_property_is_called(self): # GIVEN t = any_t() - service = network_data.Service(t, any_id(), any_enterprise_number(), any_service_data_length(), - any_service_data(), any_service_sub_tlvs(), any_stable()) + service = network_data.Service( + t, + any_id(), + any_enterprise_number(), + any_service_data_length(), + any_service_data(), + any_service_sub_tlvs(), + any_stable(), + ) # WHEN actual_t = service.t @@ -770,8 +967,15 @@ class TestService(unittest.TestCase): # GIVEN _id = any_id() - service = network_data.Service(any_t(), _id, any_enterprise_number(), any_service_data_length(), - any_service_data(), any_service_sub_tlvs(), any_stable()) + service = network_data.Service( + any_t(), + _id, + any_enterprise_number(), + any_service_data_length(), + any_service_data(), + any_service_sub_tlvs(), + any_stable(), + ) # WHEN actual_id = service.id @@ -779,12 +983,20 @@ class TestService(unittest.TestCase): # THEN self.assertEqual(_id, actual_id) - def test_should_return_enterprise_number_value_when_enterprise_number_property_is_called(self): + def test_should_return_enterprise_number_value_when_enterprise_number_property_is_called( + self): # GIVEN enterprise_number = any_enterprise_number() - service = network_data.Service(any_t(), any_id(), enterprise_number, any_service_data_length(), - any_service_data(), any_service_sub_tlvs(), any_stable()) + service = network_data.Service( + any_t(), + any_id(), + enterprise_number, + any_service_data_length(), + any_service_data(), + any_service_sub_tlvs(), + any_stable(), + ) # WHEN actual_enterprise_number = service.enterprise_number @@ -792,12 +1004,20 @@ class TestService(unittest.TestCase): # THEN self.assertEqual(enterprise_number, actual_enterprise_number) - def test_should_return_service_data_length_value_when_service_data_length_property_is_called(self): + def test_should_return_service_data_length_value_when_service_data_length_property_is_called( + self): # GIVEN service_data_length = any_service_data_length() - service = network_data.Service(any_t(), any_id(), any_enterprise_number(), service_data_length, - any_service_data(), any_service_sub_tlvs(), any_stable()) + service = network_data.Service( + any_t(), + any_id(), + any_enterprise_number(), + service_data_length, + any_service_data(), + any_service_sub_tlvs(), + any_stable(), + ) # WHEN actual_service_data_length = service.service_data_length @@ -805,12 +1025,20 @@ class TestService(unittest.TestCase): # THEN self.assertEqual(service_data_length, actual_service_data_length) - def test_should_return_service_data_value_when_service_data_property_is_called(self): + def test_should_return_service_data_value_when_service_data_property_is_called( + self): # GIVEN service_data = any_service_data() - service = network_data.Service(any_t(), any_id(), any_enterprise_number(), any_service_data_length(), - service_data, any_service_sub_tlvs(), any_stable()) + service = network_data.Service( + any_t(), + any_id(), + any_enterprise_number(), + any_service_data_length(), + service_data, + any_service_sub_tlvs(), + any_stable(), + ) # WHEN actual_service_data = service.service_data @@ -818,12 +1046,21 @@ class TestService(unittest.TestCase): # THEN self.assertEqual(service_data, actual_service_data) - def test_should_return_sub_tlvs_value_when_sub_tlvs_property_is_called(self): + def test_should_return_sub_tlvs_value_when_sub_tlvs_property_is_called( + self + ): # GIVEN sub_tlvs = any_service_sub_tlvs() - service = network_data.Service(any_t(), any_id(), any_enterprise_number(), any_service_data_length(), - any_service_data(), sub_tlvs, any_stable()) + service = network_data.Service( + any_t(), + any_id(), + any_enterprise_number(), + any_service_data_length(), + any_service_data(), + sub_tlvs, + any_stable(), + ) # WHEN actual_sub_tlvs = service.sub_tlvs @@ -835,8 +1072,15 @@ class TestService(unittest.TestCase): # GIVEN stable = any_stable() - service = network_data.Service(any_t(), any_id(), any_enterprise_number(), any_service_data_length(), - any_service_data(), any_service_sub_tlvs(), stable) + service = network_data.Service( + any_t(), + any_id(), + any_enterprise_number(), + any_service_data_length(), + any_service_data(), + any_service_sub_tlvs(), + stable, + ) # WHEN actual_stable = service.stable @@ -846,12 +1090,15 @@ class TestService(unittest.TestCase): class TestServiceSubTlvsFactory(unittest.TestCase): - - def test_should_create_SubTlvs_from_bytearray_when_parse_method_is_called(self): + def test_should_create_SubTlvs_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN sub_tlvs = any_service_sub_tlvs() - factory = network_data.ServiceSubTlvsFactory(config.create_default_network_data_service_sub_tlvs_factories()) + factory = network_data.ServiceSubTlvsFactory( + config.create_default_network_data_service_sub_tlvs_factories() + ) data = convert_service_sub_tlvs_to_bytearray(sub_tlvs) @@ -864,8 +1111,9 @@ class TestServiceSubTlvsFactory(unittest.TestCase): class TestServiceFactory(unittest.TestCase): - - def test_should_create_Service_from_bytearray_when_parse_method_is_called(self): + def test_should_create_Service_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN t = any_t() _id = any_id() @@ -875,10 +1123,21 @@ class TestServiceFactory(unittest.TestCase): sub_tlvs = any_service_sub_tlvs() stable = any_stable() - factory = network_data.ServiceFactory(config.create_default_network_data_service_sub_tlvs_factory()) + factory = network_data.ServiceFactory( + config.create_default_network_data_service_sub_tlvs_factory() + ) - data = convert_service_to_bytearray(network_data.Service( - t, _id, enterprise_number, service_data_length, service_data, sub_tlvs, stable)) + data = convert_service_to_bytearray( + network_data.Service( + t, + _id, + enterprise_number, + service_data_length, + service_data, + sub_tlvs, + stable, + ) + ) message_info = common.MessageInfo() message_info.stable = stable @@ -891,18 +1150,23 @@ class TestServiceFactory(unittest.TestCase): self.assertEqual(t, actual_service.t) self.assertEqual(_id, actual_service.id) self.assertEqual(enterprise_number, actual_service.enterprise_number) - self.assertEqual(service_data_length, actual_service.service_data_length) + self.assertEqual( + service_data_length, actual_service.service_data_length + ) self.assertEqual(service_data, actual_service.service_data) self.assertEqual(sub_tlvs, actual_service.sub_tlvs) class TestServer(unittest.TestCase): - - def test_should_return_server_16_value_when_server_16_property_is_called(self): + def test_should_return_server_16_value_when_server_16_property_is_called( + self + ): # GIVEN server_16 = any_server_16() - server = network_data.Server(server_16, any_server_data(), any_stable()) + server = network_data.Server( + server_16, any_server_data(), any_stable() + ) # WHEN actual_server_16 = server.server_16 @@ -910,11 +1174,14 @@ class TestServer(unittest.TestCase): # THEN self.assertEqual(server_16, actual_server_16) - def test_should_return_server_data_value_when_server_data_property_is_called(self): + def test_should_return_server_data_value_when_server_data_property_is_called( + self): # GIVEN server_data = any_server_data() - server = network_data.Server(any_server_16(), server_data, any_stable()) + server = network_data.Server( + any_server_16(), server_data, any_stable() + ) # WHEN actual_server_data = server.server_data @@ -926,7 +1193,9 @@ class TestServer(unittest.TestCase): # GIVEN stable = any_stable() - server = network_data.Server(any_server_16(), any_server_data(), stable) + server = network_data.Server( + any_server_16(), any_server_data(), stable + ) # WHEN actual_stable = server.stable @@ -936,8 +1205,9 @@ class TestServer(unittest.TestCase): class TestServerFactory(unittest.TestCase): - - def test_should_create_Server_from_bytearray_when_parse_method_is_called(self): + def test_should_create_Server_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN server_16 = any_server_16() server_data = any_server_data() @@ -945,7 +1215,9 @@ class TestServerFactory(unittest.TestCase): factory = network_data.ServerFactory() - data = convert_server_to_bytearray(network_data.Server(server_16, server_data, stable)) + data = convert_server_to_bytearray( + network_data.Server(server_16, server_data, stable) + ) message_info = common.MessageInfo() message_info.stable = stable diff --git a/tests/scripts/thread-cert/test_network_layer.py b/tests/scripts/thread-cert/test_network_layer.py index 7b5a0498e..f7cbfa327 100755 --- a/tests/scripts/thread-cert/test_network_layer.py +++ b/tests/scripts/thread-cert/test_network_layer.py @@ -92,7 +92,6 @@ def any_tlvs_data(count=None): class TestTargetEid(unittest.TestCase): - def test_should_return_eid_value_when_eid_property_is_called(self): # GIVEN eid = any_eid() @@ -105,7 +104,8 @@ class TestTargetEid(unittest.TestCase): # THEN self.assertEqual(eid, actual_eid) - def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values(self): + def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values( + self): # GIVEN eid = any_eid() @@ -116,8 +116,8 @@ class TestTargetEid(unittest.TestCase): class TestTargetEidFactory(unittest.TestCase): - - def test_should_create_TargetEid_from_bytearray_when_parse_method_is_called(self): + def test_should_create_TargetEid_from_bytearray_when_parse_method_is_called( + self): # GIVEN eid = any_eid() @@ -132,8 +132,8 @@ class TestTargetEidFactory(unittest.TestCase): class TestMacExtendedAddress(unittest.TestCase): - - def test_should_return_mac_address_value_when_mac_address_property_is_called(self): + def test_should_return_mac_address_value_when_mac_address_property_is_called( + self): # GIVEN mac_address = any_mac_extended_address() @@ -145,34 +145,40 @@ class TestMacExtendedAddress(unittest.TestCase): # THEN self.assertEqual(mac_address, actual_mac_address) - def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values(self): + def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values( + self): # GIVEN mac_address = any_mac_extended_address() mac_extended_address = network_layer.MacExtendedAddress(mac_address) # THEN - self.assertEqual(mac_extended_address, network_layer.MacExtendedAddress(mac_address)) + self.assertEqual( + mac_extended_address, network_layer.MacExtendedAddress(mac_address) + ) class TestMacExtendedAddressFactory(unittest.TestCase): - - def test_should_create_MacExtendedAddress_from_bytearray_when_parse_method_is_called(self): + def test_should_create_MacExtendedAddress_from_bytearray_when_parse_method_is_called( + self): # GIVEN mac_address = any_mac_extended_address() factory = network_layer.MacExtendedAddressFactory() # WHEN - mac_extended_address = factory.parse(io.BytesIO(mac_address), common.MessageInfo()) + mac_extended_address = factory.parse( + io.BytesIO(mac_address), common.MessageInfo() + ) # THEN - self.assertTrue(isinstance(mac_extended_address, network_layer.MacExtendedAddress)) + self.assertTrue( + isinstance(mac_extended_address, network_layer.MacExtendedAddress) + ) self.assertEqual(mac_address, mac_extended_address.mac_address) class TestRloc16(unittest.TestCase): - def test_should_return_rloc16_value_when_rloc16_property_is_called(self): # GIVEN rloc16 = any_rloc16() @@ -185,7 +191,8 @@ class TestRloc16(unittest.TestCase): # THEN self.assertEqual(rloc16, actual_rloc16) - def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values(self): + def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values( + self): # GIVEN rloc16 = any_rloc16() @@ -196,8 +203,9 @@ class TestRloc16(unittest.TestCase): class TestRloc16Factory(unittest.TestCase): - - def test_should_create_Rloc16_from_bytearray_when_parse_method_is_called(self): + def test_should_create_Rloc16_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN rloc16 = any_rloc16() @@ -214,7 +222,6 @@ class TestRloc16Factory(unittest.TestCase): class TestMlEid(unittest.TestCase): - def test_should_return_ml_eid_value_when_ml_eid_property_is_called(self): # GIVEN ml_eid = any_ml_eid() @@ -227,7 +234,8 @@ class TestMlEid(unittest.TestCase): # THEN self.assertEqual(ml_eid, actual_ml_eid) - def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values(self): + def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values( + self): # GIVEN ml_eid = any_ml_eid() @@ -238,8 +246,9 @@ class TestMlEid(unittest.TestCase): class TestMlEidFactory(unittest.TestCase): - - def test_should_create_MlEid_from_bytearray_when_parse_method_is_called(self): + def test_should_create_MlEid_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN ml_eid = any_ml_eid() @@ -254,7 +263,6 @@ class TestMlEidFactory(unittest.TestCase): class TestStatus(unittest.TestCase): - def test_should_return_status_value_when_status_property_is_called(self): # GIVEN status = any_status() @@ -267,7 +275,8 @@ class TestStatus(unittest.TestCase): # THEN self.assertEqual(status, actual_status) - def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values(self): + def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values( + self): # GIVEN status = any_status() @@ -278,8 +287,9 @@ class TestStatus(unittest.TestCase): class TestStatusFactory(unittest.TestCase): - - def test_should_create_Status_from_bytearray_when_parse_method_is_called(self): + def test_should_create_Status_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN status = any_status() @@ -296,12 +306,13 @@ class TestStatusFactory(unittest.TestCase): class TestTimeSinceLastTransaction(unittest.TestCase): - def test_should_return_seconds_value_when_seconds_property_is_called(self): # GIVEN seconds = any_seconds() - time_since_last_transaction = network_layer.TimeSinceLastTransaction(seconds) + time_since_last_transaction = network_layer.TimeSinceLastTransaction( + seconds + ) # WHEN actual_seconds = time_since_last_transaction.seconds @@ -309,19 +320,25 @@ class TestTimeSinceLastTransaction(unittest.TestCase): # THEN self.assertEqual(seconds, actual_seconds) - def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values(self): + def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values( + self): # GIVEN seconds = any_seconds() - time_since_last_transaction = network_layer.TimeSinceLastTransaction(seconds) + time_since_last_transaction = network_layer.TimeSinceLastTransaction( + seconds + ) # THEN - self.assertEqual(time_since_last_transaction, network_layer.TimeSinceLastTransaction(seconds)) + self.assertEqual( + time_since_last_transaction, + network_layer.TimeSinceLastTransaction(seconds), + ) class TestTimeSinceLastTransactionFactory(unittest.TestCase): - - def test_should_create_TimeSinceLastTransaction_from_bytearray_when_parse_method_is_called(self): + def test_should_create_TimeSinceLastTransaction_from_bytearray_when_parse_method_is_called( + self): # GIVEN seconds = any_seconds() @@ -330,20 +347,29 @@ class TestTimeSinceLastTransactionFactory(unittest.TestCase): data = bytearray(struct.pack(">L", seconds)) # WHEN - time_since_last_transaction = factory.parse(io.BytesIO(data), common.MessageInfo()) + time_since_last_transaction = factory.parse( + io.BytesIO(data), common.MessageInfo() + ) # THEN - self.assertTrue(isinstance(time_since_last_transaction, network_layer.TimeSinceLastTransaction)) + self.assertTrue( + isinstance( + time_since_last_transaction, + network_layer.TimeSinceLastTransaction, + ) + ) self.assertEqual(seconds, time_since_last_transaction.seconds) class TestRouterMask(unittest.TestCase): - - def test_should_return_id_sequence_value_when_id_sequence_property_is_called(self): + def test_should_return_id_sequence_value_when_id_sequence_property_is_called( + self): # GIVEN id_sequence = any_id_sequence() - router_mask = network_layer.RouterMask(id_sequence, any_router_id_mask()) + router_mask = network_layer.RouterMask( + id_sequence, any_router_id_mask() + ) # WHEN actual_id_sequence = router_mask.id_sequence @@ -351,11 +377,14 @@ class TestRouterMask(unittest.TestCase): # THEN self.assertEqual(id_sequence, actual_id_sequence) - def test_should_return_router_id_mask_value_when_router_id_mask_property_is_called(self): + def test_should_return_router_id_mask_value_when_router_id_mask_property_is_called( + self): # GIVEN router_id_mask = any_router_id_mask() - router_mask = network_layer.RouterMask(any_id_sequence(), router_id_mask) + router_mask = network_layer.RouterMask( + any_id_sequence(), router_id_mask + ) # WHEN actual_router_id_mask = router_mask.router_id_mask @@ -363,7 +392,8 @@ class TestRouterMask(unittest.TestCase): # THEN self.assertEqual(router_id_mask, actual_router_id_mask) - def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values(self): + def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values( + self): # GIVEN id_sequence = any_id_sequence() router_id_mask = any_router_id_mask() @@ -371,12 +401,14 @@ class TestRouterMask(unittest.TestCase): router_mask = network_layer.RouterMask(id_sequence, router_id_mask) # THEN - self.assertEqual(router_mask, network_layer.RouterMask(id_sequence, router_id_mask)) + self.assertEqual( + router_mask, network_layer.RouterMask(id_sequence, router_id_mask) + ) class TestRouterMaskFactory(unittest.TestCase): - - def test_should_create_RouterMask_from_bytearray_when_parse_method_is_called(self): + def test_should_create_RouterMask_from_bytearray_when_parse_method_is_called( + self): # GIVEN id_sequence = any_id_sequence() router_id_mask = any_router_id_mask() @@ -395,7 +427,6 @@ class TestRouterMaskFactory(unittest.TestCase): class TestNdOption(unittest.TestCase): - def test_should_return_options_value_when_options_property_is_called(self): # GIVEN options = any_options() @@ -408,7 +439,8 @@ class TestNdOption(unittest.TestCase): # THEN self.assertEqual(options, actual_options) - def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values(self): + def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values( + self): # GIVEN options = any_options() @@ -419,8 +451,9 @@ class TestNdOption(unittest.TestCase): class TestNdOptionFactory(unittest.TestCase): - - def test_should_create_NdOption_from_bytearray_when_parse_method_is_called(self): + def test_should_create_NdOption_from_bytearray_when_parse_method_is_called( + self + ): # GIVEN options = any_options() @@ -437,7 +470,6 @@ class TestNdOptionFactory(unittest.TestCase): class TestThreadNetworkData(unittest.TestCase): - def test_should_return_options_value_when_options_property_is_called(self): # GIVEN tlvs = any_tlvs_data() @@ -450,34 +482,42 @@ class TestThreadNetworkData(unittest.TestCase): # THEN self.assertEqual(tlvs, actual_tlvs) - def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values(self): + def test_should_return_True_when_try_to_equal_two_the_same_type_objects_with_the_same_values( + self): # GIVEN tlvs = any_tlvs_data() thread_network_data = network_layer.ThreadNetworkData(tlvs) # THEN - self.assertEqual(thread_network_data, network_layer.ThreadNetworkData(tlvs)) + self.assertEqual( + thread_network_data, network_layer.ThreadNetworkData(tlvs) + ) class TestThreadNetworkDataFactory(unittest.TestCase): - - def test_should_create_ThreadNetworkData_from_bytearray_when_parse_method_is_called(self): + def test_should_create_ThreadNetworkData_from_bytearray_when_parse_method_is_called( + self): # GIVEN tlvs = any_tlvs_data() class DummyNetworkDataTlvsFactory: - def parse(self, data, message_info): return bytearray(data.read()) - factory = network_layer.ThreadNetworkDataFactory(DummyNetworkDataTlvsFactory()) + factory = network_layer.ThreadNetworkDataFactory( + DummyNetworkDataTlvsFactory() + ) # WHEN - thread_network_data = factory.parse(io.BytesIO(tlvs), common.MessageInfo()) + thread_network_data = factory.parse( + io.BytesIO(tlvs), common.MessageInfo() + ) # THEN - self.assertTrue(isinstance(thread_network_data, network_layer.ThreadNetworkData)) + self.assertTrue( + isinstance(thread_network_data, network_layer.ThreadNetworkData) + ) self.assertEqual(tlvs, thread_network_data.tlvs) diff --git a/tests/scripts/thread-cert/test_service.py b/tests/scripts/thread-cert/test_service.py index e35a387fe..e5876237f 100755 --- a/tests/scripts/thread-cert/test_service.py +++ b/tests/scripts/thread-cert/test_service.py @@ -28,7 +28,6 @@ # import re -import time import unittest import node @@ -48,12 +47,13 @@ SRV_1_ENT_NUMBER = '234' SRV_1_SERVICE_DATA = 'baz' SRV_1_SERVER_DATA = 'qux' + class Test_Service(unittest.TestCase): def setUp(self): self.simulator = config.create_default_simulator() self.nodes = {} - for i in range(1,4): + for i in range(1, 4): self.nodes[i] = node.Node(i, simulator=self.simulator) self.nodes[LEADER].set_panid(0xface) @@ -83,27 +83,31 @@ class Test_Service(unittest.TestCase): self.nodes[ROUTER2].set_router_selection_jitter(1) def tearDown(self): - for node in list(self.nodes.values()): - node.stop() - node.destroy() + for n in list(self.nodes.values()): + n.stop() + n.destroy() self.simulator.stop() def hasAloc(self, node_id, service_id): - for addr in self.nodes[node_id].get_ip6_address(config.ADDRESS_TYPE.ALOC): + for addr in self.nodes[node_id].get_ip6_address( + config.ADDRESS_TYPE.ALOC + ): m = re.match('.*:fc(..)$', addr, re.I) if m is not None: - if m.group(1) == str(service_id + 10): # for service_id=3 look for '...:fc13' + if m.group(1) == str( + service_id + 10 + ): # for service_id=3 look for '...:fc13' return True return False def pingFromAll(self, addr): - for node in list(self.nodes.values()): - self.assertTrue(node.ping(addr)) + for n in list(self.nodes.values()): + self.assertTrue(n.ping(addr)) def failToPingFromAll(self, addr): - for node in list(self.nodes.values()): - self.assertFalse(node.ping(addr, timeout=3)) + for n in list(self.nodes.values()): + self.assertFalse(n.ping(addr, timeout=3)) def test(self): self.nodes[LEADER].start() @@ -123,7 +127,9 @@ class Test_Service(unittest.TestCase): self.assertEqual(self.hasAloc(ROUTER2, SRV_0_ID), False) self.assertEqual(self.hasAloc(ROUTER2, SRV_1_ID), False) - self.nodes[ROUTER1].add_service(SRV_0_ENT_NUMBER, SRV_0_SERVICE_DATA, SRV_0_SERVER_DATA) + self.nodes[ROUTER1].add_service( + SRV_0_ENT_NUMBER, SRV_0_SERVICE_DATA, SRV_0_SERVER_DATA + ) self.nodes[ROUTER1].register_netdata() self.simulator.go(2) @@ -134,10 +140,14 @@ class Test_Service(unittest.TestCase): self.assertEqual(self.hasAloc(ROUTER2, SRV_0_ID), False) self.assertEqual(self.hasAloc(ROUTER2, SRV_1_ID), False) - aloc0 = self.nodes[ROUTER1].get_ip6_address(config.ADDRESS_TYPE.ALOC)[0] + aloc0 = self.nodes[ROUTER1].get_ip6_address(config.ADDRESS_TYPE.ALOC)[ + 0 + ] self.pingFromAll(aloc0) - self.nodes[LEADER].add_service(SRV_0_ENT_NUMBER, SRV_0_SERVICE_DATA, SRV_0_SERVER_DATA) + self.nodes[LEADER].add_service( + SRV_0_ENT_NUMBER, SRV_0_SERVICE_DATA, SRV_0_SERVER_DATA + ) self.nodes[LEADER].register_netdata() self.simulator.go(2) @@ -150,7 +160,9 @@ class Test_Service(unittest.TestCase): self.pingFromAll(aloc0) - self.nodes[ROUTER2].add_service(SRV_1_ENT_NUMBER, SRV_1_SERVICE_DATA, SRV_1_SERVER_DATA) + self.nodes[ROUTER2].add_service( + SRV_1_ENT_NUMBER, SRV_1_SERVICE_DATA, SRV_1_SERVER_DATA + ) self.nodes[ROUTER2].register_netdata() self.simulator.go(2) @@ -161,11 +173,15 @@ class Test_Service(unittest.TestCase): self.assertEqual(self.hasAloc(ROUTER2, SRV_0_ID), False) self.assertEqual(self.hasAloc(ROUTER2, SRV_1_ID), True) - aloc1 = self.nodes[ROUTER2].get_ip6_address(config.ADDRESS_TYPE.ALOC)[0] + aloc1 = self.nodes[ROUTER2].get_ip6_address(config.ADDRESS_TYPE.ALOC)[ + 0 + ] self.pingFromAll(aloc0) self.pingFromAll(aloc1) - self.nodes[ROUTER1].remove_service(SRV_0_ENT_NUMBER, SRV_0_SERVICE_DATA) + self.nodes[ROUTER1].remove_service( + SRV_0_ENT_NUMBER, SRV_0_SERVICE_DATA + ) self.nodes[ROUTER1].register_netdata() self.simulator.go(2) @@ -193,7 +209,9 @@ class Test_Service(unittest.TestCase): self.failToPingFromAll(aloc0) self.pingFromAll(aloc1) - self.nodes[ROUTER2].remove_service(SRV_1_ENT_NUMBER, SRV_1_SERVICE_DATA) + self.nodes[ROUTER2].remove_service( + SRV_1_ENT_NUMBER, SRV_1_SERVICE_DATA + ) self.nodes[ROUTER2].register_netdata() self.simulator.go(2) @@ -207,5 +225,6 @@ class Test_Service(unittest.TestCase): self.failToPingFromAll(aloc0) self.failToPingFromAll(aloc1) + if __name__ == '__main__': unittest.main() diff --git a/tests/scripts/thread-cert/tlvs_parsing.py b/tests/scripts/thread-cert/tlvs_parsing.py index cfe46cb10..06af83d3c 100644 --- a/tests/scripts/thread-cert/tlvs_parsing.py +++ b/tests/scripts/thread-cert/tlvs_parsing.py @@ -28,8 +28,8 @@ import io -class SubTlvsFactory(object): +class SubTlvsFactory(object): def __init__(self, sub_tlvs_factories): self._sub_tlvs_factories = sub_tlvs_factories @@ -37,7 +37,9 @@ class SubTlvsFactory(object): try: return self._sub_tlvs_factories[_type] except KeyError: - raise RuntimeError("Could not find factory. Factory type = {}.".format(_type)) + raise RuntimeError( + "Could not find factory. Factory type = {}.".format(_type) + ) def parse(self, data, message_info): sub_tlvs = [] @@ -56,4 +58,3 @@ class SubTlvsFactory(object): sub_tlvs.append(tlv) return sub_tlvs - diff --git a/tests/toranj/test-001-get-set.py b/tests/toranj/test-001-get-set.py index 2c9a6e1f4..66a7401b7 100644 --- a/tests/toranj/test-001-get-set.py +++ b/tests/toranj/test-001-get-set.py @@ -28,31 +28,31 @@ from wpan import verify import wpan -import time -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: simple wpanctl get and set commands test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances node = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation verify(node.get(wpan.WPAN_STATE) == wpan.STATE_OFFLINE) -# set some of properties and check and verify that the value is indeed changed... +# set some of properties and check and verify that the value is indeed +# changed... node.set(wpan.WPAN_NAME, 'test-network') verify(node.get(wpan.WPAN_NAME) == '"test-network"') @@ -171,12 +171,10 @@ all_gettable_props = [ wpan.WPAN_THREAD_LEADER_WEIGHT, wpan.WPAN_THREAD_LEADER_LOCAL_WEIGHT, wpan.WPAN_THREAD_LEADER_NETWORK_DATA, - wpan.WPAN_THREAD_STABLE_LEADER_NETWORK_DATA + wpan.WPAN_THREAD_STABLE_LEADER_NETWORK_DATA, ] -all_posix_app_gettable_props = [ - wpan.WPAN_RCP_VERSION -] +all_posix_app_gettable_props = [wpan.WPAN_RCP_VERSION] node.form('get-set') @@ -187,9 +185,9 @@ if node.using_posix_app_with_rcp: for prop in all_posix_app_gettable_props: node.get(prop) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-002-form.py b/tests/toranj/test-002-form.py index e498b0b38..dbb561cdd 100644 --- a/tests/toranj/test-002-form.py +++ b/tests/toranj/test-002-form.py @@ -28,16 +28,15 @@ from wpan import verify import wpan -import time -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: forming a Thread network test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -45,12 +44,12 @@ wpan.Node.set_time_speedup_factor(speedup) node = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # default values after reset @@ -111,8 +110,15 @@ verify(node.get(wpan.WPAN_STATE) == wpan.STATE_OFFLINE) # Form a network with all parameters given as part of `form` command itself -node.form('vahman', channel_mask='15,20-24', panid='0x1977', xpanid='1020031510006016', - key='0123456789abcdeffecdba9876543210', key_index='1', mesh_local_prefix='fd00:cafe::') +node.form( + 'vahman', + channel_mask='15,20-24', + panid='0x1977', + xpanid='1020031510006016', + key='0123456789abcdeffecdba9876543210', + key_index='1', + mesh_local_prefix='fd00:cafe::', +) verify(node.get(wpan.WPAN_STATE) == wpan.STATE_ASSOCIATED) verify(node.get(wpan.WPAN_NAME) == '"vahman"') @@ -124,10 +130,9 @@ verify(node.get(wpan.WPAN_PANID) == '0x1977') verify(node.get(wpan.WPAN_XPANID) == '0x1020031510006016') verify(node.get(wpan.WPAN_IP6_MESH_LOCAL_PREFIX) == '"fd00:cafe::/64"') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) - +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-003-join.py b/tests/toranj/test-003-join.py index 41629851f..c39dcefad 100644 --- a/tests/toranj/test-003-join.py +++ b/tests/toranj/test-003-join.py @@ -28,16 +28,15 @@ from wpan import verify import wpan -import time -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: joining (as router, end-device, sleepy) - two node network test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -46,12 +45,12 @@ wpan.Node.set_time_speedup_factor(speedup) node1 = wpan.Node() node2 = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Form a network on node1 @@ -99,10 +98,9 @@ node2.set(wpan.WPAN_KEY, node1.get(wpan.WPAN_KEY)[1:-1], binary_data=True) verify(node2.get(wpan.WPAN_KEY) == node1.get(wpan.WPAN_KEY)) verify(node2.get(wpan.WPAN_STATE) == wpan.STATE_ASSOCIATED) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) - +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-004-scan.py b/tests/toranj/test-004-scan.py index 7141dfac5..5012b3df3 100644 --- a/tests/toranj/test-004-scan.py +++ b/tests/toranj/test-004-scan.py @@ -28,16 +28,15 @@ from wpan import verify import wpan -import time -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test desciption: Active scan and permit-join test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances NUM_NODES = 5 @@ -48,18 +47,18 @@ for i in range(NUM_NODES): scanner = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology for node in nodes: node.form(node.interface_name) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Perform active scan and check that all nodes are seen in the scan result. @@ -95,9 +94,9 @@ channel = nodes[0].get(wpan.WPAN_CHANNEL) scan_result = wpan.parse_scan_result(scanner.active_scan(channel=channel)) verify(nodes[0].is_in_scan_result(scan_result)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-005-discover-scan.py b/tests/toranj/test-005-discover-scan.py index 35aed7785..33400e0d6 100644 --- a/tests/toranj/test-005-discover-scan.py +++ b/tests/toranj/test-005-discover-scan.py @@ -28,16 +28,15 @@ from wpan import verify import wpan -import time -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: discover scan test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances NUM_NODES = 5 @@ -48,18 +47,18 @@ for i in range(NUM_NODES): scanner = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology for node in nodes: node.form(node.interface_name) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Perform active scan and check that all nodes are seen in the scan result. @@ -78,10 +77,9 @@ for node in nodes[1:]: # TODO: add tests for the joiner only and filtering -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) - +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-006-traffic-router-end-device.py b/tests/toranj/test-006-traffic-router-end-device.py index 8204352ae..c3398d453 100644 --- a/tests/toranj/test-006-traffic-router-end-device.py +++ b/tests/toranj/test-006-traffic-router-end-device.py @@ -26,29 +26,29 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- -# Test description: Traffic between router and end-device (link-local and mesh-local IPv6 addresses) +# ----------------------------------------------------------------------------------------------------------------------- +# Test description: Traffic between router and end-device (link-local and +# mesh-local IPv6 addresses) test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances node1 = wpan.Node() node2 = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # Two-node network (node1 leader/router, node2 end-device) @@ -61,7 +61,7 @@ verify(node2.get(wpan.WPAN_NAME) == node1.get(wpan.WPAN_NAME)) verify(node2.get(wpan.WPAN_PANID) == node1.get(wpan.WPAN_PANID)) verify(node2.get(wpan.WPAN_XPANID) == node1.get(wpan.WPAN_XPANID)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Get the link local addresses @@ -77,7 +77,7 @@ MSG_LENS = [40, 100, 400, 800, 1000] PORT = 1234 # all src and dst configuration (link-local and mesh-local) -for src,dst in [ (ll1, ll2), (ll1, ml2), (ml1, ll2), (ml1, ml2) ]: +for src, dst in [(ll1, ll2), (ll1, ml2), (ml1, ll2), (ml1, ml2)]: for msg_length in MSG_LENS: sender = node1.prepare_tx(src, dst, msg_length, NUM_MSGS) @@ -92,7 +92,9 @@ for src,dst in [ (ll1, ll2), (ll1, ml2), (ml1, ll2), (ml1, ml2) ]: s1 = node1.prepare_tx((src, PORT), (dst, PORT), 'Hi there!', NUM_MSGS) r1 = node2.prepare_rx(s1) - s2 = node2.prepare_tx((dst, PORT), (src, PORT), 'Hello back to you!', NUM_MSGS) + s2 = node2.prepare_tx( + (dst, PORT), (src, PORT), 'Hello back to you!', NUM_MSGS + ) r2 = node1.prepare_rx(s2) wpan.Node.perform_async_tx_rx() @@ -100,9 +102,9 @@ for src,dst in [ (ll1, ll2), (ll1, ml2), (ml1, ll2), (ml1, ml2) ]: verify(s1.was_successful and r1.was_successful) verify(s2.was_successful and r2.was_successful) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-007-traffic-router-sleepy.py b/tests/toranj/test-007-traffic-router-sleepy.py index 7c4d5a824..b0842b865 100644 --- a/tests/toranj/test-007-traffic-router-sleepy.py +++ b/tests/toranj/test-007-traffic-router-sleepy.py @@ -26,29 +26,29 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- -# Test description: Traffic between router and sleepy-end-device (link-local and mesh-local IPv6 addresses) +# ----------------------------------------------------------------------------------------------------------------------- +# Test description: Traffic between router and sleepy-end-device +# (link-local and mesh-local IPv6 addresses) test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances node1 = wpan.Node() node2 = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # Two-node network (node1 leader/router, node2 sleepy-end-device) @@ -61,7 +61,7 @@ verify(node2.get(wpan.WPAN_NAME) == node1.get(wpan.WPAN_NAME)) verify(node2.get(wpan.WPAN_PANID) == node1.get(wpan.WPAN_PANID)) verify(node2.get(wpan.WPAN_XPANID) == node1.get(wpan.WPAN_XPANID)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Get the link local addresses @@ -82,7 +82,7 @@ for poll_interval in [10, 100, 300]: verify(node2.get(wpan.WPAN_POLL_INTERVAL) == str(poll_interval)) # all src and dst configuration (link-local and mesh-local) - for src,dst in [ (ll1, ll2), (ll1, ml2), (ml1, ll2), (ml1, ml2) ]: + for src, dst in [(ll1, ll2), (ll1, ml2), (ml1, ll2), (ml1, ml2)]: for msg_length in MSG_LENS: sender = node1.prepare_tx(src, dst, msg_length, NUM_MSGS) @@ -97,7 +97,9 @@ for poll_interval in [10, 100, 300]: s1 = node1.prepare_tx((src, PORT), (dst, PORT), 'Hi there!', NUM_MSGS) r1 = node2.prepare_rx(s1) - s2 = node2.prepare_tx((dst, PORT), (src, PORT), 'Hello back to you!', NUM_MSGS) + s2 = node2.prepare_tx( + (dst, PORT), (src, PORT), 'Hello back to you!', NUM_MSGS + ) r2 = node1.prepare_rx(s2) wpan.Node.perform_async_tx_rx() @@ -105,9 +107,9 @@ for poll_interval in [10, 100, 300]: verify(s1.was_successful and r1.was_successful) verify(s2.was_successful and r2.was_successful) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-008-permit-join.py b/tests/toranj/test-008-permit-join.py index c3339eb0d..3a66f74f5 100644 --- a/tests/toranj/test-008-permit-join.py +++ b/tests/toranj/test-008-permit-join.py @@ -30,29 +30,29 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: check wpantund `permit-join` functionality and timeout test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances node = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology node.form("permit-join-test") -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation verify(node.get(wpan.WPAN_NETWORK_ALLOW_JOIN) == 'false') @@ -75,9 +75,9 @@ verify(node.get(wpan.WPAN_NETWORK_ALLOW_JOIN) == 'true') time.sleep(1.5) verify(node.get(wpan.WPAN_NETWORK_ALLOW_JOIN) == 'false') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-009-insecure-traffic-join.py b/tests/toranj/test-009-insecure-traffic-join.py index ac7b606e0..02c7e260c 100644 --- a/tests/toranj/test-009-insecure-traffic-join.py +++ b/tests/toranj/test-009-insecure-traffic-join.py @@ -26,34 +26,33 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Check insecure data transmission during joining. test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances node1 = wpan.Node() node2 = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology node1.form("insec-join-test") -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation insecure_port = 1234 @@ -74,7 +73,8 @@ verify(node2.get(wpan.WPAN_XPANID) == node1.get(wpan.WPAN_XPANID)) ll1 = node1.get(wpan.WPAN_IP6_LINK_LOCAL_ADDRESS)[1:-1] ll2 = node2.get(wpan.WPAN_IP6_LINK_LOCAL_ADDRESS)[1:-1] -# Send insecure traffic from node2 to node1 using link-local IP address for src/dst and insecure port number +# Send insecure traffic from node2 to node1 using link-local IP address +# for src/dst and insecure port number sender = node2.prepare_tx(ll2, (ll1, insecure_port), "Hi (insecure)", NUM_MSGS) recver = node1.prepare_rx(sender) @@ -82,27 +82,33 @@ wpan.Node.perform_async_tx_rx() verify(sender.was_successful) verify(recver.was_successful) -# Get the random src port number used by node1 and ensure node2 allows insecure rx traffic on that port +# Get the random src port number used by node1 and ensure node2 allows +# insecure rx traffic on that port rx_port = recver.all_rx_msg[0][1][1] node2.permit_join(duration_sec='100', port=str(rx_port)) # Send insecure reply from node1 to node2 -sender2 = node1.prepare_tx((ll1, insecure_port), (ll2, rx_port), "Hi back! (insecure)", NUM_MSGS) +sender2 = node1.prepare_tx( + (ll1, insecure_port), (ll2, rx_port), "Hi back! (insecure)", NUM_MSGS +) recver2 = node2.prepare_rx(sender2) wpan.Node.perform_async_tx_rx() verify(sender2.was_successful) verify(recver2.was_successful) -# Now node2 fully joins the network (set the network key), check all secure traffic exchange between the nodes +# Now node2 fully joins the network (set the network key), check all +# secure traffic exchange between the nodes node2.set(wpan.WPAN_KEY, node1.get(wpan.WPAN_KEY)[1:-1], binary_data=True) verify(node2.is_associated()) node1.permit_join('0') -sender = node2.prepare_tx(ll2, (ll1, insecure_port), "Hi (now secure)", NUM_MSGS) +sender = node2.prepare_tx( + ll2, (ll1, insecure_port), "Hi (now secure)", NUM_MSGS +) recver = node1.prepare_rx(sender) wpan.Node.perform_async_tx_rx() verify(sender.was_successful) @@ -110,15 +116,17 @@ verify(recver.was_successful) node2.permit_join('0') -sender2 = node1.prepare_tx((ll1, insecure_port), (ll2, rx_port), "Hi back! (secure now)", NUM_MSGS) +sender2 = node1.prepare_tx( + (ll1, insecure_port), (ll2, rx_port), "Hi back! (secure now)", NUM_MSGS +) recver2 = node2.prepare_rx(sender2) wpan.Node.perform_async_tx_rx() verify(sender2.was_successful) verify(recver2.was_successful) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-010-on-mesh-prefix-config-gateway.py b/tests/toranj/test-010-on-mesh-prefix-config-gateway.py index 46fb184dd..eae1ac44e 100644 --- a/tests/toranj/test-010-on-mesh-prefix-config-gateway.py +++ b/tests/toranj/test-010-on-mesh-prefix-config-gateway.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: # # Adding on-mesh prefix and `config-gateway` command @@ -42,12 +41,13 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Utility functions + def verify_address(node_list, prefix): """ This function verifies that all nodes in the `node_list` contain an IPv6 address with the given `prefix`. @@ -56,13 +56,27 @@ def verify_address(node_list, prefix): all_addrs = wpan.parse_list(node.get(wpan.WPAN_IP6_ALL_ADDRESSES)) verify(any([addr.startswith(prefix[:-1]) for addr in all_addrs])) -def verify_prefix(node_list, prefix, prefix_len=64, stable=True, priority='med', on_mesh=False, slaac=False, dhcp=False, - configure=False, default_route=False, preferred=True): + +def verify_prefix( + node_list, + prefix, + prefix_len=64, + stable=True, + priority='med', + on_mesh=False, + slaac=False, + dhcp=False, + configure=False, + default_route=False, + preferred=True, +): """ This function verifies that the `prefix` is present on all the nodes in the `node_list`. """ for node in node_list: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: if p.prefix == prefix: verify(int(p.prefix_len) == prefix_len) @@ -76,9 +90,12 @@ def verify_prefix(node_list, prefix, prefix_len=64, stable=True, priority='med', verify(p.priority == priority) break else: - raise wpan.VerifyError('Did not find prefix {} on node {}'.format(prefix, node)) + raise wpan.VerifyError( + 'Did not find prefix {} on node {}'.format(prefix, node) + ) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -91,12 +108,12 @@ sc2 = wpan.Node() all_nodes = [r1, r2, sc1, sc2] -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology r1.whitelist_node(r2) @@ -113,7 +130,7 @@ sc2.join_node(r2, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE) sc1.set(wpan.WPAN_POLL_INTERVAL, '200') sc2.set(wpan.WPAN_POLL_INTERVAL, '200') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation WAIT_TIME = 5 @@ -126,71 +143,143 @@ prefix4 = 'fd00:abcd::' # Add on-mesh prefix1 on router r1 r1.config_gateway(prefix1) -# Verify that the prefix1 and its corresponding address are present on all nodes +# Verify that the prefix1 and its corresponding address are present on all +# nodes + + def check_prefix1_on_all_nodes(): verify_prefix(all_nodes, prefix1, stable=True, on_mesh=True, slaac=True) verify_address(all_nodes, prefix1) + wpan.verify_within(check_prefix1_on_all_nodes, WAIT_TIME) -# Now add prefix2 with priority `high` on router r2 and check all nodes for the new prefix/address +# Now add prefix2 with priority `high` on router r2 and check all nodes +# for the new prefix/address r2.config_gateway(prefix2, default_route=True, priority='1') + def check_prefix2_on_all_nodes(): - verify_prefix(all_nodes, prefix2, stable=True, on_mesh=True, slaac=True, default_route=True, priority='high') + verify_prefix( + all_nodes, + prefix2, + stable=True, + on_mesh=True, + slaac=True, + default_route=True, + priority='high', + ) verify_address(all_nodes, prefix2) + wpan.verify_within(check_prefix2_on_all_nodes, WAIT_TIME) # Add prefix3 on sleepy end-device and check for it on all nodes sc1.config_gateway(prefix3, priority='-1') + def check_prefix3_on_all_nodes(): - verify_prefix(all_nodes, prefix3, stable=True, on_mesh=True, slaac=True, priority='low') + verify_prefix( + all_nodes, + prefix3, + stable=True, + on_mesh=True, + slaac=True, + priority='low', + ) verify_address(all_nodes, prefix3) + wpan.verify_within(check_prefix3_on_all_nodes, WAIT_TIME) # Verify that prefix1 is retained by `wpantund` and pushed to NCP after a reset r1.reset() + def check_r1_is_associated(): verify(r1.is_associated()) + # Wait for r1 to recover after reset wpan.verify_within(check_r1_is_associated, WAIT_TIME) # Wait for on-mesh prefix to be updated wpan.verify_within(check_prefix1_on_all_nodes, WAIT_TIME) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Test `add-prefix` and `remove-prefix` -r1.add_prefix(prefix4, 48, priority="1", stable=False, on_mesh=True, slaac=False, dhcp=True, configure=False, - default_route=True, preferred=False) +r1.add_prefix( + prefix4, + 48, + priority="1", + stable=False, + on_mesh=True, + slaac=False, + dhcp=True, + configure=False, + default_route=True, + preferred=False, +) + def check_prefix4_on_r1(): - verify_prefix(all_nodes, prefix4, 48, priority="high", stable=False, on_mesh=True, slaac=False, dhcp=True, - configure=False, default_route=True, preferred=False) + verify_prefix( + all_nodes, + prefix4, + 48, + priority="high", + stable=False, + on_mesh=True, + slaac=False, + dhcp=True, + configure=False, + default_route=True, + preferred=False, + ) + wpan.verify_within(check_prefix4_on_r1, WAIT_TIME) # Remove prefix and verify that it is removed from list r1.remove_prefix(prefix4, 48) + def check_prefix4_removed_from_r1(): verify(r1.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES).find(prefix4) < 0) + wpan.verify_within(check_prefix4_removed_from_r1, WAIT_TIME) -r1.add_prefix(prefix4, 48, priority="-1", stable=True, on_mesh=False, slaac=True, dhcp=False, configure=True, - default_route=False, preferred=True) -verify_prefix([r1], prefix4, 48, priority="low", stable=True, on_mesh=False, slaac=True, dhcp=False, configure=True, - default_route=False, preferred=True) +r1.add_prefix( + prefix4, + 48, + priority="-1", + stable=True, + on_mesh=False, + slaac=True, + dhcp=False, + configure=True, + default_route=False, + preferred=True, +) +verify_prefix( + [r1], + prefix4, + 48, + priority="low", + stable=True, + on_mesh=False, + slaac=True, + dhcp=False, + configure=True, + default_route=False, + preferred=True, +) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-011-child-table.py b/tests/toranj/test-011-child-table.py index 7d7a2d4cf..6a155d064 100644 --- a/tests/toranj/test-011-child-table.py +++ b/tests/toranj/test-011-child-table.py @@ -26,19 +26,18 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Child-table and child recovery # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -54,12 +53,12 @@ for i in range(NUM_CHILDREN): all_nodes = [router] + children -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology router.form('child-table') @@ -67,12 +66,14 @@ for child in children: child.join_node(router, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE) child.set(wpan.WPAN_POLL_INTERVAL, '1000') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Get the child table and verify all children are in the table. -child_table = wpan.parse_child_table_result(router.get(wpan.WPAN_THREAD_CHILD_TABLE)) +child_table = wpan.parse_child_table_result( + router.get(wpan.WPAN_THREAD_CHILD_TABLE) +) verify(len(child_table) == len(children)) @@ -80,20 +81,26 @@ for child in children: ext_addr = child.get(wpan.WPAN_EXT_ADDRESS)[1:-1] for entry in child_table: if entry.ext_address == ext_addr: - break; + break else: - print 'Failed to find a child entry for extended address {} in table'.format(ext_addr) + print( + 'Failed to find a child entry for extended address {} in table'.format( + ext_addr + ) + ) exit(1) - verify(int(entry.rloc16, 16) == int(child.get(wpan.WPAN_THREAD_RLOC16), 16)) + verify( + int(entry.rloc16, 16) == int(child.get(wpan.WPAN_THREAD_RLOC16), 16) + ) verify(int(entry.timeout, 0) == 120) - verify(entry.is_rx_on_when_idle() == False) - verify(entry.is_ftd() == False) + verify(entry.is_rx_on_when_idle() is False) + verify(entry.is_ftd() is False) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-012-multi-hop-traffic.py b/tests/toranj/test-012-multi-hop-traffic.py index c3b1a306b..eb8c350c3 100644 --- a/tests/toranj/test-012-multi-hop-traffic.py +++ b/tests/toranj/test-012-multi-hop-traffic.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: # # Traffic over multi-hop in a network with chain topology @@ -53,10 +52,10 @@ from wpan import verify test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -77,12 +76,12 @@ fed_children.append(wpan.Node()) all_nodes = routers + sed_children + fed_children -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # # r1 ----- r2 ---- r3 ----- r4 @@ -115,15 +114,17 @@ sed_children[0].join_node(routers[0], wpan.JOIN_TYPE_SLEEPY_END_DEVICE) sed_children[0].set(wpan.WPAN_POLL_INTERVAL, '500') for index in range(1, NUM_ROUTERS): - routers[index].join_node(routers[index -1], wpan.JOIN_TYPE_ROUTER) - sed_children[index].join_node(routers[index], wpan.JOIN_TYPE_SLEEPY_END_DEVICE) + routers[index].join_node(routers[index - 1], wpan.JOIN_TYPE_ROUTER) + sed_children[index].join_node( + routers[index], wpan.JOIN_TYPE_SLEEPY_END_DEVICE + ) sed_children[index].set(wpan.WPAN_POLL_INTERVAL, '500') fed_children[0].join_node(routers[0], wpan.JOIN_TYPE_END_DEVICE) fed_children[-1].join_node(routers[-1], wpan.JOIN_TYPE_END_DEVICE) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation NUM_MSGS = 3 @@ -141,7 +142,8 @@ for msg_length in MSG_LENS: verify(sender.was_successful) verify(recver.was_successful) -# Send from the SED child of the last router to the SED child of the first router. +# Send from the SED child of the last router to the SED child of the first +# router. src = sed_children[-1].get(wpan.WPAN_IP6_MESH_LOCAL_ADDRESS)[1:-1] dst = sed_children[0].get(wpan.WPAN_IP6_MESH_LOCAL_ADDRESS)[1:-1] @@ -153,7 +155,8 @@ for msg_length in MSG_LENS: verify(sender.was_successful) verify(recver.was_successful) -# Send from the FED child of the first router to the FED child of the last router. +# Send from the FED child of the first router to the FED child of the last +# router. src = fed_children[0].get(wpan.WPAN_IP6_MESH_LOCAL_ADDRESS)[1:-1] dst = fed_children[-1].get(wpan.WPAN_IP6_MESH_LOCAL_ADDRESS)[1:-1] @@ -165,9 +168,9 @@ for msg_length in MSG_LENS: verify(sender.was_successful) verify(recver.was_successful) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-013-off-mesh-route-traffic.py b/tests/toranj/test-013-off-mesh-route-traffic.py index 1caf28c2b..1f91fbfaa 100644 --- a/tests/toranj/test-013-off-mesh-route-traffic.py +++ b/tests/toranj/test-013-off-mesh-route-traffic.py @@ -27,11 +27,10 @@ # POSSIBILITY OF SUCH DAMAGE. import time -import subprocess import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Adding off-mesh routes (on routers and FEDs) and traffic flow to off-mesh addresses. # # Test topology: @@ -53,10 +52,10 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -69,7 +68,7 @@ sed2 = wpan.Node() all_nodes = [r1, fed1, r2, sed2] -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() @@ -80,7 +79,7 @@ for node in all_nodes: # on-mesh). node.set("Daemon:IPv6:AutoUpdateInterfaceAddrsOnNCP", '0') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # # r1 ---- r2 @@ -106,19 +105,19 @@ sed2.join_node(r2, wpan.JOIN_TYPE_SLEEPY_END_DEVICE) sed2.set(wpan.WPAN_POLL_INTERVAL, '1500') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation -ON_MESH_PREFIX = "fd00:1234::" +ON_MESH_PREFIX = "fd00:1234::" OFF_MESH_ROUTE_1 = "fd00:abba::" OFF_MESH_ROUTE_2 = "fd00:cafe::" OFF_MESH_ROUTE_3 = "fd00:baba::" -OFF_MESH_ADDR_1 = OFF_MESH_ROUTE_1 + "1" -OFF_MESH_ADDR_2 = OFF_MESH_ROUTE_2 + "2" -OFF_MESH_ADDR_3 = OFF_MESH_ROUTE_3 + "3" +OFF_MESH_ADDR_1 = OFF_MESH_ROUTE_1 + "1" +OFF_MESH_ADDR_2 = OFF_MESH_ROUTE_2 + "2" +OFF_MESH_ADDR_3 = OFF_MESH_ROUTE_3 + "3" # Add on-mesh prefix -r1.config_gateway(ON_MESH_PREFIX); +r1.config_gateway(ON_MESH_PREFIX) # The off-mesh-routes are added as follows: # - `r1` adds OFF_MESH_ROUTE_1, @@ -136,7 +135,8 @@ fed1.add_ip6_address_on_interface(OFF_MESH_ADDR_3) time.sleep(0.5) -# Traffic from `sed2` to `OFF_MESH_ADDR_1` (verify that it is received on `r1`). +# Traffic from `sed2` to `OFF_MESH_ADDR_1` (verify that it is received on +# `r1`). src = sed2.find_ip6_address_with_prefix(ON_MESH_PREFIX) sender = sed2.prepare_tx(src, OFF_MESH_ADDR_1, "Hello Route1") @@ -163,9 +163,9 @@ wpan.Node.perform_async_tx_rx() verify(sender.was_successful) verify(recver.was_successful) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-014-ip6-address-add.py b/tests/toranj/test-014-ip6-address-add.py index 2eeaa763a..74cdf4607 100644 --- a/tests/toranj/test-014-ip6-address-add.py +++ b/tests/toranj/test-014-ip6-address-add.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Adding/Removing IPv6 addresses on routers and SEDs on network interface. # # Test topology: @@ -54,28 +53,28 @@ from wpan import verify # all nodes. test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 wpan.Node.set_time_speedup_factor(speedup) -r1 = wpan.Node() +r1 = wpan.Node() fed1 = wpan.Node() -r2 = wpan.Node() +r2 = wpan.Node() sed2 = wpan.Node() all_nodes = [r1, fed1, r2, sed2] -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # # r1 ---- r2 @@ -101,16 +100,16 @@ sed2.join_node(r2, wpan.JOIN_TYPE_SLEEPY_END_DEVICE) sed2.set(wpan.WPAN_POLL_INTERVAL, '300') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation IP6_PREFIX_1 = "fd00:c0de::" IP6_PREFIX_2 = "fd00:deed::" IP6_PREFIX_3 = "fd00:beef::" -IP6_ADDR_1 = IP6_PREFIX_1 + "1" -IP6_ADDR_2 = IP6_PREFIX_2 + "2" -IP6_ADDR_3 = IP6_PREFIX_3 + "3" +IP6_ADDR_1 = IP6_PREFIX_1 + "1" +IP6_ADDR_2 = IP6_PREFIX_2 + "2" +IP6_ADDR_3 = IP6_PREFIX_3 + "3" # On `r2` add `IP6_ADDR_1` with prefix `IP6_PREFIX_1` # On `fed1` add `IP6_ADDR_2` with prefix `IP6_PREFIX_2` @@ -120,34 +119,43 @@ r2.add_ip6_address_on_interface(IP6_ADDR_1, prefix_len=64) fed1.add_ip6_address_on_interface(IP6_ADDR_2, prefix_len=64) sed2.add_ip6_address_on_interface(IP6_ADDR_3, prefix_len=64) + def check_addresses_and_prefixes(): - # Verify that the addresses are present in "IPv6:AllAddresses" wpantund property on the corresponding node. - verify(r2.find_ip6_address_with_prefix(IP6_PREFIX_1) == IP6_ADDR_1) + # Verify that the addresses are present in "IPv6:AllAddresses" wpantund + # property on the corresponding node. + verify(r2.find_ip6_address_with_prefix(IP6_PREFIX_1) == IP6_ADDR_1) verify(fed1.find_ip6_address_with_prefix(IP6_PREFIX_2) == IP6_ADDR_2) verify(sed2.find_ip6_address_with_prefix(IP6_PREFIX_3) == IP6_ADDR_3) - # Verify that all prefixes are present in network data on all nodes (with correct flags). + # Verify that all prefixes are present in network data on all nodes (with + # correct flags). for prefix in [IP6_PREFIX_1, IP6_PREFIX_2, IP6_PREFIX_3]: for node in all_nodes: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: if p.prefix == prefix: verify(p.prefix_len == '64') verify(p.is_stable()) - verify(p.is_on_mesh() == True) - verify(p.is_preferred() == True) - verify(p.is_def_route() == False) - verify(p.is_slaac() == False) - verify(p.is_dhcp() == False) - verify(p.is_config() == False) + verify(p.is_on_mesh()) + verify(p.is_preferred()) + verify(p.is_def_route() is False) + verify(p.is_slaac() is False) + verify(p.is_dhcp() is False) + verify(p.is_config() is False) verify(p.priority == "med") break - else: # `for` loop finished without finding the prefix. - raise wpan.VerifyError('Did not find prefix {} on node {}'.format(prefix, node)) + else: # `for` loop finished without finding the prefix. + raise wpan.VerifyError( + 'Did not find prefix {} on node {}'.format(prefix, node) + ) - # Verify that IPv6 address of `sed2` is present on `r2` (its parent) "Thread:ChildTable:Addresses". + # Verify that IPv6 address of `sed2` is present on `r2` (its parent) + # "Thread:ChildTable:Addresses". addr_str = r2.get(wpan.WPAN_THREAD_CHILD_TABLE_ADDRESSES) - # search for index on address in the `addr_str` and ensure it is non-negative. + # search for index on address in the `addr_str` and ensure it is + # non-negative. verify(addr_str.find(IP6_ADDR_3) >= 0) @@ -162,21 +170,25 @@ wpan.verify_within(check_addresses_and_prefixes, 20) # Remove address from `r2` r2.remove_ip6_address_on_interface(IP6_ADDR_1, prefix_len=64) + def check_address_prefix_removed(): # Verify that address is removed from r2 verify(r2.find_ip6_address_with_prefix(IP6_PREFIX_1) == '') # Verify that the related prefix is also removed on all nodes for node in all_nodes: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: verify(p.prefix != IP6_PREFIX_1) + # Check the addresses and prefixes (wait time 15 seconds) wpan.verify_within(check_address_prefix_removed, 15) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-015-same-prefix-on-multiple-nodes.py b/tests/toranj/test-015-same-prefix-on-multiple-nodes.py index dbd6510ce..19c61e288 100644 --- a/tests/toranj/test-015-same-prefix-on-multiple-nodes.py +++ b/tests/toranj/test-015-same-prefix-on-multiple-nodes.py @@ -26,39 +26,39 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Adding addresses with same prefix on multiple nodes. # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 wpan.Node.set_time_speedup_factor(speedup) -r1 = wpan.Node() -r2 = wpan.Node() +r1 = wpan.Node() +r2 = wpan.Node() sed2 = wpan.Node() all_nodes = [r1, r2, sed2] -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # -# Two routers r1 and r2 (sed2 is used for quick promotion of r2 to router status). +# Two routers r1 and r2 (sed2 is used for quick promotion of r2 to router +# status). r1.whitelist_node(r2) r2.whitelist_node(r1) @@ -75,13 +75,13 @@ sed2.set(wpan.WPAN_POLL_INTERVAL, '500') r2.status() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation IP6_PREFIX = "fd00:abba::" -IP6_ADDR_1 = IP6_PREFIX + "1" -IP6_ADDR_2 = IP6_PREFIX + "2" +IP6_ADDR_1 = IP6_PREFIX + "1" +IP6_ADDR_2 = IP6_PREFIX + "2" # Add IP6_ADDR_2 to r2. @@ -89,17 +89,32 @@ r2.add_ip6_address_on_interface(IP6_ADDR_2, prefix_len=64) # Verify (within 5 seconds) that corresponding prefix is seen on both nodes. + def check_prefix(): for node in [r1, r2]: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: if p.prefix == IP6_PREFIX: - if (p.origin == 'ncp' and p.prefix_len == '64' and p.is_stable() and p.is_on_mesh() and p.is_preferred() - and not p.is_def_route() and not p.is_slaac() and not p.is_dhcp() and not p.is_config() and - p.priority == "med"): + if ( + p.origin == 'ncp' + and p.prefix_len == '64' + and p.is_stable() + and p.is_on_mesh() + and p.is_preferred() + and not p.is_def_route() + and not p.is_slaac() + and not p.is_dhcp() + and not p.is_config() + and p.priority == "med" + ): break - else: # `for` loop finished without finding the prefix. - raise wpan.VerifyError('Did not find prefix {} on node {}'.format(IP6_PREFIX, r1)) + else: # `for` loop finished without finding the prefix. + raise wpan.VerifyError( + 'Did not find prefix {} on node {}'.format(IP6_PREFIX, r1) + ) + wpan.verify_within(check_prefix, 5) @@ -110,7 +125,8 @@ r1.add_ip6_address_on_interface(IP6_ADDR_1, prefix_len=64) wpan.verify_within(check_prefix, 5) # Remove the address from r2 which should remove the corresponding the prefix as well -# After this since r1 still has the address, the prefix should be present on both nodes. +# After this since r1 still has the address, the prefix should be present +# on both nodes. r2.remove_ip6_address_on_interface(IP6_ADDR_2, prefix_len=64) wpan.verify_within(check_prefix, 5) @@ -121,21 +137,26 @@ wpan.verify_within(check_prefix, 8) # Remove the address on r1. Verify that prefix list is empty. r1.remove_ip6_address_on_interface(IP6_ADDR_1, prefix_len=64) + def check_empty_prefix_list(): for node in [r1, r2]: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) verify(len(prefixes) == 0) + wpan.verify_within(check_empty_prefix_list, 5) -# Add both addresses back-to-back and check the prefix list to contain the prefix. +# Add both addresses back-to-back and check the prefix list to contain the +# prefix. r1.add_ip6_address_on_interface(IP6_ADDR_1, prefix_len=64) r2.add_ip6_address_on_interface(IP6_ADDR_2, prefix_len=64) wpan.verify_within(check_prefix, 5) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-016-neighbor-table.py b/tests/toranj/test-016-neighbor-table.py index 6246672a6..0fdbca889 100644 --- a/tests/toranj/test-016-neighbor-table.py +++ b/tests/toranj/test-016-neighbor-table.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Neighbor table # # - Network with NUM_ROUTERS(= 2) routers, all within range of each other. @@ -39,10 +38,10 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -60,18 +59,18 @@ for num in range(NUM_CHILDREN): children.append(wpan.Node()) # end-device per router used for quick promotion to router role -ed = [ 0 ] +ed = [0] for num in range(1, NUM_ROUTERS): ed.append(wpan.Node()) all_nodes = routers + children + ed -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # @@ -101,16 +100,18 @@ for num in range(1, NUM_ROUTERS): for num in range(NUM_CHILDREN): children[num].join_node(routers[0], wpan.JOIN_TYPE_SLEEPY_END_DEVICE) - children[num].set(wpan.WPAN_POLL_INTERVAL,'300') + children[num].set(wpan.WPAN_POLL_INTERVAL, '300') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation for router in routers[1:]: verify(router.get(wpan.WPAN_NODE_TYPE) == wpan.NODE_TYPE_ROUTER) # Get and parse the neighbor table on routers[0]. -neighbor_table = wpan.parse_neighbor_table_result(routers[0].get(wpan.WPAN_THREAD_NEIGHBOR_TABLE)) +neighbor_table = wpan.parse_neighbor_table_result( + routers[0].get(wpan.WPAN_THREAD_NEIGHBOR_TABLE) +) verify(len(neighbor_table) == NUM_ROUTERS - 1 + NUM_CHILDREN) @@ -119,33 +120,45 @@ for child in children: ext_addr = child.get(wpan.WPAN_EXT_ADDRESS)[1:-1] for entry in neighbor_table: if entry.ext_address == ext_addr: - break; + break else: - raise wpan.VerifyError('Failed to find a child entry for extended address {} in table'.format(ext_addr)) + raise wpan.VerifyError( + 'Failed to find a child entry for extended address {} in table'.format( + ext_addr + ) + ) - verify(int(entry.rloc16, 16) == int(child.get(wpan.WPAN_THREAD_RLOC16), 16)) - verify(entry.is_rx_on_when_idle() == False) - verify(entry.is_ftd() == False) - verify(entry.is_child() == True) + verify( + int(entry.rloc16, 16) == int(child.get(wpan.WPAN_THREAD_RLOC16), 16) + ) + verify(entry.is_rx_on_when_idle() is False) + verify(entry.is_ftd() is False) + verify(entry.is_child()) # Verify that all other routers are seen in the neighbor table for router in routers[1:]: ext_addr = router.get(wpan.WPAN_EXT_ADDRESS)[1:-1] for entry in neighbor_table: if entry.ext_address == ext_addr: - break; + break else: - raise wpan.VerifyError('Failed to find a router entry for extended address {} in table'.format(ext_addr)) + raise wpan.VerifyError( + 'Failed to find a router entry for extended address {} in table'.format( + ext_addr + ) + ) - verify(int(entry.rloc16, 16) == int(router.get(wpan.WPAN_THREAD_RLOC16), 16)) - verify(entry.is_rx_on_when_idle() == True) - verify(entry.is_ftd() == True) - verify(entry.is_child() == False) + verify( + int(entry.rloc16, 16) == int(router.get(wpan.WPAN_THREAD_RLOC16), 16) + ) + verify(entry.is_rx_on_when_idle()) + verify(entry.is_ftd()) + verify(entry.is_child() is False) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-017-parent-reset-child-recovery.py b/tests/toranj/test-017-parent-reset-child-recovery.py index e604536d0..3d66a57bf 100644 --- a/tests/toranj/test-017-parent-reset-child-recovery.py +++ b/tests/toranj/test-017-parent-reset-child-recovery.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Parent restoring children after reset # # This test covers the following: @@ -43,10 +42,10 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 2 @@ -69,12 +68,12 @@ for num in range(NUM_RX_ON_CHILDREN): all_children = sleepy_children + rx_on_children -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # @@ -87,7 +86,7 @@ for child in sleepy_children: for child in rx_on_children: child.join_node(parent, wpan.JOIN_TYPE_END_DEVICE) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # The test verifies that all children are recovered after the parent is reset. @@ -126,11 +125,13 @@ for child in rx_on_children: # ] # + def check_child_table(): # Checks the child table includes the expected number of children. child_table = wpan.parse_list(parent.get(wpan.WPAN_THREAD_CHILD_TABLE)) verify(len(child_table) == NUM_CHILDREN) + # Verify that all children are present in the child table check_child_table() @@ -142,21 +143,28 @@ for child in all_children: # Reset the parent parent.reset() + def check_parent_is_associated(): verify(parent.is_associated()) + wpan.verify_within(check_parent_is_associated, 5) -# Verify that all the children are recovered and present in the parent's child table again (within 5 seconds). +# Verify that all the children are recovered and present in the parent's +# child table again (within 5 seconds). wpan.verify_within(check_child_table, 9) -# Verify that number of state changes on all children stays as before (indicating they did not get detached). +# Verify that number of state changes on all children stays as before +# (indicating they did not get detached). for i in range(len(all_children)): - verify(child_num_state_changes[i] == len(wpan.parse_list(all_children[i].get("stat:ncp")))) + verify( + child_num_state_changes[i] + == len(wpan.parse_list(all_children[i].get("stat:ncp"))) + ) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-018-child-supervision.py b/tests/toranj/test-018-child-supervision.py index afa98e809..29c2a5b59 100644 --- a/tests/toranj/test-018-child-supervision.py +++ b/tests/toranj/test-018-child-supervision.py @@ -30,7 +30,7 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Child Supervision feature # # This test covers the behavior of Child Supervision feature. @@ -50,10 +50,10 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 2 @@ -62,12 +62,12 @@ wpan.Node.set_time_speedup_factor(speedup) parent = wpan.Node() child = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology CHILD_TIMEOUT = 6 @@ -80,7 +80,7 @@ child.set(wpan.WPAN_THREAD_CHILD_TIMEOUT, str(CHILD_TIMEOUT)) parent.form("child-sup") child.join_node(parent, wpan.JOIN_TYPE_SLEEPY_END_DEVICE) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Disable child supervision on child and parent @@ -94,7 +94,9 @@ verify(child.is_associated()) verify(int(child.get(wpan.WPAN_THREAD_CHILD_TIMEOUT), 0) == CHILD_TIMEOUT) # Verify the child table on parent contains the child with correct timeout -child_table = wpan.parse_child_table_result(parent.get(wpan.WPAN_THREAD_CHILD_TABLE)) +child_table = wpan.parse_child_table_result( + parent.get(wpan.WPAN_THREAD_CHILD_TABLE) +) verify(len(child_table) == 1) verify(int(child_table[0].timeout, 0) == CHILD_TIMEOUT) @@ -108,36 +110,53 @@ verify(int(child_table[0].timeout, 0) == CHILD_TIMEOUT) parent.set(wpan.WPAN_MAC_WHITELIST_ENABLED, '1') + def check_child_is_removed_from_parent_child_table(): - child_table = wpan.parse_child_table_result(parent.get(wpan.WPAN_THREAD_CHILD_TABLE)) - verify(len(child_table) == 0) + child_table = wpan.parse_child_table_result( + parent.get(wpan.WPAN_THREAD_CHILD_TABLE) + ) + verify(len(child_table) == 0) + # wait till child is removed from parent's child table # after this child should still be associated -wpan.verify_within(check_child_is_removed_from_parent_child_table, CHILD_TIMEOUT / speedup + 2) +wpan.verify_within( + check_child_is_removed_from_parent_child_table, CHILD_TIMEOUT / speedup + 2 +) verify(child.is_associated()) # Enable supervision check on child and expect the child to # become detached after the check timeout -child.set(wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, str(CHILD_SUPERVISION_CHECK_TIMEOUT)) +child.set( + wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, + str(CHILD_SUPERVISION_CHECK_TIMEOUT), +) + def check_child_is_detached(): - verify(not child.is_associated()) + verify(not child.is_associated()) -wpan.verify_within(check_child_is_detached, CHILD_SUPERVISION_CHECK_TIMEOUT / speedup + 8) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +wpan.verify_within( + check_child_is_detached, CHILD_SUPERVISION_CHECK_TIMEOUT / speedup + 8 +) + +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Enable child supervision on parent and disable white-listing -parent.set(wpan.WPAN_CHILD_SUPERVISION_INTERVAL, str(PARENT_SUPERVISION_INTERVAL)) +parent.set( + wpan.WPAN_CHILD_SUPERVISION_INTERVAL, str(PARENT_SUPERVISION_INTERVAL) +) parent.set(wpan.WPAN_MAC_WHITELIST_ENABLED, '0') # Wait for the child to attach back + def check_child_is_attached(): - verify(child.is_associated()) + verify(child.is_associated()) + wpan.verify_within(check_child_is_attached, 5) @@ -151,7 +170,10 @@ time.sleep(PARENT_SUPERVISION_INTERVAL * 1.2 / speedup) # messages to its child, MAC counter for number of unicast tx is # used. Note that supervision interval on parent is set to 1 sec. -verify(int(parent.get("NCP:Counter:TX_PKT_UNICAST"), 0) >= parent_unicast_tx_count + 1) +verify( + int(parent.get("NCP:Counter:TX_PKT_UNICAST"), 0) + >= parent_unicast_tx_count + 1 +) verify(child.is_associated()) @@ -161,9 +183,9 @@ parent.set(wpan.WPAN_CHILD_SUPERVISION_INTERVAL, '0') time.sleep(CHILD_SUPERVISION_CHECK_TIMEOUT * 3 / speedup) verify(child.is_associated()) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-019-inform-previous-parent.py b/tests/toranj/test-019-inform-previous-parent.py index 83d451bc4..26648940b 100644 --- a/tests/toranj/test-019-inform-previous-parent.py +++ b/tests/toranj/test-019-inform-previous-parent.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Test behavior of "Inform Previous Parent" feature # # With this feature enabled, when a child attaches to a new parent, it will send @@ -59,10 +58,10 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -72,12 +71,12 @@ parent1 = wpan.Node() parent2 = wpan.Node() child = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # # `child` is first attached to `parent2`. It is then forced to switch to `parent1`. @@ -95,10 +94,10 @@ parent2.whitelist_node(child) parent1.form("inform-parent") parent2.join_node(parent1, wpan.JOIN_TYPE_ROUTER) -child.join_node(parent2, wpan.JOIN_TYPE_SLEEPY_END_DEVICE); +child.join_node(parent2, wpan.JOIN_TYPE_SLEEPY_END_DEVICE) child.set(wpan.WPAN_POLL_INTERVAL, '300') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # @@ -109,14 +108,20 @@ PARENT_SUPERVISION_INTERVAL = 1 child_table = wpan.parse_list(parent2.get(wpan.WPAN_THREAD_CHILD_TABLE)) verify(len(child_table) == 1) -# Remove the `child` from whitelist of `parent2` and add it to whitelist of `parent1` instead. +# Remove the `child` from whitelist of `parent2` and add it to whitelist +# of `parent1` instead. parent1.whitelist_node(child) parent2.un_whitelist_node(child) # Enable supervision check on the `child` and also on `parent1`. -child.set(wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, str(CHILD_SUPERVISION_CHECK_TIMEOUT)) -parent1.set(wpan.WPAN_CHILD_SUPERVISION_INTERVAL, str(PARENT_SUPERVISION_INTERVAL)) +child.set( + wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, + str(CHILD_SUPERVISION_CHECK_TIMEOUT), +) +parent1.set( + wpan.WPAN_CHILD_SUPERVISION_INTERVAL, str(PARENT_SUPERVISION_INTERVAL) +) # Since child supervision is not enabled on `parent2` and the `child` is # removed from whitelist on `parent2`, after the supervision check timeout @@ -130,12 +135,17 @@ parent1.set(wpan.WPAN_CHILD_SUPERVISION_INTERVAL, str(PARENT_SUPERVISION_INTERVA child_num_state_changes = len(wpan.parse_list(child.get("stat:ncp"))) + def check_child_is_reattached(): - verify(len(wpan.parse_list(child.get("stat:ncp"))) > child_num_state_changes) - child_is_in_parent2_table = (len(wpan.parse_list(parent2.get(wpan.WPAN_THREAD_CHILD_TABLE)))==1) + verify( + len(wpan.parse_list(child.get("stat:ncp"))) > child_num_state_changes + ) verify(child.is_associated()) -wpan.verify_within(check_child_is_reattached, CHILD_SUPERVISION_CHECK_TIMEOUT / speedup + 5) + +wpan.verify_within( + check_child_is_reattached, CHILD_SUPERVISION_CHECK_TIMEOUT / speedup + 5 +) # Verify that the `child` is now attached to `parent1` child_table = wpan.parse_list(parent1.get(wpan.WPAN_THREAD_CHILD_TABLE)) @@ -145,15 +155,17 @@ verify(len(child_table) == 1) # table (which indicates that the `child` did indeed inform its previous # parent). + def check_child_is_removed_from_parent2_table(): child_table = wpan.parse_list(parent2.get(wpan.WPAN_THREAD_CHILD_TABLE)) verify(len(child_table) == 0) + wpan.verify_within(check_child_is_removed_from_parent2_table, 1) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-020-router-table.py b/tests/toranj/test-020-router-table.py index 176bbba9c..961930c02 100644 --- a/tests/toranj/test-020-router-table.py +++ b/tests/toranj/test-020-router-table.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Router table # # Verify router table entries on a network with 4 routers: @@ -38,10 +37,10 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -53,12 +52,12 @@ r3 = wpan.Node() r4 = wpan.Node() c4 = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # # @@ -93,7 +92,7 @@ r4.whitelist_node(c4) c4.join_node(r4, wpan.JOIN_TYPE_SLEEPY_END_DEVICE) c4.set(wpan.WPAN_POLL_INTERVAL, '2000') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # @@ -121,8 +120,11 @@ WAIT_TIME = 30 / speedup + 5 INVALID_ROUTER_ID = 63 + def check_r1_router_table(): - router_table = wpan.parse_router_table_result(r1.get(wpan.WPAN_THREAD_ROUTER_TABLE)) + router_table = wpan.parse_router_table_result( + r1.get(wpan.WPAN_THREAD_ROUTER_TABLE) + ) verify(len(router_table) == 4) for entry in router_table: if entry.rloc16 == r1_rloc: @@ -137,15 +139,19 @@ def check_r1_router_table(): verify(entry.ext_address == r3_ext_addr) elif entry.rloc16 == r4_rloc: # r1's next hop towards r4 should be through r3. - verify(not entry.is_link_established()); + verify(not entry.is_link_established()) verify(entry.next_hop == r3_id) else: - raise(wpan.VerifyError("unknown entry in the router table of r1")) + raise (wpan.VerifyError("unknown entry in the router table of r1")) + wpan.verify_within(check_r1_router_table, WAIT_TIME) + def check_r3_router_table(): - router_table = wpan.parse_router_table_result(r3.get(wpan.WPAN_THREAD_ROUTER_TABLE)) + router_table = wpan.parse_router_table_result( + r3.get(wpan.WPAN_THREAD_ROUTER_TABLE) + ) verify(len(router_table) == 4) for entry in router_table: if entry.rloc16 == r1_rloc: @@ -160,15 +166,19 @@ def check_r3_router_table(): pass elif entry.rloc16 == r4_rloc: # r3 should be directly connected to r4. - verify(entry.is_link_established()); + verify(entry.is_link_established()) verify(entry.ext_address == r4_ext_addr) else: - raise(wpan.VerifyError("unknown entry in the router table of r3")) + raise (wpan.VerifyError("unknown entry in the router table of r3")) + wpan.verify_within(check_r3_router_table, WAIT_TIME) + def check_r4_router_table(): - router_table = wpan.parse_router_table_result(r4.get(wpan.WPAN_THREAD_ROUTER_TABLE)) + router_table = wpan.parse_router_table_result( + r4.get(wpan.WPAN_THREAD_ROUTER_TABLE) + ) verify(len(router_table) == 4) for entry in router_table: if entry.rloc16 == r1_rloc: @@ -177,7 +187,7 @@ def check_r4_router_table(): verify(entry.next_hop == r3_id) elif entry.rloc16 == r2_rloc: # r4's next hop towards r2 should be through r3. - verify(not entry.is_link_established()); + verify(not entry.is_link_established()) verify(entry.next_hop == r3_id) elif entry.rloc16 == r3_rloc: # r4 should be directly connected to r3. @@ -186,13 +196,14 @@ def check_r4_router_table(): elif entry.rloc16 == r4_rloc: pass else: - raise(wpan.VerifyError("unknown entry in the router table of r4")) + raise (wpan.VerifyError("unknown entry in the router table of r4")) + wpan.verify_within(check_r4_router_table, WAIT_TIME) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-021-address-cache-table.py b/tests/toranj/test-021-address-cache-table.py index 78b88c1ac..b2bad6321 100644 --- a/tests/toranj/test-021-address-cache-table.py +++ b/tests/toranj/test-021-address-cache-table.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Address Cache Table # # This test verifies the behavior of `AddressResolver` module and entries in @@ -42,10 +41,10 @@ from wpan import verify # address cache table. test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -58,12 +57,12 @@ c1 = wpan.Node() c2 = wpan.Node() c3 = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # # r1 ---- r2 ---- r3 @@ -102,7 +101,7 @@ c3.whitelist_node(r3) r3.whitelist_node(c3) c3.join_node(r3, wpan.JOIN_TYPE_END_DEVICE) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # @@ -122,13 +121,18 @@ r3_rloc = int(r3.get(wpan.WPAN_THREAD_RLOC16), 16) c3_rloc = int(c3.get(wpan.WPAN_THREAD_RLOC16), 16) # Wait till we have a valid "next hop" route on r1 towards r3 + + def check_r1_router_table(): - router_table = wpan.parse_router_table_result(r1.get(wpan.WPAN_THREAD_ROUTER_TABLE)) + router_table = wpan.parse_router_table_result( + r1.get(wpan.WPAN_THREAD_ROUTER_TABLE) + ) verify(len(router_table) == 3) for entry in router_table: if entry.rloc16 == r3_rloc: verify(entry.next_hop != INVALID_ROUTER_ID) + wpan.verify_within(check_r1_router_table, ROUTER_TABLE_WAIT_TIME) r1_address = r1.find_ip6_address_with_prefix(PREFIX) @@ -153,7 +157,9 @@ verify(sender.was_successful and recver.was_successful) # The address cache table on r1 should contain two entries for # c2 and c3 addresses. -addr_cache_table = wpan.parse_address_cache_table_result(r1.get(wpan.WPAN_THREAD_ADDRESS_CACHE_TABLE)) +addr_cache_table = wpan.parse_address_cache_table_result( + r1.get(wpan.WPAN_THREAD_ADDRESS_CACHE_TABLE) +) verify(len(addr_cache_table) == 2) for entry in addr_cache_table: @@ -164,9 +170,9 @@ for entry in addr_cache_table: # Entry for c3 should point towards c3 itself. verify(entry.rloc16 == c3_rloc) else: - raise(VerifyError("Unknown entry in the address cache table")) + raise (wpan.VerifyError("Unknown entry in the address cache table")) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Force c2 to switch its parent from r2 to r3 @@ -175,7 +181,10 @@ PARENT_SUPERVISION_INTERVAL = 1 REATTACH_WAIT_TIME = CHILD_SUPERVISION_CHECK_TIMEOUT / speedup + 6 -c2.set(wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, str(CHILD_SUPERVISION_CHECK_TIMEOUT)) +c2.set( + wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, + str(CHILD_SUPERVISION_CHECK_TIMEOUT), +) r3.set(wpan.WPAN_CHILD_SUPERVISION_INTERVAL, str(PARENT_SUPERVISION_INTERVAL)) r2.un_whitelist_node(c2) @@ -187,10 +196,12 @@ c2.whitelist_node(r3) # Upon re-attach, previous parent r2 is notified and should remove c2 from # its child table. + def check_c2_is_removed_from_r2_child_table(): child_table = wpan.parse_list(r2.get(wpan.WPAN_THREAD_CHILD_TABLE)) verify(len(child_table) == 0) + wpan.verify_within(check_c2_is_removed_from_r2_child_table, REATTACH_WAIT_TIME) # Verify that both c2, c3 are children of r3 @@ -219,7 +230,9 @@ verify(sender.was_successful and recver.was_successful) # The address cache table on r1 should still be the same as before. -addr_cache_table = wpan.parse_address_cache_table_result(r1.get(wpan.WPAN_THREAD_ADDRESS_CACHE_TABLE)) +addr_cache_table = wpan.parse_address_cache_table_result( + r1.get(wpan.WPAN_THREAD_ADDRESS_CACHE_TABLE) +) verify(len(addr_cache_table) == 2) for entry in addr_cache_table: @@ -230,7 +243,7 @@ for entry in addr_cache_table: # Entry for c3 should still point towards c3 verify(entry.rloc16 == c3_rloc) else: - raise(VerifyError("Unknown entry in the address cache table")) + raise (wpan.VerifyError("Unknown entry in the address cache table")) # Send a UDP message from c2 to c1. # This message will be forwarded by r1 to its FED child c1. @@ -245,7 +258,9 @@ verify(sender.was_successful and recver.was_successful) # # verify that the address cache table is updated correctly. -addr_cache_table = wpan.parse_address_cache_table_result(r1.get(wpan.WPAN_THREAD_ADDRESS_CACHE_TABLE)) +addr_cache_table = wpan.parse_address_cache_table_result( + r1.get(wpan.WPAN_THREAD_ADDRESS_CACHE_TABLE) +) verify(len(addr_cache_table) == 2) for entry in addr_cache_table: @@ -256,11 +271,11 @@ for entry in addr_cache_table: # Entry for c3's address should still point to c3 verify(entry.rloc16 == c3_rloc) else: - raise(VerifyError("Unknown entry in the address cache table")) + raise (wpan.VerifyError("Unknown entry in the address cache table")) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-022-multicast-ip6-address.py b/tests/toranj/test-022-multicast-ip6-address.py index 47af10919..428e73183 100644 --- a/tests/toranj/test-022-multicast-ip6-address.py +++ b/tests/toranj/test-022-multicast-ip6-address.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Multicast addresses on routers, FEDs, and SEDs # # Test topology: @@ -50,10 +49,10 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -63,20 +62,22 @@ router = wpan.Node() fed = wpan.Node() sed = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Utility functions + def check_multicast_addresses(node, mcast_addr_list): addrs = wpan.parse_list(node.get(wpan.WPAN_IP6_MULTICAST_ADDRESSES)) for addr in mcast_addr_list: verify(addr in addrs) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # @@ -87,7 +88,7 @@ sed.join_node(router, wpan.JOIN_TYPE_SLEEPY_END_DEVICE) sed.set(wpan.WPAN_POLL_INTERVAL, '800') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Get the mesh-local prefix (remove the "/64" at the end of the string) @@ -100,17 +101,17 @@ rl_all_thread_nodes_addr = 'ff33:40:' + ml_prefix + '1' # List of multicast addresses subscribed by all nodes mcast_addrs = [ - "ff02::1", # All nodes link-local - "ff03::1", # All nodes realm-local + "ff02::1", # All nodes link-local + "ff03::1", # All nodes realm-local "ff03::fc", # All MPL forwarder realm-local ll_all_thread_nodes_addr, - rl_all_thread_nodes_addr + rl_all_thread_nodes_addr, ] # List of multicast addresses subscribed by routers only router_mcast_addrs = mcast_addrs + [ - "ff02::2", # All routers link-local - "ff03::2" # All routers realm-local + "ff02::2", # All routers link-local + "ff03::2", # All routers realm-local ] check_multicast_addresses(router, router_mcast_addrs) @@ -128,11 +129,11 @@ for node in [router, fed, sed]: node.remove(wpan.WPAN_IP6_MULTICAST_ADDRESSES, MCAST_ADDR) addrs = wpan.parse_list(node.get(wpan.WPAN_IP6_MULTICAST_ADDRESSES)) - verify(not MCAST_ADDR in addrs) + verify(MCAST_ADDR not in addrs) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-023-multicast-traffic.py b/tests/toranj/test-023-multicast-traffic.py index f5c7d0e19..9217f75ec 100644 --- a/tests/toranj/test-023-multicast-traffic.py +++ b/tests/toranj/test-023-multicast-traffic.py @@ -30,7 +30,7 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Multicast traffic # # Network topology @@ -53,21 +53,35 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Utility functions -def send_mcast(src_node, src_addr, mcast_addr, recving_nodes, non_recving_nodes=[], msg_len=30, mcast_hops=5): + +def send_mcast( + src_node, + src_addr, + mcast_addr, + recving_nodes, + non_recving_nodes=[], + msg_len=30, + mcast_hops=5, +): """ Send a multicast message with given `len` from `src_node` using `src_addr` to the multicast address `mcast_addr`. Verify that the message is received on all nodes in `recving_nodes` list and that it is not received on all nodes in `non_recving_nodes` list. """ - sender = src_node.prepare_tx(src_addr, mcast_addr, msg_len, mcast_hops=mcast_hops) + sender = src_node.prepare_tx( + src_addr, mcast_addr, msg_len, mcast_hops=mcast_hops + ) recvers = [node.prepare_rx(sender) for node in recving_nodes] - listeners = [node.preapre_listener(sender.dst_port, timeout=0.5) for node in non_recving_nodes] + listeners = [ + node.preapre_listener(sender.dst_port, timeout=0.5) + for node in non_recving_nodes + ] wpan.Node.perform_async_tx_rx() @@ -76,10 +90,19 @@ def send_mcast(src_node, src_addr, mcast_addr, recving_nodes, non_recving_nodes= verify(recvr.was_successful) for lsnr in listeners: # `all_rx_msg` contains a list of (msg_content, (src_addr, src_port)). - verify(len(lsnr.all_rx_msg) == 0 or - all([msg[1][0] != sender.src_addr and msg[1][1] != sender.src_port for msg in lsnr.all_rx_msg])) + verify( + len(lsnr.all_rx_msg) == 0 + or all( + [ + msg[1][0] != sender.src_addr + and msg[1][1] != sender.src_port + for msg in lsnr.all_rx_msg + ] + ) + ) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -95,12 +118,12 @@ sed = wpan.Node() all_routers = [r1, r2, r3, r4] all_nodes = all_routers + [fed, sed] -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # # Test topology: @@ -134,7 +157,7 @@ sed.whitelist_node(r4) sed.join_node(r4, wpan.JOIN_TYPE_SLEEPY_END_DEVICE) sed.set(wpan.WPAN_POLL_INTERVAL, '600') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation ml1 = r1.get(wpan.WPAN_IP6_MESH_LOCAL_ADDRESS)[1:-1] @@ -190,27 +213,50 @@ send_mcast(r1, ll1, ll_all_thread_nodes_addr, [r1, r2], [fed, r3, r4, sed]) # fed =>> mesh-local all-thread. send_mcast(fed, ml_fed, ml_all_thread_nodes_addr, all_nodes) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Send a large multicast message (requiring MAC level fragmentations) send_mcast(r3, ml3, ml_all_thread_nodes_addr, all_nodes, msg_len=400) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Check the hop limit behavior # r1 =>> mesh-local all-thread (one hop) -send_mcast(r1, ml1, ml_all_thread_nodes_addr, [r1, r2], [fed, r3, r4, sed], mcast_hops=1) +send_mcast( + r1, + ml1, + ml_all_thread_nodes_addr, + [r1, r2], + [fed, r3, r4, sed], + mcast_hops=1, +) # r1 =>> mesh-local all-thread (two hops) -send_mcast(r1, ml1, ml_all_thread_nodes_addr, [r1, r2, fed, r3], [r4, sed], mcast_hops=2) +send_mcast( + r1, + ml1, + ml_all_thread_nodes_addr, + [r1, r2, fed, r3], + [r4, sed], + mcast_hops=2, +) # r1 =>> mesh-local all-thread (three hops) -send_mcast(r1, ml1, ml_all_thread_nodes_addr, [r1, r2, fed, r3, r4], [sed], mcast_hops=3) +send_mcast( + r1, + ml1, + ml_all_thread_nodes_addr, + [r1, r2, fed, r3, r4], + [sed], + mcast_hops=3, +) # r1 =>> mesh-local all-thread (four hops) -send_mcast(r1, ml1, ml_all_thread_nodes_addr, [r1, r2, fed, r3, r4, sed], mcast_hops=4) +send_mcast( + r1, ml1, ml_all_thread_nodes_addr, [r1, r2, fed, r3, r4, sed], mcast_hops=4 +) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Subscribe to a specific multicast address on r2 and sed mcast_addr = "ff03::114" @@ -221,9 +267,9 @@ time.sleep(1) # r1 =>> specific address send_mcast(r1, ml1, mcast_addr, [r2, sed], [r1, r3, r4, fed]) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-024-partition-merge.py b/tests/toranj/test-024-partition-merge.py index 5fc53ac86..8e205ba6c 100644 --- a/tests/toranj/test-024-partition-merge.py +++ b/tests/toranj/test-024-partition-merge.py @@ -30,7 +30,7 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Partition formation and merge # # Network Topology: @@ -51,19 +51,33 @@ from wpan import verify test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Utility functions -def verify_prefix(node_list, prefix, prefix_len=64, stable=True, priority='med', on_mesh=False, slaac=False, dhcp=False, - configure=False, default_route=False, preferred=False): + +def verify_prefix( + node_list, + prefix, + prefix_len=64, + stable=True, + priority='med', + on_mesh=False, + slaac=False, + dhcp=False, + configure=False, + default_route=False, + preferred=False, +): """ This function verifies that the `prefix` is present on all the nodes in the `node_list`. """ for node in node_list: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: if p.prefix == prefix: verify(int(p.prefix_len) == prefix_len) @@ -77,9 +91,12 @@ def verify_prefix(node_list, prefix, prefix_len=64, stable=True, priority='med', verify(p.priority == priority) break else: - raise wpan.VerifyError("Did not find prefix {} on node {}".format(prefix, node)) + raise wpan.VerifyError( + "Did not find prefix {} on node {}".format(prefix, node) + ) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 25 @@ -90,12 +107,12 @@ r2 = wpan.Node() c1 = wpan.Node() c2 = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # @@ -113,11 +130,11 @@ c2.whitelist_node(r2) r2.whitelist_node(c2) c2.join_node(r2, wpan.JOIN_TYPE_END_DEVICE) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation short_wait = 6 -long_wait = 15 # With speedup of 25, this emulates 375s (~6 min). +long_wait = 15 # With speedup of 25, this emulates 375s (~6 min). prefix1 = "fd00:1234::" prefix2 = "fd00:abcd::" @@ -137,9 +154,12 @@ r2.un_whitelist_node(r1) r2.add_prefix(prefix2) # Check that r2 forms its own partition + + def check_r2_become_leader(): verify(r2.get(wpan.WPAN_NODE_TYPE) == wpan.NODE_TYPE_LEADER) + wpan.verify_within(check_r2_become_leader, long_wait) # While we have two partition, add a prefix on r1 @@ -149,34 +169,47 @@ r1.add_prefix(prefix1) r1.whitelist_node(r2) r2.whitelist_node(r1) + def check_paritition_id_macth(): verify(r1.get(wpan.WPAN_PARTITION_ID) == r2.get(wpan.WPAN_PARTITION_ID)) + wpan.verify_within(check_paritition_id_macth, long_wait) # Check that partitions merged successfully + + def check_r1_r2_roles(): r1_type = r1.get(wpan.WPAN_NODE_TYPE) r2_type = r2.get(wpan.WPAN_NODE_TYPE) - verify((r1_type == wpan.NODE_TYPE_LEADER and r2_type == wpan.NODE_TYPE_ROUTER) or - (r2_type == wpan.NODE_TYPE_LEADER and r1_type == wpan.NODE_TYPE_ROUTER)) + verify( + (r1_type == wpan.NODE_TYPE_LEADER and r2_type == wpan.NODE_TYPE_ROUTER) + or ( + r2_type == wpan.NODE_TYPE_LEADER + and r1_type == wpan.NODE_TYPE_ROUTER + ) + ) + wpan.verify_within(check_r1_r2_roles, short_wait) # Verify all nodes have both prefixes + + def check_prefixes(): verify_prefix([r1, r2, c1, c2], prefix1) verify_prefix([r1, r2, c1, c2], prefix2) + wpan.verify_within(check_prefixes, short_wait) # Verify that the children stayed with their parents verify(len(wpan.parse_list(r1.get(wpan.WPAN_THREAD_CHILD_TABLE))) == 1) verify(len(wpan.parse_list(r2.get(wpan.WPAN_THREAD_CHILD_TABLE))) == 1) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-025-network-data-timeout.py b/tests/toranj/test-025-network-data-timeout.py index b435d1185..602a37456 100644 --- a/tests/toranj/test-025-network-data-timeout.py +++ b/tests/toranj/test-025-network-data-timeout.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Network Data (on-mesh prefix) timeout and entry removal # # Network topology @@ -51,20 +50,38 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -def verify_prefix(node_list, prefix, rloc16, prefix_len=64, stable=True, priority='med', on_mesh=False, slaac=False, dhcp=False, - configure=False, default_route=False, preferred=True): +def verify_prefix( + node_list, + prefix, + rloc16, + prefix_len=64, + stable=True, + priority='med', + on_mesh=False, + slaac=False, + dhcp=False, + configure=False, + default_route=False, + preferred=True, +): """ This function verifies that the `prefix` is present on all the nodes in the `node_list`. It also verifies that the `prefix` is associated with the given `rloc16` (as an integer). """ for node in node_list: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: - if p.prefix == prefix and p.origin == "ncp" and int(p.rloc16(), 0) == rloc16: + if ( + p.prefix == prefix + and p.origin == "ncp" + and int(p.rloc16(), 0) == rloc16 + ): verify(int(p.prefix_len) == prefix_len) verify(p.is_stable() == stable) verify(p.is_on_mesh() == on_mesh) @@ -76,7 +93,10 @@ def verify_prefix(node_list, prefix, rloc16, prefix_len=64, stable=True, priorit verify(p.priority == priority) break else: - raise wpan.VerifyError("Did not find prefix {} on node {}".format(prefix, node)) + raise wpan.VerifyError( + "Did not find prefix {} on node {}".format(prefix, node) + ) + def verify_no_prefix(node_list, prefix, rloc16): """ @@ -84,12 +104,23 @@ def verify_no_prefix(node_list, prefix, rloc16): given `rloc16`. """ for node in node_list: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: - if p.prefix == prefix and p.origin == "ncp" and int(p.rloc16(), 0) == rloc16: - raise wpan.VerifyError("Did find prefix {} with rloc {} on node {}".format(prefix, hex(rloc16), node)) + if ( + p.prefix == prefix + and p.origin == "ncp" + and int(p.rloc16(), 0) == rloc16 + ): + raise wpan.VerifyError( + "Did find prefix {} with rloc {} on node {}".format( + prefix, hex(rloc16), node + ) + ) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 25 @@ -99,12 +130,12 @@ r1 = wpan.Node() r2 = wpan.Node() c2 = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # # Test topology: @@ -125,7 +156,7 @@ c2.whitelist_node(r2) c2.join_node(r2, wpan.JOIN_TYPE_SLEEPY_END_DEVICE) c2.set(wpan.WPAN_POLL_INTERVAL, '400') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation common_prefix = "fd00:cafe::" @@ -149,27 +180,83 @@ r1_rloc = int(r1.get(wpan.WPAN_THREAD_RLOC16), 0) r2_rloc = int(r2.get(wpan.WPAN_THREAD_RLOC16), 0) c2_rloc = int(c2.get(wpan.WPAN_THREAD_RLOC16), 0) + def check_prefixes(): # Verify that all three `prefix1`, 'prefix2', and `prefix3` are present on all nodes # and respectively associated with `r1`, r2, and `r3` nodes. - verify_prefix([r1, r2, c2], prefix1, r1_rloc, on_mesh=True, preferred=True, stable=True) - verify_prefix([r1, r2, c2], prefix2, r2_rloc, on_mesh=True, preferred=True, stable=True) - verify_prefix([r1, r2, c2], prefix3, c2_rloc, on_mesh=True, preferred=True, stable=True) + verify_prefix( + [r1, r2, c2], + prefix1, + r1_rloc, + on_mesh=True, + preferred=True, + stable=True, + ) + verify_prefix( + [r1, r2, c2], + prefix2, + r2_rloc, + on_mesh=True, + preferred=True, + stable=True, + ) + verify_prefix( + [r1, r2, c2], + prefix3, + c2_rloc, + on_mesh=True, + preferred=True, + stable=True, + ) + + # Verify the presence of `common_prefix` associated with each node (with + # correct flags). + verify_prefix( + [r1, r2, c2], + common_prefix, + r1_rloc, + on_mesh=True, + preferred=True, + stable=False, + ) + verify_prefix( + [r1, r2, c2], + common_prefix, + r2_rloc, + on_mesh=True, + preferred=True, + stable=True, + ) + verify_prefix( + [r1, r2, c2], + common_prefix, + c2_rloc, + on_mesh=True, + preferred=False, + stable=True, + ) - # Verify the presence of `common_prefix` associated with each node (with correct flags). - verify_prefix([r1, r2, c2], common_prefix, r1_rloc, on_mesh=True, preferred=True, stable=False) - verify_prefix([r1, r2, c2], common_prefix, r2_rloc, on_mesh=True, preferred=True, stable=True) - verify_prefix([r1, r2, c2], common_prefix, c2_rloc, on_mesh=True, preferred=False, stable=True) wpan.verify_within(check_prefixes, wait_time) -# Remove `r2`. This should trigger all the prefixes added by it or its child to timeout and be removed. +# Remove `r2`. This should trigger all the prefixes added by it or its +# child to timeout and be removed. r2.leave() + def check_prefixes_on_r1_after_r2_leave(): # Verify that entries added by r1 are still present - verify_prefix([r1], prefix1, r1_rloc, on_mesh=True, preferred=True, stable=True) - verify_prefix([r1], common_prefix, r1_rloc, on_mesh=True, preferred=True, stable=False) + verify_prefix( + [r1], prefix1, r1_rloc, on_mesh=True, preferred=True, stable=True + ) + verify_prefix( + [r1], + common_prefix, + r1_rloc, + on_mesh=True, + preferred=True, + stable=False, + ) # Verify all entries added by `r2` or `c2` are removed verify_no_prefix([r1], prefix2, r2_rloc) @@ -177,11 +264,12 @@ def check_prefixes_on_r1_after_r2_leave(): verify_no_prefix([r1], common_prefix, r2_rloc) verify_no_prefix([r1], common_prefix, c2_rloc) + wpan.verify_within(check_prefixes_on_r1_after_r2_leave, wait_time) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-026-slaac-address-wpantund.py b/tests/toranj/test-026-slaac-address-wpantund.py index 78241ee43..95b8cc0bf 100644 --- a/tests/toranj/test-026-slaac-address-wpantund.py +++ b/tests/toranj/test-026-slaac-address-wpantund.py @@ -30,19 +30,20 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: SLAAC address # # This test covers the addition/removal of SLAAC IPv6 address by `wpantund`. # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Utility functions + def verify_address(node_list, prefix): """ This function verifies that all nodes in the `node_list` contain an IPv6 address with the given `prefix`. @@ -51,6 +52,7 @@ def verify_address(node_list, prefix): all_addrs = wpan.parse_list(node.get(wpan.WPAN_IP6_ALL_ADDRESSES)) verify(any([addr.startswith(prefix[:-1]) for addr in all_addrs])) + def verify_no_address(node_list, prefix): """ This function verifies that none of nodes in the `node_list` contain an IPv6 address with the given `prefix`. @@ -59,38 +61,60 @@ def verify_no_address(node_list, prefix): all_addrs = wpan.parse_list(node.get(wpan.WPAN_IP6_ALL_ADDRESSES)) verify(all([not addr.startswith(prefix[:-1]) for addr in all_addrs])) -def verify_prefix(node_list, prefix, prefix_len=64, stable=True, priority='med', on_mesh=False, slaac=False, dhcp=False, - configure=False, default_route=False, preferred=False): + +def verify_prefix( + node_list, + prefix, + prefix_len=64, + stable=True, + priority='med', + on_mesh=False, + slaac=False, + dhcp=False, + configure=False, + default_route=False, + preferred=False, +): """ This function verifies that the `prefix` is present on all nodes in the `node_list`. """ for node in node_list: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: if p.prefix == prefix: - if int(p.prefix_len) == prefix_len and \ - p.is_stable() == stable and \ - p.is_on_mesh() == on_mesh and \ - p.is_def_route() == default_route and \ - p.is_slaac() == slaac and \ - p.is_dhcp() == dhcp and \ - p.is_config() == configure and \ - p.is_preferred() == preferred and \ - p.priority == priority: + if ( + int(p.prefix_len) == prefix_len + and p.is_stable() == stable + and p.is_on_mesh() == on_mesh + and p.is_def_route() == default_route + and p.is_slaac() == slaac + and p.is_dhcp() == dhcp + and p.is_config() == configure + and p.is_preferred() == preferred + and p.priority == priority + ): break else: - raise wpan.VerifyError("Did not find prefix {} on node {}".format(prefix, node)) + raise wpan.VerifyError( + "Did not find prefix {} on node {}".format(prefix, node) + ) + def verify_no_prefix(node_list, prefix): """ This function verifies that the `prefix` is NOT present on any node in the `node_list`. """ for node in node_list: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: verify(not p.prefix == prefix) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -102,12 +126,12 @@ c2 = wpan.Node() all_nodes = [r1, r2, c2] -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology r1.form('slaac-test') @@ -122,7 +146,7 @@ r2.whitelist_node(c2) c2.join_node(r2, node_type=wpan.JOIN_TYPE_END_DEVICE) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # This test covers the SLAAC address management by `wpantund`. So before starting the test we ensure that SLAAC module @@ -140,23 +164,28 @@ r1.add_prefix(PREFIX, stable=True, on_mesh=True, slaac=True) # Verify that all nodes get the prefix and add the SLAAC address + def check_prefix_and_slaac_address_are_added(): verify_prefix(all_nodes, PREFIX, stable=True, on_mesh=True, slaac=True) verify_address(all_nodes, PREFIX) + wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) # Reset r1 and check that prefix and SLAAC address are re-added r1.reset() wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -# Remove the prefix on r1 and verify that the address and prefix are removed on all nodes. +# Remove the prefix on r1 and verify that the address and prefix are +# removed on all nodes. r1.remove_prefix(PREFIX) + def check_prefix_and_slaac_address_are_removed(): verify_no_prefix(all_nodes, PREFIX) verify_no_address(all_nodes, PREFIX) + wpan.verify_within(check_prefix_and_slaac_address_are_removed, WAIT_INTERVAL) # Add prefix on r2 @@ -167,12 +196,14 @@ wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) r1.add_prefix(PREFIX, stable=True, on_mesh=True, slaac=True) wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -# Remove on r1, addresses and prefixes should stay as before (r2 still has the same prefix) +# Remove on r1, addresses and prefixes should stay as before (r2 still has +# the same prefix) r1.remove_prefix(PREFIX) time.sleep(0.5) wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -# Remove the prefix on r2 and verify that the address and prefix are now removed on all nodes. +# Remove the prefix on r2 and verify that the address and prefix are now +# removed on all nodes. r2.remove_prefix(PREFIX) wpan.verify_within(check_prefix_and_slaac_address_are_removed, WAIT_INTERVAL) @@ -184,15 +215,17 @@ wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) # Now remove the prefix on r2 and verify that SLAAC address is removed r2.remove_prefix(PREFIX) + def check_slaac_address_is_removed(): verify_no_address(all_nodes, PREFIX) + wpan.verify_within(check_slaac_address_is_removed, WAIT_INTERVAL) r1.remove_prefix(PREFIX) wpan.verify_within(check_prefix_and_slaac_address_are_removed, WAIT_INTERVAL) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IP_ADDRESS = PREFIX + "1234" @@ -207,23 +240,27 @@ wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) r1_addrs = wpan.parse_list(r1.get(wpan.WPAN_IP6_ALL_ADDRESSES)) verify(IP_ADDRESS in r1_addrs) -# Also verify that adding the prefix did not add a SLAAC address for same prefix on r1 -r1_addrs.remove(IP_ADDRESS); +# Also verify that adding the prefix did not add a SLAAC address for same +# prefix on r1 +r1_addrs.remove(IP_ADDRESS) verify(all([not addr.startswith(PREFIX[:-1]) for addr in r1_addrs])) # Remove the PREFIX on r2 r2.remove_prefix(PREFIX) + def check_ip6_addresses(): # Verify that SLAAC addresses are removed on r2 and c2 - verify_no_address([r2,c2], PREFIX) + verify_no_address([r2, c2], PREFIX) # And that user-added address matching the preifx is not removed on r1 r1_addrs = wpan.parse_list(r1.get(wpan.WPAN_IP6_ALL_ADDRESSES)) verify(IP_ADDRESS in r1_addrs) + wpan.verify_within(check_ip6_addresses, WAIT_INTERVAL) -# Send from r2 to r1 using the user-added address verifying that address is present on NCP +# Send from r2 to r1 using the user-added address verifying that address +# is present on NCP IP_ADDRESS_2 = PREFIX + "2" r2.add_ip6_address_on_interface(IP_ADDRESS_2) sender = r2.prepare_tx(IP_ADDRESS_2, IP_ADDRESS, "Hello r1 from r2") @@ -232,9 +269,9 @@ wpan.Node.perform_async_tx_rx() verify(sender.was_successful) verify(recver.was_successful) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-027-child-mode-change.py b/tests/toranj/test-027-child-mode-change.py index a203f512f..d49174f4e 100644 --- a/tests/toranj/test-027-child-mode-change.py +++ b/tests/toranj/test-027-child-mode-change.py @@ -26,27 +26,29 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Verify Thread mode change on children and recovery after parent reset # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Utility functions + def verify_child_table(parent, children): """ This function verifies that child table on `parent` node contains all the entries in `children` list and the child table entry's mode value matches the children Thread mode. """ - child_table = wpan.parse_child_table_result(parent.get(wpan.WPAN_THREAD_CHILD_TABLE)) + child_table = wpan.parse_child_table_result( + parent.get(wpan.WPAN_THREAD_CHILD_TABLE) + ) verify(len(child_table) == len(children)) for child in children: ext_addr = child.get(wpan.WPAN_EXT_ADDRESS)[1:-1] @@ -54,17 +56,37 @@ def verify_child_table(parent, children): if entry.ext_address == ext_addr: break else: - raise wpan.VerifyError('Failed to find a child entry for extended address {} in table'.format(ext_addr)) + raise wpan.VerifyError( + 'Failed to find a child entry for extended address {} in table'.format( + ext_addr + ) + ) exit(1) - verify(int(entry.rloc16, 16) == int(child.get(wpan.WPAN_THREAD_RLOC16), 16)) + verify( + int(entry.rloc16, 16) + == int(child.get(wpan.WPAN_THREAD_RLOC16), 16) + ) mode = int(child.get(wpan.WPAN_THREAD_DEVICE_MODE), 0) - verify(entry.is_rx_on_when_idle() == (mode & wpan.THREAD_MODE_FLAG_RX_ON_WHEN_IDLE != 0)) - verify(entry.is_ftd() == (mode & wpan.THREAD_MODE_FLAG_FULL_THREAD_DEV != 0)) - verify(entry.is_full_net_data() == (mode & wpan.THREAD_MODE_FLAG_FULL_NETWORK_DATA != 0)) - verify(entry.is_sec_data_req() == (mode & wpan.THREAD_MODE_FLAG_SECURE_DATA_REQUEST != 0)) + verify( + entry.is_rx_on_when_idle() + == (mode & wpan.THREAD_MODE_FLAG_RX_ON_WHEN_IDLE != 0) + ) + verify( + entry.is_ftd() + == (mode & wpan.THREAD_MODE_FLAG_FULL_THREAD_DEV != 0) + ) + verify( + entry.is_full_net_data() + == (mode & wpan.THREAD_MODE_FLAG_FULL_NETWORK_DATA != 0) + ) + verify( + entry.is_sec_data_req() + == (mode & wpan.THREAD_MODE_FLAG_SECURE_DATA_REQUEST != 0) + ) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -74,12 +96,12 @@ parent = wpan.Node() child1 = wpan.Node() child2 = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # @@ -93,15 +115,22 @@ child2.set(wpan.WPAN_POLL_INTERVAL, '8000') children = [child1, child2] -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation WAIT_INTERVAL = 6 # Thread Mode for end-device and sleepy end-device -DEVICE_MODE_SLEEPY_END_DEVICE = wpan.THREAD_MODE_FLAG_FULL_NETWORK_DATA | wpan.THREAD_MODE_FLAG_SECURE_DATA_REQUEST -DEVICE_MODE_END_DEVICE = wpan.THREAD_MODE_FLAG_FULL_NETWORK_DATA | wpan.THREAD_MODE_FLAG_FULL_THREAD_DEV \ - | wpan.THREAD_MODE_FLAG_SECURE_DATA_REQUEST | wpan.THREAD_MODE_FLAG_RX_ON_WHEN_IDLE +DEVICE_MODE_SLEEPY_END_DEVICE = ( + wpan.THREAD_MODE_FLAG_FULL_NETWORK_DATA + | wpan.THREAD_MODE_FLAG_SECURE_DATA_REQUEST +) +DEVICE_MODE_END_DEVICE = ( + wpan.THREAD_MODE_FLAG_FULL_NETWORK_DATA + | wpan.THREAD_MODE_FLAG_FULL_THREAD_DEV + | wpan.THREAD_MODE_FLAG_SECURE_DATA_REQUEST + | wpan.THREAD_MODE_FLAG_RX_ON_WHEN_IDLE +) # Disable child supervision on all devices parent.set(wpan.WPAN_CHILD_SUPERVISION_INTERVAL, '0') @@ -109,12 +138,19 @@ child1.set(wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, '0') child2.set(wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, '0') # Verify Thread Device Mode on both children -verify(int(child1.get(wpan.WPAN_THREAD_DEVICE_MODE),0) == DEVICE_MODE_END_DEVICE) -verify(int(child2.get(wpan.WPAN_THREAD_DEVICE_MODE),0) == DEVICE_MODE_SLEEPY_END_DEVICE) +verify( + int(child1.get(wpan.WPAN_THREAD_DEVICE_MODE), 0) == DEVICE_MODE_END_DEVICE +) +verify( + int(child2.get(wpan.WPAN_THREAD_DEVICE_MODE), 0) + == DEVICE_MODE_SLEEPY_END_DEVICE +) + def check_child_table(): verify_child_table(parent, children) + wpan.verify_within(check_child_table, WAIT_INTERVAL) # Reset parent and verify all children are recovered @@ -123,10 +159,15 @@ wpan.verify_within(check_child_table, WAIT_INTERVAL) # Change mode on both children (make child1 sleepy, and child2 non-sleepy) child1.set(wpan.WPAN_THREAD_DEVICE_MODE, str(DEVICE_MODE_SLEEPY_END_DEVICE)) -verify(int(child1.get(wpan.WPAN_THREAD_DEVICE_MODE),0) == DEVICE_MODE_SLEEPY_END_DEVICE) +verify( + int(child1.get(wpan.WPAN_THREAD_DEVICE_MODE), 0) + == DEVICE_MODE_SLEEPY_END_DEVICE +) child2.set(wpan.WPAN_THREAD_DEVICE_MODE, str(DEVICE_MODE_END_DEVICE)) -verify(int(child2.get(wpan.WPAN_THREAD_DEVICE_MODE),0) == DEVICE_MODE_END_DEVICE) +verify( + int(child2.get(wpan.WPAN_THREAD_DEVICE_MODE), 0) == DEVICE_MODE_END_DEVICE +) # Verify that the child table on parent is also updated wpan.verify_within(check_child_table, WAIT_INTERVAL) @@ -135,9 +176,9 @@ wpan.verify_within(check_child_table, WAIT_INTERVAL) parent.reset() wpan.verify_within(check_child_table, WAIT_INTERVAL) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-028-router-leader-reset-recovery.py b/tests/toranj/test-028-router-leader-reset-recovery.py index b3cfcde41..76af349ab 100644 --- a/tests/toranj/test-028-router-leader-reset-recovery.py +++ b/tests/toranj/test-028-router-leader-reset-recovery.py @@ -26,50 +26,58 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Verify sequential reset recovery of a router and leader # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Utility functions + def verify_neighbor_table(node, neighbors): """ This function verifies that the neighbor table of a given `node` contains the node in the `neighbors` list. """ - neighbor_table = wpan.parse_neighbor_table_result(node.get(wpan.WPAN_THREAD_NEIGHBOR_TABLE)) + neighbor_table = wpan.parse_neighbor_table_result( + node.get(wpan.WPAN_THREAD_NEIGHBOR_TABLE) + ) for neighbor in neighbors: ext_addr = neighbor.get(wpan.WPAN_EXT_ADDRESS)[1:-1] for entry in neighbor_table: if entry.ext_address == ext_addr: break else: - raise wpan.VerifyError('Failed to find a neighbor entry for extended address {} in table'.format(ext_addr)) + raise wpan.VerifyError( + 'Failed to find a neighbor entry for extended address {} in table'.format( + ext_addr + ) + ) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 wpan.Node.set_time_speedup_factor(speedup) -r1 = wpan.Node(); -r2 = wpan.Node(); -c2 = wpan.Node(); # c2 is used to force r2 becoming router +r1 = wpan.Node() +r2 = wpan.Node() +c2 = wpan.Node() +# c2 is used to force r2 becoming router -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # @@ -84,16 +92,19 @@ r2.whitelist_node(c2) c2.join_node(r2, wpan.JOIN_TYPE_END_DEVICE) c2.set(wpan.WPAN_POLL_INTERVAL, '8000') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation WAIT_INTERVAL = 6 # Check that r1 and r2 are present in each other's neighbor table + + def check_neighbor_tables(): verify_neighbor_table(r1, [r2]) verify_neighbor_table(r2, [r1]) + wpan.verify_within(check_neighbor_tables, WAIT_INTERVAL) verify(r1.get(wpan.WPAN_NODE_TYPE) == wpan.NODE_TYPE_LEADER) @@ -102,10 +113,12 @@ verify(r2.get(wpan.WPAN_NODE_TYPE) == wpan.NODE_TYPE_ROUTER) # Reset r2 and wait for it to be associated. r2.reset() + def check_r2_neighbor_table(): verify(r2.is_associated()) verify_neighbor_table(r2, [r1]) + wpan.verify_within(check_r2_neighbor_table, WAIT_INTERVAL) verify(r1.get(wpan.WPAN_NODE_TYPE) == wpan.NODE_TYPE_LEADER) verify(r2.get(wpan.WPAN_NODE_TYPE) == wpan.NODE_TYPE_ROUTER) @@ -114,19 +127,21 @@ verify(r2.get(wpan.WPAN_NODE_TYPE) == wpan.NODE_TYPE_ROUTER) # Now reset r1 and check that everything recover correctly. r1.reset() + def check_r1_neighbor_table(): verify(r1.is_associated()) verify_neighbor_table(r1, [r2]) + wpan.verify_within(check_r1_neighbor_table, WAIT_INTERVAL) verify(r1.get(wpan.WPAN_NODE_TYPE) == wpan.NODE_TYPE_LEADER) verify(r2.get(wpan.WPAN_NODE_TYPE) == wpan.NODE_TYPE_ROUTER) wpan.verify_within(check_r2_neighbor_table, WAIT_INTERVAL) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-029-data-poll-interval.py b/tests/toranj/test-029-data-poll-interval.py index dd245543b..d2463e3cf 100644 --- a/tests/toranj/test-029-data-poll-interval.py +++ b/tests/toranj/test-029-data-poll-interval.py @@ -30,28 +30,28 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Verify transmission of data polls and poll interval change. test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 wpan.Node.set_time_speedup_factor(speedup) -parent = wpan.Node(); +parent = wpan.Node() child = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology # @@ -59,7 +59,7 @@ parent.form("poll-interval") child.join_node(parent, wpan.JOIN_TYPE_SLEEPY_END_DEVICE) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Verify the default poll interval is smaller than child_timeout @@ -68,24 +68,32 @@ child_timeout = int(child.get(wpan.WPAN_THREAD_CHILD_TIMEOUT), 0) * 1000 default_poll_interval = int(child.get(wpan.WPAN_POLL_INTERVAL), 0) verify(0 < default_poll_interval <= child_timeout) -WAIT_TIME = 0.36 # in seconds +WAIT_TIME = 0.36 # in seconds # Check number of data polls with different poll intervals -for poll_interval in [100, 200, 500, 50]: # in milliseconds +for poll_interval in [100, 200, 500, 50]: # in milliseconds - poll_count_before = int(child.get(wpan.WPAN_NCP_COUNTER_TX_PKT_DATA_POLL), 0) + poll_count_before = int( + child.get(wpan.WPAN_NCP_COUNTER_TX_PKT_DATA_POLL), 0 + ) child.set(wpan.WPAN_POLL_INTERVAL, str(poll_interval)) verify(int(child.get(wpan.WPAN_POLL_INTERVAL), 0) == poll_interval) time.sleep(WAIT_TIME) - poll_count_after = int(child.get(wpan.WPAN_NCP_COUNTER_TX_PKT_DATA_POLL), 0) + poll_count_after = int( + child.get(wpan.WPAN_NCP_COUNTER_TX_PKT_DATA_POLL), 0 + ) actual_polls = poll_count_after - poll_count_before expected_polls = WAIT_TIME * 1000 * speedup / poll_interval - print "poll interval {} ms, polls -> actual {}, expected {}".format(poll_interval, actual_polls, expected_polls) + print( + "poll interval {} ms, polls -> actual {}, expected {}".format( + poll_interval, actual_polls, expected_polls + ) + ) verify(actual_polls >= int(expected_polls)) @@ -122,9 +130,9 @@ child.set(wpan.WPAN_THREAD_CHILD_TIMEOUT, str(child_timeout / 1000)) verify(int(child.get(wpan.WPAN_POLL_INTERVAL), 0) == default_poll_interval) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-030-slaac-address-ncp.py b/tests/toranj/test-030-slaac-address-ncp.py index 78b9d9a50..2abbf7d51 100644 --- a/tests/toranj/test-030-slaac-address-ncp.py +++ b/tests/toranj/test-030-slaac-address-ncp.py @@ -30,7 +30,7 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: SLAAC address # # This test covers the behavior of SLAAC module in OpenThread (NCP): @@ -45,12 +45,13 @@ from wpan import verify # - Check behavior when prefix is added while SLAAC module is disabled and then enabled later. test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Utility functions + def verify_address(node_list, prefix): """ This function verifies that all nodes in the `node_list` contain an IPv6 address with the given `prefix`. @@ -59,6 +60,7 @@ def verify_address(node_list, prefix): all_addrs = wpan.parse_list(node.get(wpan.WPAN_IP6_ALL_ADDRESSES)) verify(any([addr.startswith(prefix[:-1]) for addr in all_addrs])) + def verify_no_address(node_list, prefix): """ This function verifies that none of nodes in the `node_list` contain an IPv6 address with the given `prefix`. @@ -67,38 +69,60 @@ def verify_no_address(node_list, prefix): all_addrs = wpan.parse_list(node.get(wpan.WPAN_IP6_ALL_ADDRESSES)) verify(all([not addr.startswith(prefix[:-1]) for addr in all_addrs])) -def verify_prefix(node_list, prefix, prefix_len=64, stable=True, priority='med', on_mesh=False, slaac=False, dhcp=False, - configure=False, default_route=False, preferred=False): + +def verify_prefix( + node_list, + prefix, + prefix_len=64, + stable=True, + priority='med', + on_mesh=False, + slaac=False, + dhcp=False, + configure=False, + default_route=False, + preferred=False, +): """ This function verifies that the `prefix` is present on all nodes in the `node_list`. """ for node in node_list: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: if p.prefix == prefix: - if int(p.prefix_len) == prefix_len and \ - p.is_stable() == stable and \ - p.is_on_mesh() == on_mesh and \ - p.is_def_route() == default_route and \ - p.is_slaac() == slaac and \ - p.is_dhcp() == dhcp and \ - p.is_config() == configure and \ - p.is_preferred() == preferred and \ - p.priority == priority: + if ( + int(p.prefix_len) == prefix_len + and p.is_stable() == stable + and p.is_on_mesh() == on_mesh + and p.is_def_route() == default_route + and p.is_slaac() == slaac + and p.is_dhcp() == dhcp + and p.is_config() == configure + and p.is_preferred() == preferred + and p.priority == priority + ): break else: - raise wpan.VerifyError("Did not find prefix {} on node {}".format(prefix, node)) + raise wpan.VerifyError( + "Did not find prefix {} on node {}".format(prefix, node) + ) + def verify_no_prefix(node_list, prefix): """ This function verifies that the `prefix` is NOT present on any node in the `node_list`. """ for node in node_list: - prefixes = wpan.parse_on_mesh_prefix_result(node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES)) + prefixes = wpan.parse_on_mesh_prefix_result( + node.get(wpan.WPAN_THREAD_ON_MESH_PREFIXES) + ) for p in prefixes: verify(not p.prefix == prefix) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -110,12 +134,12 @@ c2 = wpan.Node() all_nodes = [r1, r2, c2] -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology r1.form('slaac-ncp') @@ -130,7 +154,7 @@ r2.whitelist_node(c2) c2.join_node(r2, node_type=wpan.JOIN_TYPE_END_DEVICE) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # This test covers the SLAAC address management by NCP. So before starting the test we ensure that SLAAC module @@ -145,82 +169,108 @@ WAIT_INTERVAL = 5 PREFIX = 'fd00:1234::' -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Add prefix and check all nodes get the prefix and add a corresponding SLAAC address. +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Add prefix and check all nodes get the prefix and add a corresponding +# SLAAC address. r1.add_prefix(PREFIX, stable=True, on_mesh=True, slaac=True) + def check_prefix_and_slaac_address_are_added(): verify_prefix(all_nodes, PREFIX, stable=True, on_mesh=True, slaac=True) verify_address(all_nodes, PREFIX) + wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) # Save the assigned SLAAC addresses. slaac_addrs = [node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Check recovery after reseting r1 and c1 (same SLAAC address to be added) r1.reset() wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -verify([node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] == slaac_addrs) +verify( + [node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] + == slaac_addrs +) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Remove the prefix on r1 and verify that the address and prefix are removed on all nodes. +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Remove the prefix on r1 and verify that the address and prefix are +# removed on all nodes. r1.remove_prefix(PREFIX) + def check_prefix_and_slaac_address_are_removed(): verify_no_prefix(all_nodes, PREFIX) verify_no_address(all_nodes, PREFIX) + wpan.verify_within(check_prefix_and_slaac_address_are_removed, WAIT_INTERVAL) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Add the prefix on both r1 and r2, then remove from r1 and ensure SLAAC addresses are assigned on all nodes. +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Add the prefix on both r1 and r2, then remove from r1 and ensure SLAAC +# addresses are assigned on all nodes. # Add prefix on r2 r2.add_prefix(PREFIX, stable=True, on_mesh=True, slaac=True) wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -verify([node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] == slaac_addrs) +verify( + [node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] + == slaac_addrs +) # Add same prefix on r1 and verify prefix and addresses stay as before r1.add_prefix(PREFIX, stable=True, on_mesh=True, slaac=True) wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -verify([node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] == slaac_addrs) +verify( + [node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] + == slaac_addrs +) -# Remove on r1, addresses and prefixes should stay as before (r2 still has the same prefix) +# Remove on r1, addresses and prefixes should stay as before (r2 still has +# the same prefix) r1.remove_prefix(PREFIX) time.sleep(0.5) wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -verify([node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] == slaac_addrs) +verify( + [node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] + == slaac_addrs +) -# Remove the prefix on r2 and verify that the address and prefix are now removed on all nodes. +# Remove the prefix on r2 and verify that the address and prefix are now +# removed on all nodes. r2.remove_prefix(PREFIX) wpan.verify_within(check_prefix_and_slaac_address_are_removed, WAIT_INTERVAL) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Add the prefix on r1 (without SLAAC flag) and r2 (with SLAAC flag) # Add prefix on r1 without SLAAC flag, and on r2 with SLAAC flag r1.add_prefix(PREFIX, stable=True, on_mesh=True, slaac=False) r2.add_prefix(PREFIX, stable=True, on_mesh=True, slaac=True) wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -verify([node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] == slaac_addrs) +verify( + [node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] + == slaac_addrs +) # Now remove the prefix on r2 and verify that SLAAC address is removed r2.remove_prefix(PREFIX) + def check_slaac_address_is_removed(): verify_no_address(all_nodes, PREFIX) + wpan.verify_within(check_slaac_address_is_removed, WAIT_INTERVAL) r1.remove_prefix(PREFIX) wpan.verify_within(check_prefix_and_slaac_address_are_removed, WAIT_INTERVAL) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Check behavior when a user-added address with same prefix already exists. IP_ADDRESS = PREFIX + "1234" @@ -236,42 +286,53 @@ wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) r1_addrs = wpan.parse_list(r1.get(wpan.WPAN_IP6_ALL_ADDRESSES)) verify(IP_ADDRESS in r1_addrs) -# Also verify that adding the prefix did not add a SLAAC address for same prefix on r1 -r1_addrs.remove(IP_ADDRESS); +# Also verify that adding the prefix did not add a SLAAC address for same +# prefix on r1 +r1_addrs.remove(IP_ADDRESS) verify(all([not addr.startswith(PREFIX[:-1]) for addr in r1_addrs])) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Check behavior when a user-added address with same prefix is removed (SLAAC module should add a SLAAC address). +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Check behavior when a user-added address with same prefix is removed +# (SLAAC module should add a SLAAC address). r1.remove_ip6_address_on_interface(IP_ADDRESS) wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -verify([node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] == slaac_addrs) +verify( + [node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] + == slaac_addrs +) # Re-add the address r1.add_ip6_address_on_interface(IP_ADDRESS) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Ensure removal of prefix does not remove user-added address with same prefix. r2.remove_prefix(PREFIX) + def check_ip6_addresses(): # Verify that SLAAC addresses are removed on r2 and c2 - verify_no_address([r2,c2], PREFIX) + verify_no_address([r2, c2], PREFIX) # And that user-added address matching the prefix is not removed on r1 r1_addrs = wpan.parse_list(r1.get(wpan.WPAN_IP6_ALL_ADDRESSES)) verify(IP_ADDRESS in r1_addrs) + wpan.verify_within(check_ip6_addresses, WAIT_INTERVAL) r1.remove_ip6_address_on_interface(IP_ADDRESS) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Ensure disabling SLAAC module removes previously added SLAAC addresses, and re-enabling it adds them back. +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Ensure disabling SLAAC module removes previously added SLAAC addresses, +# and re-enabling it adds them back. r1.add_prefix(PREFIX, stable=True, on_mesh=True, slaac=True) wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -verify([node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] == slaac_addrs) +verify( + [node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] + == slaac_addrs +) for node in all_nodes: node.set(wpan.WPAN_OT_SLAAC_ENABLED, 'false') @@ -281,13 +342,17 @@ wpan.verify_within(check_slaac_address_is_removed, WAIT_INTERVAL) for node in all_nodes: node.set(wpan.WPAN_OT_SLAAC_ENABLED, 'true') wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -verify([node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] == slaac_addrs) +verify( + [node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] + == slaac_addrs +) r1.remove_prefix(PREFIX) wpan.verify_within(check_prefix_and_slaac_address_are_removed, WAIT_INTERVAL) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Check behavior when prefix is added while SLAAC is disabled and then enabled later. +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Check behavior when prefix is added while SLAAC is disabled and then +# enabled later. for node in all_nodes: node.set(wpan.WPAN_OT_SLAAC_ENABLED, 'false') @@ -299,11 +364,14 @@ wpan.verify_within(check_slaac_address_is_removed, WAIT_INTERVAL) for node in all_nodes: node.set(wpan.WPAN_OT_SLAAC_ENABLED, 'true') wpan.verify_within(check_prefix_and_slaac_address_are_added, WAIT_INTERVAL) -verify([node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] == slaac_addrs) +verify( + [node.find_ip6_address_with_prefix(PREFIX) for node in all_nodes] + == slaac_addrs +) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-031-meshcop-joiner-commissioner.py b/tests/toranj/test-031-meshcop-joiner-commissioner.py index fc11dbc78..30a471dc6 100644 --- a/tests/toranj/test-031-meshcop-joiner-commissioner.py +++ b/tests/toranj/test-031-meshcop-joiner-commissioner.py @@ -26,21 +26,21 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Test MeshCop Joiner and Commissioner behavior # -# This test covers Thread commissioning with a single commissioner and joiner device. +# This test covers Thread commissioning with a single commissioner and +# joiner device. test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -49,20 +49,20 @@ wpan.Node.set_time_speedup_factor(speedup) c = wpan.Node() j = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology c.form('meshcop') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation -WAIT_TIME = 2 # seconds +WAIT_TIME = 2 # seconds PSKd = '123456' @@ -80,14 +80,16 @@ verify(j.get(wpan.WPAN_STATE) == wpan.STATE_COMMISSIONED) j.joiner_attach() + def joiner_is_asscoated(): verify(j.is_associated()) + wpan.verify_within(joiner_is_asscoated, WAIT_TIME) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-032-child-attach-with-multiple-ip-addresses.py b/tests/toranj/test-032-child-attach-with-multiple-ip-addresses.py index 42befbded..5f986b56c 100644 --- a/tests/toranj/test-032-child-attach-with-multiple-ip-addresses.py +++ b/tests/toranj/test-032-child-attach-with-multiple-ip-addresses.py @@ -30,7 +30,7 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: # # This test covers the situation for SED child (re)attaching to a parent with multiple IPv6 addresses present on the @@ -45,12 +45,13 @@ from wpan import verify # test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Utility functions + def verify_address(node_list, prefix): """ This function verifies that all nodes in the `node_list` contain an IPv6 address with the given `prefix`. @@ -59,7 +60,8 @@ def verify_address(node_list, prefix): all_addrs = wpan.parse_list(node.get(wpan.WPAN_IP6_ALL_ADDRESSES)) verify(any([addr.startswith(prefix[:-1]) for addr in all_addrs])) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -69,12 +71,12 @@ leader = wpan.Node() parent = wpan.Node() child = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology leader.form('multi-addr-test') @@ -89,7 +91,7 @@ child.whitelist_node(parent) child.join_node(parent, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE) child.set(wpan.WPAN_POLL_INTERVAL, '400') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation WAIT_TIME = 5 @@ -107,41 +109,60 @@ leader.add_prefix(prefix3, on_mesh=True, slaac=True, configure=True) leader.add_prefix(prefix4, on_mesh=True, slaac=True, configure=True) # Verify that the sleepy child gets all 4 SLAAC addresses. + + def check_addresses_on_child(): verify_address([child], prefix1) verify_address([child], prefix2) verify_address([child], prefix3) verify_address([child], prefix4) + wpan.verify_within(check_addresses_on_child, WAIT_TIME) # Remove child from parent's white-list -parent.remove(wpan.WPAN_MAC_WHITELIST_ENTRIES, child.get(wpan.WPAN_EXT_ADDRESS)[1:-1]) +parent.remove( + wpan.WPAN_MAC_WHITELIST_ENTRIES, child.get(wpan.WPAN_EXT_ADDRESS)[1:-1] +) # Enable supervision check on child, this ensures that child is detached soon. -child.set(wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, str(CHILD_SUPERVISION_CHECK_TIMEOUT)) +child.set( + wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, + str(CHILD_SUPERVISION_CHECK_TIMEOUT), +) # Wait for child to get detached. + + def check_child_is_detached(): verify(not child.is_associated()) + wpan.verify_within(check_child_is_detached, WAIT_TIME) # Now reset parent and wait for it to be associated. parent.reset() + def check_parent_is_associated(): verify(parent.is_associated()) + wpan.verify_within(check_parent_is_associated, WAIT_TIME) # Now verify that child is indeed getting attached back. + + def check_child_is_associated(): verify(child.is_associated()) + wpan.verify_within(check_child_is_associated, WAIT_TIME) -# Any finally check that we see all the child addresses in the parent's child table. +# Any finally check that we see all the child addresses in the parent's +# child table. + + def check_child_addressses_on_parent(): child_addrs = parent.get(wpan.WPAN_THREAD_CHILD_TABLE_ADDRESSES) verify(child_addrs.find(prefix1) > 0) @@ -149,17 +170,20 @@ def check_child_addressses_on_parent(): verify(child_addrs.find(prefix3) > 0) verify(child_addrs.find(prefix4) > 0) + wpan.verify_within(check_child_addressses_on_parent, WAIT_TIME) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Check the child recovery after a parent reset using quick re-attach ("Child Update" exchange). +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Check the child recovery after a parent reset using quick re-attach +# ("Child Update" exchange). # Disable supervision check on the child. child.set(wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, '1000') child.set(wpan.WPAN_POLL_INTERVAL, '10000') time.sleep(0.1) -# We use the "stat:ncp" wpantund property to verify that child does not get detached. +# We use the "stat:ncp" wpantund property to verify that child does not +# get detached. child_num_state_changes = len(wpan.parse_list(child.get("stat:ncp"))) # Reset parent and wait for it to be associated. @@ -169,15 +193,16 @@ wpan.verify_within(check_parent_is_associated, WAIT_TIME) child.set(wpan.WPAN_POLL_INTERVAL, '100') # Verify that we again see all the child addresses in the parent's child table. -# Note that child should register its addresses using "Child Update Request" exchange. +# Note that child should register its addresses using "Child Update +# Request" exchange. wpan.verify_within(check_child_addressses_on_parent, WAIT_TIME) # Verify that there was no state change on child. verify(child_num_state_changes == len(wpan.parse_list(child.get("stat:ncp")))) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-033-mesh-local-prefix-change.py b/tests/toranj/test-033-mesh-local-prefix-change.py index 4eb55a937..bf1126f06 100644 --- a/tests/toranj/test-033-mesh-local-prefix-change.py +++ b/tests/toranj/test-033-mesh-local-prefix-change.py @@ -26,11 +26,10 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: # # This test covers the situation where a node attached to a parent with a different mesh-local prefix. It verifies @@ -38,10 +37,10 @@ from wpan import verify # filtered (by wpantund). test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -50,12 +49,12 @@ wpan.Node.set_time_speedup_factor(speedup) node1 = wpan.Node() node2 = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation NET_NAME = 'ml-change' @@ -68,23 +67,42 @@ ML_PREFIX_1 = 'fd00:1::' ML_PREFIX_2 = 'fd00:2::' # Form a network on node1 -node1.form(NET_NAME, channel=CHANNEL, panid=PANID, xpanid=XPANID, key=KEY, mesh_local_prefix = ML_PREFIX_1) +node1.form( + NET_NAME, + channel=CHANNEL, + panid=PANID, + xpanid=XPANID, + key=KEY, + mesh_local_prefix=ML_PREFIX_1, +) -# On node2, form a network with same parameters but a different mesh-local prefix -node2.form(NET_NAME, channel=CHANNEL, panid=PANID, xpanid=XPANID, key=KEY, mesh_local_prefix = ML_PREFIX_2) +# On node2, form a network with same parameters but a different mesh-local +# prefix +node2.form( + NET_NAME, + channel=CHANNEL, + panid=PANID, + xpanid=XPANID, + key=KEY, + mesh_local_prefix=ML_PREFIX_2, +) -# Node 2 is expected to attach to node1 and adopt the mesh-local prefix from node1 +# Node 2 is expected to attach to node1 and adopt the mesh-local prefix +# from node1 verify(node2.is_associated()) -verify(node2.get(wpan.WPAN_IP6_MESH_LOCAL_PREFIX) == node1.get(wpan.WPAN_IP6_MESH_LOCAL_PREFIX)) +verify( + node2.get(wpan.WPAN_IP6_MESH_LOCAL_PREFIX) + == node1.get(wpan.WPAN_IP6_MESH_LOCAL_PREFIX) +) # Ensure that there are only two addresses on the node2 (link-local and mesh-local address) and that RLOC # address is correctly filtered (by wpantund). verify(len(wpan.parse_list(node2.get(wpan.WPAN_IP6_ALL_ADDRESSES))) == 2) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-100-mcu-power-state.py b/tests/toranj/test-100-mcu-power-state.py index 4cba5896a..ec232ec1e 100644 --- a/tests/toranj/test-100-mcu-power-state.py +++ b/tests/toranj/test-100-mcu-power-state.py @@ -30,77 +30,93 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Testing controlling of NCP's MCU power state test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances node = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Verify that state is ON after a reset verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_ON) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Check power state wpantund property get and set WAIT_TIME = 5 + def check_wpan_is_in_offline_state(): verify(node.get(wpan.WPAN_STATE) == wpan.STATE_OFFLINE) + def check_wpan_is_in_deep_sleep_state(): verify(node.get(wpan.WPAN_STATE) == wpan.STATE_DEEP_SLEEP) + def check_wpan_is_in_commissioned_state(): verify(node.get(wpan.WPAN_STATE) == wpan.STATE_COMMISSIONED) + def check_wpan_is_in_associated_state(): verify(node.get(wpan.WPAN_STATE) == wpan.STATE_ASSOCIATED) + def check_wpan_is_in_associating_state(): verify(node.get(wpan.WPAN_STATE) == wpan.STATE_ASSOCIATING) + node.form("mcu-power-state") verify(node.is_associated()) node.set(wpan.WPAN_NCP_MCU_POWER_STATE, 'low-power') -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) verify(node.get(wpan.WPAN_STATE) == wpan.STATE_ASSOCIATED) node.set(wpan.WPAN_NCP_MCU_POWER_STATE, 'on') verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_ON) -node.set(wpan.WPAN_NCP_MCU_POWER_STATE, 'lp') # special short-form string for low-power -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +node.set( + wpan.WPAN_NCP_MCU_POWER_STATE, 'lp' +) # special short-form string for low-power +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) node.set(wpan.WPAN_NCP_MCU_POWER_STATE, wpan.MCU_POWER_STATE_ON) verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_ON) node.set(wpan.WPAN_NCP_MCU_POWER_STATE, wpan.MCU_POWER_STATE_LOW_POWER) -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) verify(node.get(wpan.WPAN_STATE) == wpan.STATE_ASSOCIATED) # Verify that `wpantund` will restore the user-set value after NCP reset node.reset() time.sleep(1) -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) node.set(wpan.WPAN_NCP_MCU_POWER_STATE, wpan.MCU_POWER_STATE_ON) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Check the `wpantund` state changes between "deep-sleep" and "offline" node.leave() @@ -109,7 +125,8 @@ verify(not node.is_associated()) verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_ON) verify(node.get(wpan.WPAN_STATE) == wpan.STATE_OFFLINE) -# Setting the power state to `low-power` should change wpantund state to `DEEP_SLEEP` +# Setting the power state to `low-power` should change wpantund state to +# `DEEP_SLEEP` node.set(wpan.WPAN_NCP_MCU_POWER_STATE, wpan.MCU_POWER_STATE_LOW_POWER) wpan.verify_within(check_wpan_is_in_deep_sleep_state, WAIT_TIME) @@ -117,7 +134,9 @@ wpan.verify_within(check_wpan_is_in_deep_sleep_state, WAIT_TIME) # Verify that reading/getting a property does not impact the wpantund state. node.get(wpan.WPAN_THREAD_RLOC16) -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) verify(node.get(wpan.WPAN_STATE) == wpan.STATE_DEEP_SLEEP) # Setting the power state to `on` should change wpantund state to `OFFLINE` @@ -125,25 +144,30 @@ verify(node.get(wpan.WPAN_STATE) == wpan.STATE_DEEP_SLEEP) node.set(wpan.WPAN_NCP_MCU_POWER_STATE, wpan.MCU_POWER_STATE_ON) wpan.verify_within(check_wpan_is_in_offline_state, WAIT_TIME) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Verify the behavior of `begin-low-power` wpanctl command node.wpanctl('begin-low-power') wpan.verify_within(check_wpan_is_in_deep_sleep_state, WAIT_TIME) -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) node.set(wpan.WPAN_NCP_MCU_POWER_STATE, wpan.MCU_POWER_STATE_ON) wpan.verify_within(check_wpan_is_in_offline_state, WAIT_TIME) -# Check the `wpantund` state changes between "offline:commissioned" and "deep-sleep" +# Check the `wpantund` state changes between "offline:commissioned" and +# "deep-sleep" node.form("test-network") -node.set('Daemon:AutoAssociateAfterReset','0') +node.set('Daemon:AutoAssociateAfterReset', '0') # Verify that issuing a `begin-low-power` when in "associated" state # does not change the state. node.wpanctl('begin-low-power') -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) verify(node.get(wpan.WPAN_STATE) == wpan.STATE_ASSOCIATED) # After reset, power state should remain `LOW_POWER` (wpantund would restore the value @@ -162,53 +186,64 @@ wpan.verify_within(check_wpan_is_in_deep_sleep_state, WAIT_TIME) node.set(wpan.WPAN_NCP_MCU_POWER_STATE, wpan.MCU_POWER_STATE_ON) node.leave() -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Verify sleep behavior after disabling `wpantund` ("Daemon:Enabled" property) when state is "offline" +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Verify sleep behavior after disabling `wpantund` ("Daemon:Enabled" +# property) when state is "offline" verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_ON) verify(node.get(wpan.WPAN_STATE) == wpan.STATE_OFFLINE) verify(node.get('Daemon:Enabled') == 'true') # Disabling `wpantund` should put the NCP to deep sleep -node.set('Daemon:Enabled', 'false'); +node.set('Daemon:Enabled', 'false') verify(node.get('Daemon:Enabled') == 'false') wpan.verify_within(check_wpan_is_in_deep_sleep_state, WAIT_TIME) -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) # Enabling `wpantund` should update the `MCU_POWER_STATE` back to `ON`. -node.set('Daemon:Enabled', 'true'); +node.set('Daemon:Enabled', 'true') wpan.verify_within(check_wpan_is_in_offline_state, WAIT_TIME) verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_ON) -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Verify sleep behavior after disabling `wpantund` ("Daemon:Enabled" property) when state is "associated" +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Verify sleep behavior after disabling `wpantund` ("Daemon:Enabled" +# property) when state is "associated" node.form("disable-test") verify(node.is_associated()) verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_ON) -node.set('Daemon:Enabled', 'false'); +node.set('Daemon:Enabled', 'false') verify(node.get('Daemon:Enabled') == 'false') wpan.verify_within(check_wpan_is_in_deep_sleep_state, WAIT_TIME) -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) -node.set('Daemon:Enabled', 'true'); +node.set('Daemon:Enabled', 'true') wpan.verify_within(check_wpan_is_in_commissioned_state, WAIT_TIME) verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_ON) node.leave() -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# Verify `AutoAssociateAfterReset` behavior after reset from "deep-sleep" (but commissioned). +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Verify `AutoAssociateAfterReset` behavior after reset from "deep-sleep" +# (but commissioned). node.set('Daemon:AutoAssociateAfterReset', '1') node.set(wpan.WPAN_NCP_MCU_POWER_STATE, wpan.MCU_POWER_STATE_LOW_POWER) -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) node.form("resume-test") verify(node.is_associated()) -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) node.reset() @@ -217,11 +252,13 @@ node.reset() # is enabled, network should be recovered. wpan.verify_within(check_wpan_is_in_associating_state, WAIT_TIME) -verify(node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER) +verify( + node.get(wpan.WPAN_NCP_MCU_POWER_STATE) == wpan.MCU_POWER_STATE_LOW_POWER +) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-600-channel-manager-properties.py b/tests/toranj/test-600-channel-manager-properties.py index 9e535aa75..2016fdd76 100644 --- a/tests/toranj/test-600-channel-manager-properties.py +++ b/tests/toranj/test-600-channel-manager-properties.py @@ -30,29 +30,30 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- -# Test description: This test verifies wpantund properties related to `ChannelManager` feature +# ----------------------------------------------------------------------------------------------------------------------- +# Test description: This test verifies wpantund properties related to +# `ChannelManager` feature test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances node = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology node.form("channel-manager", channel=11) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Check default property values @@ -74,23 +75,41 @@ node.set(wpan.WPAN_CHANNEL_MANAGER_AUTO_SELECT_ENABLED, '0') verify(node.get(wpan.WPAN_CHANNEL_MANAGER_AUTO_SELECT_ENABLED) == 'false') node.set(wpan.WPAN_CHANNEL_MANAGER_AUTO_SELECT_INTERVAL, '1000') -verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_AUTO_SELECT_INTERVAL), 0) == 1000) +verify( + int(node.get(wpan.WPAN_CHANNEL_MANAGER_AUTO_SELECT_INTERVAL), 0) == 1000 +) all_channls_mask = int('0x7fff800', 0) chan_11_mask = int('0x800', 0) chan_11_to_13_mask = int('0x3800', 0) -node.set(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK, str(all_channls_mask)) -verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK), 0) == all_channls_mask) +node.set( + wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK, str(all_channls_mask) +) +verify( + int(node.get(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK), 0) + == all_channls_mask +) node.set(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK, str(chan_11_mask)) -verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK), 0) == chan_11_mask) +verify( + int(node.get(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK), 0) + == chan_11_mask +) -node.set(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK, str(chan_11_to_13_mask)) -verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK), 0) == chan_11_to_13_mask) +node.set( + wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK, str(chan_11_to_13_mask) +) +verify( + int(node.get(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK), 0) + == chan_11_to_13_mask +) node.set(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK, str(all_channls_mask)) -verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK), 0) == all_channls_mask) +verify( + int(node.get(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK), 0) + == all_channls_mask +) node.set(wpan.WPAN_CHANNEL_MANAGER_AUTO_SELECT_ENABLED, '1') verify(node.get(wpan.WPAN_CHANNEL_MANAGER_AUTO_SELECT_ENABLED) == 'true') @@ -103,20 +122,32 @@ start_time = time.time() wait_time = 20 while node.get(wpan.WPAN_STATE) != wpan.STATE_ASSOCIATED: - if time.time() - start_time > wait_time: - print 'Took too long to restore after reset ({}>{} sec)'.format(time.time() - start_time, wait_time) - exit(1) - time.sleep(2) + if time.time() - start_time > wait_time: + print( + 'Took too long to restore after reset ({}>{} sec)'.format( + time.time() - start_time, wait_time + ) + ) + exit(1) + time.sleep(2) verify(node.get(wpan.WPAN_CHANNEL_MANAGER_AUTO_SELECT_ENABLED) == 'true') -verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK), 0) == all_channls_mask) -verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK), 0) == chan_11_to_13_mask) -verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_AUTO_SELECT_INTERVAL), 0) == 1000) +verify( + int(node.get(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK), 0) + == all_channls_mask +) +verify( + int(node.get(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK), 0) + == chan_11_to_13_mask +) +verify( + int(node.get(wpan.WPAN_CHANNEL_MANAGER_AUTO_SELECT_INTERVAL), 0) == 1000 +) verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_DELAY), 0) == 180) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-601-channel-manager-channel-change.py b/tests/toranj/test-601-channel-manager-channel-change.py index 82744799a..d7a363229 100644 --- a/tests/toranj/test-601-channel-manager-channel-change.py +++ b/tests/toranj/test-601-channel-manager-channel-change.py @@ -30,12 +30,12 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: verifies `ChannelManager` channel change process test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) def verify_channel(nodes, new_channel, wait_time=20): @@ -45,15 +45,23 @@ def verify_channel(nodes, new_channel, wait_time=20): """ start_time = time.time() - while not all([ (new_channel == int(node.get(wpan.WPAN_CHANNEL), 0)) for node in nodes ]): + while not all( + [ + (new_channel == int(node.get(wpan.WPAN_CHANNEL), 0)) + for node in nodes + ] + ): if time.time() - start_time > wait_time: - print 'Took too long to switch to channel {} ({}>{} sec)'.format(new_channel, time.time() - start_time, - wait_time) + print( + 'Took too long to switch to channel {} ({}>{} sec)'.format( + new_channel, time.time() - start_time, wait_time + ) + ) exit(1) time.sleep(0.1) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances speedup = 4 @@ -69,12 +77,12 @@ sc3 = wpan.Node() all_nodes = [r1, r2, r3, sc1, ec1, sc2, sc3] -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology for node in all_nodes: @@ -102,10 +110,11 @@ sc1.set(wpan.WPAN_POLL_INTERVAL, '500') sc2.set(wpan.WPAN_POLL_INTERVAL, '500') sc3.set(wpan.WPAN_POLL_INTERVAL, '500') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation -# The channel manager delay is set from "openthread-core-toranj-config.h". Verify that it is 2 seconds. +# The channel manager delay is set from "openthread-core-toranj-config.h". +# Verify that it is 2 seconds. verify(int(r1.get(wpan.WPAN_CHANNEL_MANAGER_DELAY), 0) == 2) @@ -133,16 +142,18 @@ verify_channel(all_nodes, 16) # Request different channels from two routers (r1 and r2) -r1.set(wpan.WPAN_CHANNEL_MANAGER_DELAY, '20') # increase the time to ensure r1 change is in process +r1.set( + wpan.WPAN_CHANNEL_MANAGER_DELAY, '20' +) # increase the time to ensure r1 change is in process r1.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '17') time.sleep(10.5 / speedup) verify_channel(all_nodes, 16) r2.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '18') verify_channel(all_nodes, 18) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-602-channel-manager-channel-select.py b/tests/toranj/test-602-channel-manager-channel-select.py index 826d206f1..d0996b492 100644 --- a/tests/toranj/test-602-channel-manager-channel-select.py +++ b/tests/toranj/test-602-channel-manager-channel-select.py @@ -30,12 +30,13 @@ import time import wpan from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: verifies `ChannelManager` channel selection procedure test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) + def verify_channel(nodes, new_channel, wait_time=20): """ @@ -44,14 +45,23 @@ def verify_channel(nodes, new_channel, wait_time=20): """ start_time = time.time() - while not all([ (new_channel == int(node.get(wpan.WPAN_CHANNEL), 0)) for node in nodes ]): + while not all( + [ + (new_channel == int(node.get(wpan.WPAN_CHANNEL), 0)) + for node in nodes + ] + ): if time.time() - start_time > wait_time: - print 'Took too long to switch to channel {} ({}>{} sec)'.format(new_channel, time.time() - start_time, - wait_time) + print( + 'Took too long to switch to channel {} ({}>{} sec)'.format( + new_channel, time.time() - start_time, wait_time + ) + ) exit(1) time.sleep(0.1) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances # Run the test with 10,000 time speedup factor @@ -59,42 +69,51 @@ wpan.Node.set_time_speedup_factor(10000) node = wpan.Node() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology node.form('channel-manager', channel=24) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation -all_channls_mask = int('0x7fff800', 0) +all_channls_mask = int('0x7fff800', 0) chan_12_to_15_mask = int('0x000f000', 0) chan_15_to_17_mask = int('0x0038000', 0) # Set supported channel mask to be all channels -node.set(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK, str(all_channls_mask)) -verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK), 0) == all_channls_mask) +node.set( + wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK, str(all_channls_mask) +) +verify( + int(node.get(wpan.WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK), 0) + == all_channls_mask +) -# Sleep for 4.5 second with speedup factor of 10,000 this is more than 12 hours. +# Sleep for 4.5 second with speedup factor of 10,000 this is more than 12 +# hours. time.sleep(4.5) verify(int(node.get(wpan.WPAN_CHANNEL_MONITOR_SAMPLE_COUNT), 0) > 970) -# Verify the initial value of `NEW_CHANNEL` (should be zero if there has been no channel change so far). +# Verify the initial value of `NEW_CHANNEL` (should be zero if there has +# been no channel change so far). verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL), 0) == 0) -# Issue a channel-select with quality check enabled, and verify that no action is taken. +# Issue a channel-select with quality check enabled, and verify that no +# action is taken. node.set(wpan.WPAN_CHANNEL_MANAGER_CHANNEL_SELECT, 'false') verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL), 0) == 0) -# Issue a channel-select with quality check disabled, verify that channel is switched to channel 11. +# Issue a channel-select with quality check disabled, verify that channel +# is switched to channel 11. node.set(wpan.WPAN_CHANNEL_MANAGER_CHANNEL_SELECT, 'true') verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL), 0) == 11) @@ -105,8 +124,12 @@ verify_channel([node], 11) # Even though 11 would be best, quality difference between 11 and 12 is not high enough for selection # algorithm to pick an unfavored channel. -node.set(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK, str(chan_12_to_15_mask)) -node.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '25') # request a channel change to 25 +node.set( + wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK, str(chan_12_to_15_mask) +) +node.set( + wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '25' +) # request a channel change to 25 verify_channel([node], 25) node.set(wpan.WPAN_CHANNEL_MANAGER_CHANNEL_SELECT, 'true') verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL), 0) == 12) @@ -117,16 +140,23 @@ verify_channel([node], 12) # This time the quality difference between 11 and 15 should be high enough for selection # algorithm to pick the best though unfavored channel (i.e., channel 11). -node.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '25') # request a channel change to 25 +node.set( + wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '25' +) # request a channel change to 25 verify_channel([node], 25) -node.set(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK, str(chan_15_to_17_mask)) +node.set( + wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK, str(chan_15_to_17_mask) +) node.set(wpan.WPAN_CHANNEL_MANAGER_CHANNEL_SELECT, 'true') verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL), 0) == 11) verify_channel([node], 11) -# Set channels 12-15 as favorable and request a channel select, verify that channel is not switched. +# Set channels 12-15 as favorable and request a channel select, verify +# that channel is not switched. -node.set(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK, str(chan_12_to_15_mask)) +node.set( + wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK, str(chan_12_to_15_mask) +) node.set(wpan.WPAN_CHANNEL_MANAGER_CHANNEL_SELECT, 'true') verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL), 0) == 11) verify_channel([node], 11) @@ -135,7 +165,9 @@ verify_channel([node], 11) # However, since quality difference between current channel 12 and new best channel 11 is not large # enough, no action should be taken. -node.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '12') # request a channel change to 12 +node.set( + wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '12' +) # request a channel change to 12 verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL), 0) == 12) verify_channel([node], 12) node.set(wpan.WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK, str(all_channls_mask)) @@ -143,9 +175,9 @@ node.set(wpan.WPAN_CHANNEL_MANAGER_CHANNEL_SELECT, 'true') verify(int(node.get(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL), 0) == 12) verify_channel([node], 12) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-603-channel-manager-announce-recovery.py b/tests/toranj/test-603-channel-manager-announce-recovery.py index 0724d68ed..3712b2e0f 100644 --- a/tests/toranj/test-603-channel-manager-announce-recovery.py +++ b/tests/toranj/test-603-channel-manager-announce-recovery.py @@ -30,12 +30,13 @@ from wpan import verify import wpan import time -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: Orphaned node attach through MLE Announcement test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) + def verify_channel(nodes, new_channel, wait_time=20): """ @@ -44,14 +45,23 @@ def verify_channel(nodes, new_channel, wait_time=20): """ start_time = time.time() - while not all([ (new_channel == int(node.get(wpan.WPAN_CHANNEL), 0)) for node in nodes ]): + while not all( + [ + (new_channel == int(node.get(wpan.WPAN_CHANNEL), 0)) + for node in nodes + ] + ): if time.time() - start_time > wait_time: - print 'Took too long to switch to channel {} ({}>{} sec)'.format(new_channel, time.time() - start_time, - wait_time) + print( + 'Took too long to switch to channel {} ({}>{} sec)'.format( + new_channel, time.time() - start_time, wait_time + ) + ) exit(1) time.sleep(0.1) -#----------------------------------------------------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances router = wpan.Node() @@ -60,12 +70,12 @@ c2 = wpan.Node() all_nodes = [router, c1, c2] -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology router.form('announce-tst', channel=11) @@ -76,15 +86,15 @@ c2.join_node(router, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE) c1.set(wpan.WPAN_POLL_INTERVAL, '500') c2.set(wpan.WPAN_POLL_INTERVAL, '500') -c1.set(wpan.WPAN_THREAD_DEVICE_MODE,'5') -c2.set(wpan.WPAN_THREAD_DEVICE_MODE,'5') +c1.set(wpan.WPAN_THREAD_DEVICE_MODE, '5') +c2.set(wpan.WPAN_THREAD_DEVICE_MODE, '5') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation # Reset c2 and keep it in detached state c2.set('Daemon:AutoAssociateAfterReset', 'false') -c2.reset(); +c2.reset() # Switch the rest of network to channel 26 router.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '26') @@ -94,22 +104,24 @@ verify_channel([router, c1], 26) # c2 would go through the ML Announce recovery. c2.set('Daemon:AutoAssociateAfterReset', 'true') -c2.reset(); +c2.reset() verify(int(c2.get(wpan.WPAN_CHANNEL), 0) == 11) # wait for 20s for c2 to be attached/associated + + def check_c2_is_associated(): verify(c2.is_associated()) + wpan.verify_within(check_c2_is_associated, 20) # Check that c2 is now on channel 26. verify(int(c2.get(wpan.WPAN_CHANNEL), 0) == 26) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) - +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/test-nnn-template.py b/tests/toranj/test-nnn-template.py index b1dd0a78c..0a4e6b427 100644 --- a/tests/toranj/test-nnn-template.py +++ b/tests/toranj/test-nnn-template.py @@ -26,40 +26,38 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -import time import wpan -from wpan import verify -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test description: TODO test_name = __file__[:-3] if __file__.endswith('.py') else __file__ -print '-' * 120 -print 'Starting \'{}\''.format(test_name) +print('-' * 120) +print('Starting \'{}\''.format(test_name)) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Creating `wpan.Nodes` instances -#TODO +# TODO -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Build network topology -#TODO +# TODO -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test implementation -#TODO +# TODO -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Test finished wpan.Node.finalize_all_nodes() -print '\'{}\' passed.'.format(test_name) +print('\'{}\' passed.'.format(test_name)) diff --git a/tests/toranj/wpan.py b/tests/toranj/wpan.py index 34f85e150..50450e90d 100644 --- a/tests/toranj/wpan.py +++ b/tests/toranj/wpan.py @@ -38,214 +38,215 @@ import socket import asyncore import inspect -#---------------------------------------------------------------------------------------------------------------------- +# ---------------------------------------------------------------------------------------------------------------------- # wpantund properties -WPAN_STATE = 'NCP:State' -WPAN_NAME = 'Network:Name' -WPAN_PANID = 'Network:PANID' -WPAN_XPANID = 'Network:XPANID' -WPAN_KEY = 'Network:Key' -WPAN_KEY_INDEX = 'Network:KeyIndex' -WPAN_CHANNEL = 'NCP:Channel' -WPAN_HW_ADDRESS = 'NCP:HardwareAddress' -WPAN_EXT_ADDRESS = 'NCP:ExtendedAddress' -WPAN_POLL_INTERVAL = 'NCP:SleepyPollInterval' -WPAN_NODE_TYPE = 'Network:NodeType' -WPAN_ROLE = 'Network:Role' -WPAN_PARTITION_ID = 'Network:PartitionId' -WPAN_NCP_VERSION = 'NCP:Version' -WPAN_NCP_MCU_POWER_STATE = "NCP:MCUPowerState" -WPAN_NETWORK_ALLOW_JOIN = 'com.nestlabs.internal:Network:AllowingJoin' -WPAN_NETWORK_PASSTHRU_PORT = 'com.nestlabs.internal:Network:PassthruPort' -WPAN_RCP_VERSION = "POSIXApp:RCPVersion" +WPAN_STATE = 'NCP:State' +WPAN_NAME = 'Network:Name' +WPAN_PANID = 'Network:PANID' +WPAN_XPANID = 'Network:XPANID' +WPAN_KEY = 'Network:Key' +WPAN_KEY_INDEX = 'Network:KeyIndex' +WPAN_CHANNEL = 'NCP:Channel' +WPAN_HW_ADDRESS = 'NCP:HardwareAddress' +WPAN_EXT_ADDRESS = 'NCP:ExtendedAddress' +WPAN_POLL_INTERVAL = 'NCP:SleepyPollInterval' +WPAN_NODE_TYPE = 'Network:NodeType' +WPAN_ROLE = 'Network:Role' +WPAN_PARTITION_ID = 'Network:PartitionId' +WPAN_NCP_VERSION = 'NCP:Version' +WPAN_NCP_MCU_POWER_STATE = "NCP:MCUPowerState" +WPAN_NETWORK_ALLOW_JOIN = 'com.nestlabs.internal:Network:AllowingJoin' +WPAN_NETWORK_PASSTHRU_PORT = 'com.nestlabs.internal:Network:PassthruPort' +WPAN_RCP_VERSION = "POSIXApp:RCPVersion" -WPAN_IP6_LINK_LOCAL_ADDRESS = "IPv6:LinkLocalAddress" -WPAN_IP6_MESH_LOCAL_ADDRESS = "IPv6:MeshLocalAddress" -WPAN_IP6_MESH_LOCAL_PREFIX = "IPv6:MeshLocalPrefix" -WPAN_IP6_ALL_ADDRESSES = "IPv6:AllAddresses" -WPAN_IP6_MULTICAST_ADDRESSES = "IPv6:MulticastAddresses" +WPAN_IP6_LINK_LOCAL_ADDRESS = "IPv6:LinkLocalAddress" +WPAN_IP6_MESH_LOCAL_ADDRESS = "IPv6:MeshLocalAddress" +WPAN_IP6_MESH_LOCAL_PREFIX = "IPv6:MeshLocalPrefix" +WPAN_IP6_ALL_ADDRESSES = "IPv6:AllAddresses" +WPAN_IP6_MULTICAST_ADDRESSES = "IPv6:MulticastAddresses" -WPAN_THREAD_RLOC16 = "Thread:RLOC16" -WPAN_THREAD_ROUTER_ID = "Thread:RouterID" -WPAN_THREAD_LEADER_ADDRESS = "Thread:Leader:Address" -WPAN_THREAD_LEADER_ROUTER_ID = "Thread:Leader:RouterID" -WPAN_THREAD_LEADER_WEIGHT = "Thread:Leader:Weight" -WPAN_THREAD_LEADER_LOCAL_WEIGHT = "Thread:Leader:LocalWeight" -WPAN_THREAD_LEADER_NETWORK_DATA = "Thread:Leader:NetworkData" -WPAN_THREAD_STABLE_LEADER_NETWORK_DATA = "Thread:Leader:StableNetworkData" -WPAN_THREAD_NETWORK_DATA = "Thread:NetworkData" -WPAN_THREAD_CHILD_TABLE = "Thread:ChildTable" -WPAN_THREAD_CHILD_TABLE_ASVALMAP = "Thread:ChildTable:AsValMap" -WPAN_THREAD_CHILD_TABLE_ADDRESSES = "Thread:ChildTable:Addresses" -WPAN_THREAD_NEIGHBOR_TABLE = "Thread:NeighborTable" -WPAN_THREAD_NEIGHBOR_TABLE_ASVALMAP = "Thread:NeighborTable:AsValMap" -WPAN_THREAD_NEIGHBOR_TABLE_ERR_RATES = "Thread:NeighborTable:ErrorRates" -WPAN_THREAD_NEIGHBOR_TABLE_ERR_RATES_AVVALMAP = "Thread:NeighborTable:ErrorRates:AsValMap" -WPAN_THREAD_ROUTER_TABLE = "Thread:RouterTable" -WPAN_THREAD_ROUTER_TABLE_ASVALMAP = "Thread:RouterTable:AsValMap" -WPAN_THREAD_CHILD_TIMEOUT = "Thread:ChildTimeout" -WPAN_THREAD_PARENT = "Thread:Parent" -WPAN_THREAD_PARENT_ASVALMAP = "Thread:Parent:AsValMap" -WPAN_THREAD_NETWORK_DATA_VERSION = "Thread:NetworkDataVersion" -WPAN_THREAD_STABLE_NETWORK_DATA = "Thread:StableNetworkData" -WPAN_THREAD_STABLE_NETWORK_DATA_VERSION = "Thread:StableNetworkDataVersion" -WPAN_THREAD_PREFERRED_ROUTER_ID = "Thread:PreferredRouterID" -WPAN_THREAD_COMMISSIONER_ENABLED = "Thread:Commissioner:Enabled" -WPAN_THREAD_DEVICE_MODE = "Thread:DeviceMode" -WPAN_THREAD_OFF_MESH_ROUTES = "Thread:OffMeshRoutes" -WPAN_THREAD_ON_MESH_PREFIXES = "Thread:OnMeshPrefixes" -WPAN_THREAD_ROUTER_ROLE_ENABLED = "Thread:RouterRole:Enabled" -WPAN_THREAD_CONFIG_FILTER_RLOC_ADDRESSES = "Thread:Config:FilterRLOCAddresses" -WPAN_THREAD_ROUTER_UPGRADE_THRESHOLD = "Thread:RouterUpgradeThreshold" -WPAN_THREAD_ROUTER_DOWNGRADE_THRESHOLD = "Thread:RouterDowngradeThreshold" -WPAN_THREAD_ACTIVE_DATASET = "Thread:ActiveDataset" -WPAN_THREAD_ACTIVE_DATASET_ASVALMAP = "Thread:ActiveDataset:AsValMap" -WPAN_THREAD_PENDING_DATASET = "Thread:PendingDataset" -WPAN_THREAD_PENDING_DATASET_ASVALMAP = "Thread:PendingDataset:AsValMap" -WPAN_THREAD_ADDRESS_CACHE_TABLE = "Thread:AddressCacheTable" -WPAN_THREAD_ADDRESS_CACHE_TABLE_ASVALMAP = "Thread:AddressCacheTable:AsValMap" +WPAN_THREAD_RLOC16 = "Thread:RLOC16" +WPAN_THREAD_ROUTER_ID = "Thread:RouterID" +WPAN_THREAD_LEADER_ADDRESS = "Thread:Leader:Address" +WPAN_THREAD_LEADER_ROUTER_ID = "Thread:Leader:RouterID" +WPAN_THREAD_LEADER_WEIGHT = "Thread:Leader:Weight" +WPAN_THREAD_LEADER_LOCAL_WEIGHT = "Thread:Leader:LocalWeight" +WPAN_THREAD_LEADER_NETWORK_DATA = "Thread:Leader:NetworkData" +WPAN_THREAD_STABLE_LEADER_NETWORK_DATA = "Thread:Leader:StableNetworkData" +WPAN_THREAD_NETWORK_DATA = "Thread:NetworkData" +WPAN_THREAD_CHILD_TABLE = "Thread:ChildTable" +WPAN_THREAD_CHILD_TABLE_ASVALMAP = "Thread:ChildTable:AsValMap" +WPAN_THREAD_CHILD_TABLE_ADDRESSES = "Thread:ChildTable:Addresses" +WPAN_THREAD_NEIGHBOR_TABLE = "Thread:NeighborTable" +WPAN_THREAD_NEIGHBOR_TABLE_ASVALMAP = "Thread:NeighborTable:AsValMap" +WPAN_THREAD_NEIGHBOR_TABLE_ERR_RATES = "Thread:NeighborTable:ErrorRates" +WPAN_THREAD_NEIGHBOR_TABLE_ERR_RATES_AVVALMAP = "Thread:NeighborTable:ErrorRates:AsValMap" +WPAN_THREAD_ROUTER_TABLE = "Thread:RouterTable" +WPAN_THREAD_ROUTER_TABLE_ASVALMAP = "Thread:RouterTable:AsValMap" +WPAN_THREAD_CHILD_TIMEOUT = "Thread:ChildTimeout" +WPAN_THREAD_PARENT = "Thread:Parent" +WPAN_THREAD_PARENT_ASVALMAP = "Thread:Parent:AsValMap" +WPAN_THREAD_NETWORK_DATA_VERSION = "Thread:NetworkDataVersion" +WPAN_THREAD_STABLE_NETWORK_DATA = "Thread:StableNetworkData" +WPAN_THREAD_STABLE_NETWORK_DATA_VERSION = "Thread:StableNetworkDataVersion" +WPAN_THREAD_PREFERRED_ROUTER_ID = "Thread:PreferredRouterID" +WPAN_THREAD_COMMISSIONER_ENABLED = "Thread:Commissioner:Enabled" +WPAN_THREAD_DEVICE_MODE = "Thread:DeviceMode" +WPAN_THREAD_OFF_MESH_ROUTES = "Thread:OffMeshRoutes" +WPAN_THREAD_ON_MESH_PREFIXES = "Thread:OnMeshPrefixes" +WPAN_THREAD_ROUTER_ROLE_ENABLED = "Thread:RouterRole:Enabled" +WPAN_THREAD_CONFIG_FILTER_RLOC_ADDRESSES = "Thread:Config:FilterRLOCAddresses" +WPAN_THREAD_ROUTER_UPGRADE_THRESHOLD = "Thread:RouterUpgradeThreshold" +WPAN_THREAD_ROUTER_DOWNGRADE_THRESHOLD = "Thread:RouterDowngradeThreshold" +WPAN_THREAD_ACTIVE_DATASET = "Thread:ActiveDataset" +WPAN_THREAD_ACTIVE_DATASET_ASVALMAP = "Thread:ActiveDataset:AsValMap" +WPAN_THREAD_PENDING_DATASET = "Thread:PendingDataset" +WPAN_THREAD_PENDING_DATASET_ASVALMAP = "Thread:PendingDataset:AsValMap" +WPAN_THREAD_ADDRESS_CACHE_TABLE = "Thread:AddressCacheTable" +WPAN_THREAD_ADDRESS_CACHE_TABLE_ASVALMAP = "Thread:AddressCacheTable:AsValMap" -WPAN_OT_LOG_LEVEL = "OpenThread:LogLevel" -WPAN_OT_SLAAC_ENABLED = "OpenThread:SLAAC:Enabled" -WPAN_OT_STEERING_DATA_ADDRESS = "OpenThread:SteeringData:Address" -WPAN_OT_STEERING_DATA_SET_WHEN_JOINABLE = "OpenThread:SteeringData:SetWhenJoinable" -WPAN_OT_MSG_BUFFER_COUNTERS = "OpenThread:MsgBufferCounters" -WPAN_OT_MSG_BUFFER_COUNTERS_AS_STRING = "OpenThread:MsgBufferCounters:AsString" -WPAN_OT_DEBUG_TEST_ASSERT = "OpenThread:Debug:TestAssert" -WPAN_OT_DEBUG_TEST_WATCHDOG = "OpenThread:Debug:TestWatchdog" +WPAN_OT_LOG_LEVEL = "OpenThread:LogLevel" +WPAN_OT_SLAAC_ENABLED = "OpenThread:SLAAC:Enabled" +WPAN_OT_STEERING_DATA_ADDRESS = "OpenThread:SteeringData:Address" +WPAN_OT_STEERING_DATA_SET_WHEN_JOINABLE = "OpenThread:SteeringData:SetWhenJoinable" +WPAN_OT_MSG_BUFFER_COUNTERS = "OpenThread:MsgBufferCounters" +WPAN_OT_MSG_BUFFER_COUNTERS_AS_STRING = "OpenThread:MsgBufferCounters:AsString" +WPAN_OT_DEBUG_TEST_ASSERT = "OpenThread:Debug:TestAssert" +WPAN_OT_DEBUG_TEST_WATCHDOG = "OpenThread:Debug:TestWatchdog" -WPAN_MAC_WHITELIST_ENABLED = "MAC:Whitelist:Enabled" -WPAN_MAC_WHITELIST_ENTRIES = "MAC:Whitelist:Entries" -WPAN_MAC_WHITELIST_ENTRIES_ASVALMAP = "MAC:Whitelist:Entries:AsValMap" -WPAN_MAC_BLACKLIST_ENABLED = "MAC:Blacklist:Enabled" -WPAN_MAC_BLACKLIST_ENTRIES = "MAC:Blacklist:Entries" -WPAN_MAC_BLACKLIST_ENTRIES_ASVALMAP = "MAC:Blacklist:Entries:AsValMap" +WPAN_MAC_WHITELIST_ENABLED = "MAC:Whitelist:Enabled" +WPAN_MAC_WHITELIST_ENTRIES = "MAC:Whitelist:Entries" +WPAN_MAC_WHITELIST_ENTRIES_ASVALMAP = "MAC:Whitelist:Entries:AsValMap" +WPAN_MAC_BLACKLIST_ENABLED = "MAC:Blacklist:Enabled" +WPAN_MAC_BLACKLIST_ENTRIES = "MAC:Blacklist:Entries" +WPAN_MAC_BLACKLIST_ENTRIES_ASVALMAP = "MAC:Blacklist:Entries:AsValMap" -WPAN_CHILD_SUPERVISION_INTERVAL = "ChildSupervision:Interval" -WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT = "ChildSupervision:CheckTimeout" +WPAN_CHILD_SUPERVISION_INTERVAL = "ChildSupervision:Interval" +WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT = "ChildSupervision:CheckTimeout" -WPAN_JAM_DETECTION_STATUS = "JamDetection:Status" -WPAN_JAM_DETECTION_ENABLE = "JamDetection:Enable" -WPAN_JAM_DETECTION_RSSI_THRESHOLD = "JamDetection:RssiThreshold" -WPAN_JAM_DETECTION_WINDOW = "JamDetection:Window" -WPAN_JAM_DETECTION_BUSY_PERIOD = "JamDetection:BusyPeriod" -WPAN_JAM_DETECTION_DEBUG_HISTORY_BITMAP = "JamDetection:Debug:HistoryBitmap" +WPAN_JAM_DETECTION_STATUS = "JamDetection:Status" +WPAN_JAM_DETECTION_ENABLE = "JamDetection:Enable" +WPAN_JAM_DETECTION_RSSI_THRESHOLD = "JamDetection:RssiThreshold" +WPAN_JAM_DETECTION_WINDOW = "JamDetection:Window" +WPAN_JAM_DETECTION_BUSY_PERIOD = "JamDetection:BusyPeriod" +WPAN_JAM_DETECTION_DEBUG_HISTORY_BITMAP = "JamDetection:Debug:HistoryBitmap" -WPAN_CHANNEL_MONITOR_SAMPLE_INTERVAL = "ChannelMonitor:SampleInterval" -WPAN_CHANNEL_MONITOR_RSSI_THRESHOLD = "ChannelMonitor:RssiThreshold" -WPAN_CHANNEL_MONITOR_SAMPLE_WINDOW = "ChannelMonitor:SampleWindow" -WPAN_CHANNEL_MONITOR_SAMPLE_COUNT = "ChannelMonitor:SampleCount" -WPAN_CHANNEL_MONITOR_CHANNEL_QUALITY = "ChannelMonitor:ChannelQuality" -WPAN_CHANNEL_MONITOR_CHANNEL_QUALITY_ASVALMAP = "ChannelMonitor:ChannelQuality:AsValMap" +WPAN_CHANNEL_MONITOR_SAMPLE_INTERVAL = "ChannelMonitor:SampleInterval" +WPAN_CHANNEL_MONITOR_RSSI_THRESHOLD = "ChannelMonitor:RssiThreshold" +WPAN_CHANNEL_MONITOR_SAMPLE_WINDOW = "ChannelMonitor:SampleWindow" +WPAN_CHANNEL_MONITOR_SAMPLE_COUNT = "ChannelMonitor:SampleCount" +WPAN_CHANNEL_MONITOR_CHANNEL_QUALITY = "ChannelMonitor:ChannelQuality" +WPAN_CHANNEL_MONITOR_CHANNEL_QUALITY_ASVALMAP = "ChannelMonitor:ChannelQuality:AsValMap" -WPAN_CHANNEL_MANAGER_NEW_CHANNEL = "ChannelManager:NewChannel" -WPAN_CHANNEL_MANAGER_DELAY = "ChannelManager:Delay" -WPAN_CHANNEL_MANAGER_CHANNEL_SELECT = "ChannelManager:ChannelSelect" -WPAN_CHANNEL_MANAGER_AUTO_SELECT_ENABLED = "ChannelManager:AutoSelect:Enabled" -WPAN_CHANNEL_MANAGER_AUTO_SELECT_INTERVAL = "ChannelManager:AutoSelect:Interval" -WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK = "ChannelManager:SupportedChannelMask" -WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK = "ChannelManager:FavoredChannelMask" +WPAN_CHANNEL_MANAGER_NEW_CHANNEL = "ChannelManager:NewChannel" +WPAN_CHANNEL_MANAGER_DELAY = "ChannelManager:Delay" +WPAN_CHANNEL_MANAGER_CHANNEL_SELECT = "ChannelManager:ChannelSelect" +WPAN_CHANNEL_MANAGER_AUTO_SELECT_ENABLED = "ChannelManager:AutoSelect:Enabled" +WPAN_CHANNEL_MANAGER_AUTO_SELECT_INTERVAL = "ChannelManager:AutoSelect:Interval" +WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK = "ChannelManager:SupportedChannelMask" +WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK = "ChannelManager:FavoredChannelMask" -WPAN_NCP_COUNTER_ALL_MAC = "NCP:Counter:AllMac" -WPAN_NCP_COUNTER_ALL_MAC_ASVALMAP = "NCP:Counter:AllMac:AsValMap" -WPAN_NCP_COUNTER_TX_PKT_TOTAL = "NCP:Counter:TX_PKT_TOTAL" -WPAN_NCP_COUNTER_TX_PKT_UNICAST = "NCP:Counter:TX_PKT_UNICAST" -WPAN_NCP_COUNTER_TX_PKT_BROADCAST = "NCP:Counter:TX_PKT_BROADCAST" -WPAN_NCP_COUNTER_TX_PKT_ACK_REQ = "NCP:Counter:TX_PKT_ACK_REQ" -WPAN_NCP_COUNTER_TX_PKT_ACKED = "NCP:Counter:TX_PKT_ACKED" -WPAN_NCP_COUNTER_TX_PKT_NO_ACK_REQ = "NCP:Counter:TX_PKT_NO_ACK_REQ" -WPAN_NCP_COUNTER_TX_PKT_DATA = "NCP:Counter:TX_PKT_DATA" -WPAN_NCP_COUNTER_TX_PKT_DATA_POLL = "NCP:Counter:TX_PKT_DATA_POLL" -WPAN_NCP_COUNTER_TX_PKT_BEACON = "NCP:Counter:TX_PKT_BEACON" -WPAN_NCP_COUNTER_TX_PKT_BEACON_REQ = "NCP:Counter:TX_PKT_BEACON_REQ" -WPAN_NCP_COUNTER_TX_PKT_OTHER = "NCP:Counter:TX_PKT_OTHER" -WPAN_NCP_COUNTER_TX_PKT_RETRY = "NCP:Counter:TX_PKT_RETRY" -WPAN_NCP_COUNTER_TX_ERR_CCA = "NCP:Counter:TX_ERR_CCA" -WPAN_NCP_COUNTER_TX_ERR_ABORT = "NCP:Counter:TX_ERR_ABORT" -WPAN_NCP_COUNTER_RX_PKT_TOTAL = "NCP:Counter:RX_PKT_TOTAL" -WPAN_NCP_COUNTER_RX_PKT_UNICAST = "NCP:Counter:RX_PKT_UNICAST" -WPAN_NCP_COUNTER_RX_PKT_BROADCAST = "NCP:Counter:RX_PKT_BROADCAST" -WPAN_NCP_COUNTER_RX_PKT_DATA = "NCP:Counter:RX_PKT_DATA" -WPAN_NCP_COUNTER_RX_PKT_DATA_POLL = "NCP:Counter:RX_PKT_DATA_POLL" -WPAN_NCP_COUNTER_RX_PKT_BEACON = "NCP:Counter:RX_PKT_BEACON" -WPAN_NCP_COUNTER_RX_PKT_BEACON_REQ = "NCP:Counter:RX_PKT_BEACON_REQ" -WPAN_NCP_COUNTER_RX_PKT_OTHER = "NCP:Counter:RX_PKT_OTHER" -WPAN_NCP_COUNTER_RX_PKT_FILT_WL = "NCP:Counter:RX_PKT_FILT_WL" -WPAN_NCP_COUNTER_RX_PKT_FILT_DA = "NCP:Counter:RX_PKT_FILT_DA" -WPAN_NCP_COUNTER_RX_ERR_EMPTY = "NCP:Counter:RX_ERR_EMPTY" -WPAN_NCP_COUNTER_RX_ERR_UKWN_NBR = "NCP:Counter:RX_ERR_UKWN_NBR" -WPAN_NCP_COUNTER_RX_ERR_NVLD_SADDR = "NCP:Counter:RX_ERR_NVLD_SADDR" -WPAN_NCP_COUNTER_RX_ERR_SECURITY = "NCP:Counter:RX_ERR_SECURITY" -WPAN_NCP_COUNTER_RX_ERR_BAD_FCS = "NCP:Counter:RX_ERR_BAD_FCS" -WPAN_NCP_COUNTER_RX_ERR_OTHER = "NCP:Counter:RX_ERR_OTHER" -WPAN_NCP_COUNTER_TX_IP_SEC_TOTAL = "NCP:Counter:TX_IP_SEC_TOTAL" -WPAN_NCP_COUNTER_TX_IP_INSEC_TOTAL = "NCP:Counter:TX_IP_INSEC_TOTAL" -WPAN_NCP_COUNTER_TX_IP_DROPPED = "NCP:Counter:TX_IP_DROPPED" -WPAN_NCP_COUNTER_RX_IP_SEC_TOTAL = "NCP:Counter:RX_IP_SEC_TOTAL" -WPAN_NCP_COUNTER_RX_IP_INSEC_TOTAL = "NCP:Counter:RX_IP_INSEC_TOTAL" -WPAN_NCP_COUNTER_RX_IP_DROPPED = "NCP:Counter:RX_IP_DROPPED" -WPAN_NCP_COUNTER_TX_SPINEL_TOTAL = "NCP:Counter:TX_SPINEL_TOTAL" -WPAN_NCP_COUNTER_RX_SPINEL_TOTAL = "NCP:Counter:RX_SPINEL_TOTAL" -WPAN_NCP_COUNTER_RX_SPINEL_ERR = "NCP:Counter:RX_SPINEL_ERR" -WPAN_NCP_COUNTER_IP_TX_SUCCESS = "NCP:Counter:IP_TX_SUCCESS" -WPAN_NCP_COUNTER_IP_RX_SUCCESS = "NCP:Counter:IP_RX_SUCCESS" -WPAN_NCP_COUNTER_IP_TX_FAILURE = "NCP:Counter:IP_TX_FAILURE" -WPAN_NCP_COUNTER_IP_RX_FAILURE = "NCP:Counter:IP_RX_FAILURE" +WPAN_NCP_COUNTER_ALL_MAC = "NCP:Counter:AllMac" +WPAN_NCP_COUNTER_ALL_MAC_ASVALMAP = "NCP:Counter:AllMac:AsValMap" +WPAN_NCP_COUNTER_TX_PKT_TOTAL = "NCP:Counter:TX_PKT_TOTAL" +WPAN_NCP_COUNTER_TX_PKT_UNICAST = "NCP:Counter:TX_PKT_UNICAST" +WPAN_NCP_COUNTER_TX_PKT_BROADCAST = "NCP:Counter:TX_PKT_BROADCAST" +WPAN_NCP_COUNTER_TX_PKT_ACK_REQ = "NCP:Counter:TX_PKT_ACK_REQ" +WPAN_NCP_COUNTER_TX_PKT_ACKED = "NCP:Counter:TX_PKT_ACKED" +WPAN_NCP_COUNTER_TX_PKT_NO_ACK_REQ = "NCP:Counter:TX_PKT_NO_ACK_REQ" +WPAN_NCP_COUNTER_TX_PKT_DATA = "NCP:Counter:TX_PKT_DATA" +WPAN_NCP_COUNTER_TX_PKT_DATA_POLL = "NCP:Counter:TX_PKT_DATA_POLL" +WPAN_NCP_COUNTER_TX_PKT_BEACON = "NCP:Counter:TX_PKT_BEACON" +WPAN_NCP_COUNTER_TX_PKT_BEACON_REQ = "NCP:Counter:TX_PKT_BEACON_REQ" +WPAN_NCP_COUNTER_TX_PKT_OTHER = "NCP:Counter:TX_PKT_OTHER" +WPAN_NCP_COUNTER_TX_PKT_RETRY = "NCP:Counter:TX_PKT_RETRY" +WPAN_NCP_COUNTER_TX_ERR_CCA = "NCP:Counter:TX_ERR_CCA" +WPAN_NCP_COUNTER_TX_ERR_ABORT = "NCP:Counter:TX_ERR_ABORT" +WPAN_NCP_COUNTER_RX_PKT_TOTAL = "NCP:Counter:RX_PKT_TOTAL" +WPAN_NCP_COUNTER_RX_PKT_UNICAST = "NCP:Counter:RX_PKT_UNICAST" +WPAN_NCP_COUNTER_RX_PKT_BROADCAST = "NCP:Counter:RX_PKT_BROADCAST" +WPAN_NCP_COUNTER_RX_PKT_DATA = "NCP:Counter:RX_PKT_DATA" +WPAN_NCP_COUNTER_RX_PKT_DATA_POLL = "NCP:Counter:RX_PKT_DATA_POLL" +WPAN_NCP_COUNTER_RX_PKT_BEACON = "NCP:Counter:RX_PKT_BEACON" +WPAN_NCP_COUNTER_RX_PKT_BEACON_REQ = "NCP:Counter:RX_PKT_BEACON_REQ" +WPAN_NCP_COUNTER_RX_PKT_OTHER = "NCP:Counter:RX_PKT_OTHER" +WPAN_NCP_COUNTER_RX_PKT_FILT_WL = "NCP:Counter:RX_PKT_FILT_WL" +WPAN_NCP_COUNTER_RX_PKT_FILT_DA = "NCP:Counter:RX_PKT_FILT_DA" +WPAN_NCP_COUNTER_RX_ERR_EMPTY = "NCP:Counter:RX_ERR_EMPTY" +WPAN_NCP_COUNTER_RX_ERR_UKWN_NBR = "NCP:Counter:RX_ERR_UKWN_NBR" +WPAN_NCP_COUNTER_RX_ERR_NVLD_SADDR = "NCP:Counter:RX_ERR_NVLD_SADDR" +WPAN_NCP_COUNTER_RX_ERR_SECURITY = "NCP:Counter:RX_ERR_SECURITY" +WPAN_NCP_COUNTER_RX_ERR_BAD_FCS = "NCP:Counter:RX_ERR_BAD_FCS" +WPAN_NCP_COUNTER_RX_ERR_OTHER = "NCP:Counter:RX_ERR_OTHER" +WPAN_NCP_COUNTER_TX_IP_SEC_TOTAL = "NCP:Counter:TX_IP_SEC_TOTAL" +WPAN_NCP_COUNTER_TX_IP_INSEC_TOTAL = "NCP:Counter:TX_IP_INSEC_TOTAL" +WPAN_NCP_COUNTER_TX_IP_DROPPED = "NCP:Counter:TX_IP_DROPPED" +WPAN_NCP_COUNTER_RX_IP_SEC_TOTAL = "NCP:Counter:RX_IP_SEC_TOTAL" +WPAN_NCP_COUNTER_RX_IP_INSEC_TOTAL = "NCP:Counter:RX_IP_INSEC_TOTAL" +WPAN_NCP_COUNTER_RX_IP_DROPPED = "NCP:Counter:RX_IP_DROPPED" +WPAN_NCP_COUNTER_TX_SPINEL_TOTAL = "NCP:Counter:TX_SPINEL_TOTAL" +WPAN_NCP_COUNTER_RX_SPINEL_TOTAL = "NCP:Counter:RX_SPINEL_TOTAL" +WPAN_NCP_COUNTER_RX_SPINEL_ERR = "NCP:Counter:RX_SPINEL_ERR" +WPAN_NCP_COUNTER_IP_TX_SUCCESS = "NCP:Counter:IP_TX_SUCCESS" +WPAN_NCP_COUNTER_IP_RX_SUCCESS = "NCP:Counter:IP_RX_SUCCESS" +WPAN_NCP_COUNTER_IP_TX_FAILURE = "NCP:Counter:IP_TX_FAILURE" +WPAN_NCP_COUNTER_IP_RX_FAILURE = "NCP:Counter:IP_RX_FAILURE" -#---------------------------------------------------------------------------------------------------------------------- +# ---------------------------------------------------------------------------------------------------------------------- # Valid state values -STATE_UNINITIALIZED = '"uninitialized"' -STATE_FAULT = '"uninitialized:fault"' -STATE_UPGRADING = '"uninitialized:upgrading"' -STATE_DEEP_SLEEP = '"offline:deep-sleep"' -STATE_OFFLINE = '"offline"' -STATE_COMMISSIONED = '"offline:commissioned"' -STATE_ASSOCIATING = '"associating"' -STATE_CREDENTIALS_NEEDED = '"associating:credentials-needed"' -STATE_ASSOCIATED = '"associated"' -STATE_ISOLATED = '"associated:no-parent"' -STATE_NETWAKE_ASLEEP = '"associated:netwake-asleep"' -STATE_NETWAKE_WAKING = '"associated:netwake-waking"' +STATE_UNINITIALIZED = '"uninitialized"' +STATE_FAULT = '"uninitialized:fault"' +STATE_UPGRADING = '"uninitialized:upgrading"' +STATE_DEEP_SLEEP = '"offline:deep-sleep"' +STATE_OFFLINE = '"offline"' +STATE_COMMISSIONED = '"offline:commissioned"' +STATE_ASSOCIATING = '"associating"' +STATE_CREDENTIALS_NEEDED = '"associating:credentials-needed"' +STATE_ASSOCIATED = '"associated"' +STATE_ISOLATED = '"associated:no-parent"' +STATE_NETWAKE_ASLEEP = '"associated:netwake-asleep"' +STATE_NETWAKE_WAKING = '"associated:netwake-waking"' -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # MCU Power state from `WPAN_NCP_MCU_POWER_STATE` -MCU_POWER_STATE_ON = '"on"' -MCU_POWER_STATE_LOW_POWER = '"low-power"' -MCU_POWER_STATE_OFF = '"off"' +MCU_POWER_STATE_ON = '"on"' +MCU_POWER_STATE_LOW_POWER = '"low-power"' +MCU_POWER_STATE_OFF = '"off"' -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Node types (from `WPAN_NODE_TYPE` property) -NODE_TYPE_UNKNOWN = '"unknown"' -NODE_TYPE_LEADER = '"leader"' -NODE_TYPE_ROUTER = '"router"' -NODE_TYPE_END_DEVICE = '"end-device"' -NODE_TYPE_SLEEPY_END_DEVICE = '"sleepy-end-device"' -NODE_TYPE_COMMISSIONER = '"commissioner"' -NODE_TYPE_NEST_LURKER = '"nl-lurker"' +NODE_TYPE_UNKNOWN = '"unknown"' +NODE_TYPE_LEADER = '"leader"' +NODE_TYPE_ROUTER = '"router"' +NODE_TYPE_END_DEVICE = '"end-device"' +NODE_TYPE_SLEEPY_END_DEVICE = '"sleepy-end-device"' +NODE_TYPE_COMMISSIONER = '"commissioner"' +NODE_TYPE_NEST_LURKER = '"nl-lurker"' -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Node types used by `Node.join()` -JOIN_TYPE_ROUTER = 'r' -JOIN_TYPE_END_DEVICE = 'e' -JOIN_TYPE_SLEEPY_END_DEVICE = 's' +JOIN_TYPE_ROUTER = 'r' +JOIN_TYPE_END_DEVICE = 'e' +JOIN_TYPE_SLEEPY_END_DEVICE = 's' -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Bit Flags for Thread Device Mode `WPAN_THREAD_DEVICE_MODE` -THREAD_MODE_FLAG_FULL_NETWORK_DATA = (1 << 0) -THREAD_MODE_FLAG_FULL_THREAD_DEV = (1 << 1) +THREAD_MODE_FLAG_FULL_NETWORK_DATA = (1 << 0) +THREAD_MODE_FLAG_FULL_THREAD_DEV = (1 << 1) THREAD_MODE_FLAG_SECURE_DATA_REQUEST = (1 << 2) -THREAD_MODE_FLAG_RX_ON_WHEN_IDLE = (1 << 3) +THREAD_MODE_FLAG_RX_ON_WHEN_IDLE = (1 << 3) _OT_BUILDDIR = os.getenv('top_builddir', '../..') _WPANTUND_PREFIX = os.getenv('WPANTUND_PREFIX', '/usr/local') -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- + def _log(text, new_line=True, flush=True): sys.stdout.write(text) @@ -254,18 +255,20 @@ def _log(text, new_line=True, flush=True): if flush: sys.stdout.flush() -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Node class + class Node(object): """ A wpantund OT NCP instance """ - _VERBOSE = False # defines the default verbosity setting (can be changed per `Node`) + # defines the default verbosity setting (can be changed per `Node`) + _VERBOSE = False _SPEED_UP_FACTOR = 1 # defines the default time speed up factor # path to `wpantund`, `wpanctl`, `ot-ncp-ftd`,`ot-ncp` and `ot-rcp` _WPANTUND = '%s/sbin/wpantund' % _WPANTUND_PREFIX - _WPANCTL = '%s/bin/wpanctl' % _WPANTUND_PREFIX + _WPANCTL = '%s/bin/wpanctl' % _WPANTUND_PREFIX _OT_NCP_FTD = '%s/examples/apps/ncp/ot-ncp-ftd' % _OT_BUILDDIR _OT_NCP_FTD_POSIX_APP = '%s/src/posix/ot-ncp' % _OT_BUILDDIR @@ -276,8 +279,11 @@ class Node(object): # Otherwise, the posix NCP `ot-ncp-ftd` is used _POSIX_APP_ENV_VAR = 'TORANJ_POSIX_APP_RCP_MODEL' - _TUND_LOG_TO_FILE = True # determines if the wpantund logs are saved in file or sent to stdout - _TUND_LOG_FNAME = 'wpantund-logs' # name of wpantund log file (if # name of wpantund _TUND_LOG_TO_FILE is True) + # determines if the wpantund logs are saved in file or sent to stdout + _TUND_LOG_TO_FILE = True + # name of wpantund log file (if # name of wpantund _TUND_LOG_TO_FILE is + # True) + _TUND_LOG_FNAME = 'wpantund-logs' # interface name _INTFC_NAME_PREFIX = 'utun' if sys.platform == 'darwin' else 'wpan' @@ -299,35 +305,40 @@ class Node(object): # Check if env variable `TORANJ_POSIX_APP_RCP_MODEL` is defined # and use it to determine if to use operate in "posix-ncp-app". if self._POSIX_APP_ENV_VAR in os.environ: - self._use_posix_app_with_rcp = (os.environ[self._POSIX_APP_ENV_VAR] in ['1', 'yes']) + self._use_posix_app_with_rcp = ( + os.environ[self._POSIX_APP_ENV_VAR] in ['1', 'yes']) else: self._use_posix_app_with_rcp = False if self._use_posix_app_with_rcp: - ncp_socket_path = 'system:{} -s {} {} {}'.format(self._OT_NCP_FTD_POSIX_APP, self._SPEED_UP_FACTOR, - self._OT_RCP, index) + ncp_socket_path = 'system:{} -s {} {} {}'.format( + self._OT_NCP_FTD_POSIX_APP, self._SPEED_UP_FACTOR, self._OT_RCP, index) else: - ncp_socket_path = 'system:{} {} {}'.format(self._OT_NCP_FTD, index, self._SPEED_UP_FACTOR) + ncp_socket_path = 'system:{} {} {}'.format( + self._OT_NCP_FTD, index, self._SPEED_UP_FACTOR) cmd = self._WPANTUND + \ - ' -o Config:NCP:SocketPath \"{}\"'.format(ncp_socket_path) + \ - ' -o Config:TUN:InterfaceName {}'.format(self._interface_name) + \ - ' -o Config:NCP:DriverName spinel' + \ - ' -o Daemon:SyslogMask \"all -debug\"' + ' -o Config:NCP:SocketPath \"{}\"'.format(ncp_socket_path) + \ + ' -o Config:TUN:InterfaceName {}'.format(self._interface_name) + \ + ' -o Config:NCP:DriverName spinel' + \ + ' -o Daemon:SyslogMask \"all -debug\"' if Node._TUND_LOG_TO_FILE: - self._tund_log_file = open(self._TUND_LOG_FNAME + str(index) + '.log', 'wb') + self._tund_log_file = open( + self._TUND_LOG_FNAME + str(index) + '.log', 'wb') else: self._tund_log_file = None if self._verbose: _log('$ Node{}.__init__() cmd: {}'.format(index, cmd)) - self._wpantund_process = subprocess.Popen(cmd, shell=True, stderr=self._tund_log_file) + self._wpantund_process = subprocess.Popen( + cmd, shell=True, stderr=self._tund_log_file) self._wpanctl_cmd = self._WPANCTL + ' -I ' + self._interface_name + ' ' - self._recvers = weakref.WeakValueDictionary() # map from local_port to `AsyncReceiver` object + # map from local_port to `AsyncReceiver` object + self._recvers = weakref.WeakValueDictionary() Node._all_nodes.add(self) def __del__(self): @@ -337,7 +348,8 @@ class Node(object): self._wpantund_process.wait() def __repr__(self): - return 'Node (index={}, interface_name={})'.format(self._index, self._interface_name) + return 'Node (index={}, interface_name={})'.format( + self._index, self._interface_name) @property def index(self): @@ -355,18 +367,26 @@ class Node(object): def using_posix_app_with_rcp(self): return self._use_posix_app_with_rcp - #------------------------------------------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------------------------------------------ # Executing a `wpanctl` command def wpanctl(self, cmd): """ Runs a wpanctl command on the given wpantund/OT-NCP instance and returns the output """ if self._verbose: - _log('$ Node{}.wpanctl(\'{}\')'.format(self._index, cmd), new_line=False) + _log( + '$ Node{}.wpanctl(\'{}\')'.format( + self._index, + cmd), + new_line=False) - result = subprocess.check_output(self._wpanctl_cmd + cmd, shell=True, stderr=subprocess.STDOUT) + result = subprocess.check_output( + self._wpanctl_cmd + cmd, + shell=True, + stderr=subprocess.STDOUT) - if len(result) >= 1 and result[-1] == '\n': # remove the last char if it is '\n', + if len( + result) >= 1 and result[-1] == '\n': # remove the last char if it is '\n', result = result[:-1] if self._verbose: @@ -379,7 +399,7 @@ class Node(object): return result - #------------------------------------------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------------------------------------------ # APIs matching `wpanctl` commands. def get(self, prop_name, value_only=True): @@ -395,8 +415,8 @@ class Node(object): return self._update_prop('remove', prop_name, value, binary_data) def _update_prop(self, action, prop_name, value, binary_data): - return self.wpanctl(action + ' ' + prop_name + ' ' + ('-d ' if binary_data else '') + - '-v ' + value) # use -v to handle values starting with `-`. + return self.wpanctl(action + ' ' + prop_name + ' ' + ('-d ' if binary_data else '') + + '-v ' + value) # use -v to handle values starting with `-`. def reset(self): return self.wpanctl('reset') @@ -407,43 +427,64 @@ class Node(object): def leave(self): return self.wpanctl('leave') - def form(self, name, channel=None, channel_mask=None, panid=None, xpanid=None, key=None, key_index=None, - node_type=None, mesh_local_prefix=None, legacy_prefix=None): - return self.wpanctl('form \"' + name + '\"' + - (' -c {}'.format(channel) if channel is not None else '') + - (' -m {}'.format(channel_mask) if channel_mask is not None else '') + - (' -p {}'.format(panid) if panid is not None else '') + - (' -x {}'.format(xpanid) if xpanid is not None else '') + - (' -k {}'.format(key) if key is not None else '') + - (' -i {}'.format(key_index) if key_index is not None else '') + - (' -T {}'.format(node_type) if node_type is not None else '') + - (' -M {}'.format(mesh_local_prefix) if mesh_local_prefix is not None else '') + - (' -L {}'.format(legacy_prefix) if legacy_prefix is not None else '')) + def form( + self, + name, + channel=None, + channel_mask=None, + panid=None, + xpanid=None, + key=None, + key_index=None, + node_type=None, + mesh_local_prefix=None, + legacy_prefix=None): + return self.wpanctl('form \"' + name + '\"' + + (' -c {}'.format(channel) if channel is not None else '') + + (' -m {}'.format(channel_mask) if channel_mask is not None else '') + + (' -p {}'.format(panid) if panid is not None else '') + + (' -x {}'.format(xpanid) if xpanid is not None else '') + + (' -k {}'.format(key) if key is not None else '') + + (' -i {}'.format(key_index) if key_index is not None else '') + + (' -T {}'.format(node_type) if node_type is not None else '') + + (' -M {}'.format(mesh_local_prefix) if mesh_local_prefix is not None else '') + + (' -L {}'.format(legacy_prefix) if legacy_prefix is not None else '')) - - def join(self, name, channel=None, node_type=None, panid=None, xpanid=None, key=None): - return self.wpanctl('join \"' + name + '\"' + - (' -c {}'.format(channel) if channel is not None else '') + - (' -T {}'.format(node_type) if node_type is not None else '') + - (' -p {}'.format(panid) if panid is not None else '') + - (' -x {}'.format(xpanid) if xpanid is not None else '') + - (' -k {}'.format(key) if key is not None else '') + - (' -n')) + def join( + self, + name, + channel=None, + node_type=None, + panid=None, + xpanid=None, + key=None): + return self.wpanctl('join \"' + name + '\"' + + (' -c {}'.format(channel) if channel is not None else '') + + (' -T {}'.format(node_type) if node_type is not None else '') + + (' -p {}'.format(panid) if panid is not None else '') + + (' -x {}'.format(xpanid) if xpanid is not None else '') + + (' -k {}'.format(key) if key is not None else '') + + (' -n')) def active_scan(self, channel=None): - return self.wpanctl('scan' + - (' -c {}'.format(channel) if channel is not None else '')) + return self.wpanctl( + 'scan' + (' -c {}'.format(channel) if channel is not None else '')) def energy_scan(self, channel=None): - return self.wpanctl('scan -e' + - (' -c {}'.format(channel) if channel is not None else '')) + return self.wpanctl( + 'scan -e' + (' -c {}'.format(channel) if channel is not None else '')) - def discover_scan(self, channel=None, joiner_only=False, enable_filtering=False, panid_filter=None): - return self.wpanctl('scan -d' + - (' -c {}'.format(channel) if channel is not None else '') + - (' -j' if joiner_only else '') + - (' -e' if enable_filtering else '') + - (' -p {}'.format(panid_filter) if panid_filter is not None else '')) + def discover_scan( + self, + channel=None, + joiner_only=False, + enable_filtering=False, + panid_filter=None): + return self.wpanctl('scan -d' + + (' -c {}'.format(channel) if channel is not None else '') + + (' -j' if joiner_only else '') + + (' -e' if enable_filtering else '') + + (' -p {}'.format(panid_filter) if panid_filter is not None else '')) def permit_join(self, duration_sec=None, port=None, udp=True, tcp=True): if not udp and not tcp: # incorrect use! @@ -456,51 +497,72 @@ class Node(object): if port is not None and duration_sec is None: duration_sec = '240' - return self.wpanctl('permit-join' + - (' {}'.format(duration_sec) if duration_sec is not None else '') + - (' {}'.format(port) if port is not None else '') + - traffic_type) + return self.wpanctl('permit-join' + + (' {}'.format(duration_sec) if duration_sec is not None else '') + + (' {}'.format(port) if port is not None else '') + + traffic_type) def config_gateway(self, prefix, default_route=False, priority=None): - return self.wpanctl('config-gateway ' + prefix + - (' -d' if default_route else '') + - (' -P {}'.format(priority) if priority is not None else '')) + return self.wpanctl('config-gateway ' + prefix + + (' -d' if default_route else '') + + (' -P {}'.format(priority) if priority is not None else '')) - def add_prefix(self, prefix, prefix_len=None, priority=None, stable=True, on_mesh=False, slaac=False, dhcp=False, - configure=False, default_route=False, preferred=False): - return self.wpanctl('add-prefix ' + prefix + - (' -l {}'.format(prefix_len) if prefix_len is not None else '') + - (' -P {}'.format(priority) if priority is not None else '') + - (' -s' if stable else '') + - (' -f' if preferred else '') + - (' -a' if slaac else '') + - (' -d' if dhcp else '') + - (' -c' if configure else '') + - (' -r' if default_route else '') + - (' -o' if on_mesh else '')) + def add_prefix( + self, + prefix, + prefix_len=None, + priority=None, + stable=True, + on_mesh=False, + slaac=False, + dhcp=False, + configure=False, + default_route=False, + preferred=False): + return self.wpanctl('add-prefix ' + prefix + + (' -l {}'.format(prefix_len) if prefix_len is not None else '') + + (' -P {}'.format(priority) if priority is not None else '') + + (' -s' if stable else '') + + (' -f' if preferred else '') + + (' -a' if slaac else '') + + (' -d' if dhcp else '') + + (' -c' if configure else '') + + (' -r' if default_route else '') + + (' -o' if on_mesh else '')) def remove_prefix(self, prefix, prefix_len=None): - return self.wpanctl('remove-prefix ' + prefix + - (' -l {}'.format(prefix_len) if prefix_len is not None else '')) + return self.wpanctl('remove-prefix ' + prefix + + (' -l {}'.format(prefix_len) if prefix_len is not None else '')) - def add_route(self, route_prefix, prefix_len=None, priority=None, stable=True): + def add_route( + self, + route_prefix, + prefix_len=None, + priority=None, + stable=True): """route priority [(>0 for high, 0 for medium, <0 for low)]""" - return self.wpanctl('add-route ' + route_prefix + - (' -l {}'.format(prefix_len) if prefix_len is not None else '') + - (' -p {}'.format(priority) if priority is not None else '') + - ('' if stable else '-n')) + return self.wpanctl('add-route ' + route_prefix + + (' -l {}'.format(prefix_len) if prefix_len is not None else '') + + (' -p {}'.format(priority) if priority is not None else '') + + ('' if stable else '-n')) - def remove_route(self, route_prefix, prefix_len=None, priority=None, stable=True): + def remove_route( + self, + route_prefix, + prefix_len=None, + priority=None, + stable=True): """route priority [(>0 for high, 0 for medium, <0 for low)]""" - return self.wpanctl('remove-route ' + route_prefix + - (' -l {}'.format(prefix_len) if prefix_len is not None else '') + - (' -p {}'.format(priority) if priority is not None else '')) + return self.wpanctl('remove-route ' + route_prefix + + (' -l {}'.format(prefix_len) if prefix_len is not None else '') + + (' -p {}'.format(priority) if priority is not None else '')) def commissioner_start(self): return self.wpanctl('commissioner start') - def commissioner_add_joiner(self, eui64, pskd, timeout = '100'): - return self.wpanctl('commissioner joiner-add {} {} {}'.format(eui64, timeout, pskd)) + def commissioner_add_joiner(self, eui64, pskd, timeout='100'): + return self.wpanctl( + 'commissioner joiner-add {} {} {}'.format(eui64, timeout, pskd)) def joiner_join(self, pskd): return self.wpanctl('joiner --join {}'.format(pskd)) @@ -508,7 +570,7 @@ class Node(object): def joiner_attach(self): return self.wpanctl('joiner --attach') - #------------------------------------------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------------------------------------------ # Helper methods def is_associated(self): @@ -536,7 +598,10 @@ class Node(object): def un_whitelist_node(self, node): """Removes a given node (of node `Node) from the whitelist""" - self.remove(WPAN_MAC_WHITELIST_ENTRIES, node.get(WPAN_EXT_ADDRESS)[1:-1]) + self.remove( + WPAN_MAC_WHITELIST_ENTRIES, + node.get(WPAN_EXT_ADDRESS)[ + 1:-1]) def is_in_scan_result(self, scan_result): """Checks if node is in the scan results @@ -550,12 +615,15 @@ class Node(object): ext_address = self.get(WPAN_EXT_ADDRESS)[1:-1] for item in scan_result: - if all( [item.network_name == name, - item.panid == panid, - item.xpanid == xpanid, - item.channel == channel, - item.ext_address == ext_address, - (item.type == ScanResult.TYPE_DISCOVERY_SCAN) or (item.joinable == joinable) ] ): + if all( + [ + item.network_name == name, + item.panid == panid, + item.xpanid == xpanid, + item.channel == channel, + item.ext_address == ext_address, + (item.type == ScanResult.TYPE_DISCOVERY_SCAN) or ( + item.joinable == joinable)]): return True return False @@ -577,11 +645,13 @@ class Node(object): `prefix_len` is an `int` specifying the prefix length. NOTE: this method uses linux `ip` command. """ - cmd = 'ip -6 addr add '+ address + '/{} dev '.format(prefix_len) + self.interface_name + cmd = 'ip -6 addr add ' + address + \ + '/{} dev '.format(prefix_len) + self.interface_name if self._verbose: _log('$ Node{} \'{}\')'.format(self._index, cmd)) - result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) + result = subprocess.check_output( + cmd, shell=True, stderr=subprocess.STDOUT) return result def remove_ip6_address_on_interface(self, address, prefix_len=64): @@ -590,14 +660,16 @@ class Node(object): `prefix_len` is an `int` specifying the prefix length. NOTE: this method uses linux `ip` command. """ - cmd = 'ip -6 addr del '+ address + '/{} dev '.format(prefix_len) + self.interface_name + cmd = 'ip -6 addr del ' + address + \ + '/{} dev '.format(prefix_len) + self.interface_name if self._verbose: _log('$ Node{} \'{}\')'.format(self._index, cmd)) - result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) + result = subprocess.check_output( + cmd, shell=True, stderr=subprocess.STDOUT) return result - #------------------------------------------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------------------------------------------ # class methods @classmethod @@ -611,7 +683,7 @@ class Node(object): try: node._wpantund_process.poll() if node._wpantund_process.returncode is not None: - print 'Node {} wpantund instance has terminated unexpectedly'.format(node) + print('Node {} wpantund instance has terminated unexpectedly'.format(node)) if disable_logs: node.set(WPAN_OT_LOG_LEVEL, '0') node.leave() @@ -620,9 +692,9 @@ class Node(object): _log(' -> \'{}\' exit code: {}'.format(e.output, e.returncode)) interval = time.time() - start_time if interval > wait_time: - print 'Took too long to init node {} ({}>{} sec)'.format(node, interval, wait_time) + print('Took too long to init node {} ({}>{} sec)'.format(node, interval, wait_time)) raise - except: + except BaseException: raise else: break @@ -639,10 +711,11 @@ class Node(object): def set_time_speedup_factor(cls, factor): """Sets up the time speed up factor - should be set before creating any `Node` objects""" if len(Node._all_nodes) != 0: - raise Node._NodeError('set_time_speedup_factor() cannot be called after creating a `Node`') + raise Node._NodeError( + 'set_time_speedup_factor() cannot be called after creating a `Node`') Node._SPEED_UP_FACTOR = factor - #------------------------------------------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------------------------------------------ # IPv6 message Sender and Receiver class class _NodeError(Exception): @@ -682,10 +755,19 @@ class Node(object): else: msg = data - return AsyncSender(self, src_addr, src_port, dst_addr, dst_port, msg, count, mcast_hops) + return AsyncSender( + self, + src_addr, + src_port, + dst_addr, + dst_port, + msg, + count, + mcast_hops) def _get_receiver(self, local_port): - # Gets or creates a receiver (an `AsyncReceiver`) tied to given port number + # Gets or creates a receiver (an `AsyncReceiver`) tied to given port + # number if local_port in self._recvers: receiver = self._recvers[local_port] else: @@ -694,7 +776,8 @@ class Node(object): return receiver def _remove_recver(self, recvr): - # Removes a receiver from weak dictionary - called when the receiver is done and its socket is closed + # Removes a receiver from weak dictionary - called when the receiver is + # done and its socket is closed local_port = recvr.local_port if local_port in self._recvers: del self._recvers[local_port] @@ -702,7 +785,11 @@ class Node(object): def prepare_rx(self, sender): """Prepare to receive messages from a sender (an `AsyncSender`)""" receiver = self._get_receiver(sender.dst_port) - receiver._add_sender(sender.src_addr, sender.src_port, sender.msg, sender.count) + receiver._add_sender( + sender.src_addr, + sender.src_port, + sender.msg, + sender.count) return receiver def preapre_listener(self, local_port, timeout=1): @@ -719,33 +806,48 @@ class Node(object): while asyncore.socket_map: elapsed_time = time.time() - start_time if elapsed_time > timeout: - print 'Performing aysnc tx/tx took too long ({}>{} sec)'.format(elapsed_time, timeout) - raise Node._NodeError('perform_tx_rx timed out ({}>{} sec)'.format(elapsed_time, timeout)) + print('Performing aysnc tx/tx took too long ({}>{} sec)'.format(elapsed_time, timeout)) + raise Node._NodeError( + 'perform_tx_rx timed out ({}>{} sec)'.format( + elapsed_time, timeout)) # perform a single asyncore loop asyncore.loop(timeout=0.5, count=1) - except: - print 'Failed to perform async rx/tx' + except BaseException: + print('Failed to perform async rx/tx') raise -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # `AsyncSender` and `AsyncReceiver classes + _SO_BINDTODEVICE = 25 + def _is_ipv6_addr_link_local(ip_addr): """Indicates if a given IPv6 address is link-local""" return ip_addr.lower().startswith('fe80::') + def _create_socket_address(ip_address, port): """Convert a given IPv6 address (string) and port number into a socket address""" # `socket.getaddrinfo()` returns a list of `(family, socktype, proto, canonname, sockaddr)` where `sockaddr` # (at index 4) can be used as input in socket methods (like `sendto()`, `bind()`, etc.). return socket.getaddrinfo(ip_address, port)[0][4] + class AsyncSender(asyncore.dispatcher): """ An IPv6 async message sender - use `Node.prepare_tx()` to create one""" - def __init__(self, node, src_addr, src_port, dst_addr, dst_port, msg, count, mcast_hops=None): + def __init__( + self, + node, + src_addr, + src_port, + dst_addr, + dst_port, + msg, + count, + mcast_hops=None): self._node = node self._src_addr = src_addr self._src_port = src_port @@ -759,17 +861,25 @@ class AsyncSender(asyncore.dispatcher): # Create a socket, bind it to the node's interface sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) - sock.setsockopt(socket.SOL_SOCKET, _SO_BINDTODEVICE, node.interface_name + '\0') + sock.setsockopt( + socket.SOL_SOCKET, + _SO_BINDTODEVICE, + node.interface_name + '\0') sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # Set the IPV6_MULTICAST_HOPS if mcast_hops is not None: - sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, mcast_hops) + sock.setsockopt( + socket.IPPROTO_IPV6, + socket.IPV6_MULTICAST_HOPS, + mcast_hops) # Bind the socket to the given src address if _is_ipv6_addr_link_local(src_addr): - # If src is a link local address it requires the interface name to be specified. - src_sock_addr = _create_socket_address(src_addr + '%' + node.interface_name, src_port) + # If src is a link local address it requires the interface name to + # be specified. + src_sock_addr = _create_socket_address( + src_addr + '%' + node.interface_name, src_port) else: src_sock_addr = _create_socket_address(src_addr, src_port) sock.bind(src_sock_addr) @@ -824,12 +934,18 @@ class AsyncSender(asyncore.dispatcher): if self._node._verbose: if sent_len < 30: - info_text = '{} bytes ("{}")'.format(sent_len, self._tx_buffer[:sent_len]) + info_text = '{} bytes ("{}")'.format( + sent_len, self._tx_buffer[:sent_len]) else: info_text = '{} bytes'.format(sent_len) - _log('- Node{} sent {} to [{}]:{} from [{}]:{}'.format(self._node._index, info_text, - self._dst_addr, self._dst_port, - self._src_addr, self._src_port)) + _log( + '- Node{} sent {} to [{}]:{} from [{}]:{}'.format( + self._node._index, + info_text, + self._dst_addr, + self._dst_port, + self._src_addr, + self._src_port)) self._tx_buffer = self._tx_buffer[sent_len:] @@ -843,7 +959,8 @@ class AsyncSender(asyncore.dispatcher): def handle_close(self): self.close() -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + class AsyncReceiver(asyncore.dispatcher): """ An IPv6 async message receiver - use `prepare_rx()` to create one""" @@ -870,14 +987,19 @@ class AsyncReceiver(asyncore.dispatcher): self._node = node self._local_port = local_port self._senders = [] # list of `_SenderInfo` objects - self._all_rx = [] # contains all received messages as a list of (pkt, (src_addr, src_port)) + # contains all received messages as a list of (pkt, (src_addr, + # src_port)) + self._all_rx = [] self._timeout = 0 # listen timeout (zero means forever) self._started = False self._start_time = 0 # Create a socket, bind it to the node's interface sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) - sock.setsockopt(socket.SOL_SOCKET, _SO_BINDTODEVICE, node.interface_name + '\0') + sock.setsockopt( + socket.SOL_SOCKET, + _SO_BINDTODEVICE, + node.interface_name + '\0') sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # Bind the socket to any IPv6 address with the given local port @@ -887,7 +1009,9 @@ class AsyncReceiver(asyncore.dispatcher): asyncore.dispatcher.__init__(self, sock) def _add_sender(self, sender_addr, sender_port, msg, count): - self._senders.append(AsyncReceiver._SenderInfo(sender_addr, sender_port, msg, count)) + self._senders.append( + AsyncReceiver._SenderInfo( + sender_addr, sender_port, msg, count)) def _set_listen_timeout(self, timeout): self._timeout = timeout @@ -910,7 +1034,8 @@ class AsyncReceiver(asyncore.dispatcher): @property def was_successful(self): """Indicates if all expected IPv6 messages were received successfully""" - return len(self._senders) == 0 or all([sender._did_recv_all() for sender in self._senders]) + return len(self._senders) == 0 or all( + [sender._did_recv_all() for sender in self._senders]) # asyncore.dispatcher callbacks @@ -936,43 +1061,55 @@ class AsyncReceiver(asyncore.dispatcher): if (_is_ipv6_addr_link_local(src_addr)): if '%' in src_addr: - src_addr = src_addr.split('%')[0] # remove the interface name from address + # remove the interface name from address + src_addr = src_addr.split('%')[0] if self._node._verbose: if len(msg) < 30: info_text = '{} bytes ("{}")'.format(len(msg), msg) else: info_text = '{} bytes'.format(len(msg)) - _log('- Node{} received {} on port {} from [{}]:{}'.format(self._node._index, info_text, - self._local_port, - src_addr, src_port)) + _log( + '- Node{} received {} on port {} from [{}]:{}'.format( + self._node._index, + info_text, + self._local_port, + src_addr, + src_port)) self._all_rx.append((msg, (src_addr, src_port))) - if all([sender._check_received(msg, src_addr, src_port) for sender in self._senders]): + if all([sender._check_received(msg, src_addr, src_port) + for sender in self._senders]): self.handle_close() def handle_close(self): self.close() - # remove the receiver from the node once the socket is closed + # remove the receiver from the node once the socket is closed self._node._remove_recver(self) -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- + + class VerifyError(Exception): pass + _is_in_verify_within = False + def verify(condition): """Verifies that a `condition` is true, otherwise raises a VerifyError""" global _is_in_verify_within if not condition: calling_frame = inspect.currentframe().f_back - error_message = 'verify() failed at line {} in "{}"'.format(calling_frame.f_lineno, calling_frame.f_code.co_filename) + error_message = 'verify() failed at line {} in "{}"'.format( + calling_frame.f_lineno, calling_frame.f_code.co_filename) if not _is_in_verify_within: - print error_message + print(error_message) raise VerifyError(error_message) + def verify_within(condition_checker_func, wait_time, delay_time=0.1): """Verifies that a given function `condition_checker_func` passes successfully within a given wait timeout. `wait_time` is maximum time waiting for condition_checker to pass (in seconds). @@ -987,10 +1124,10 @@ def verify_within(condition_checker_func, wait_time, delay_time=0.1): condition_checker_func() except VerifyError as e: if time.time() - start_time > wait_time: - print 'Took too long to pass the condition ({}>{} sec)'.format(time.time() - start_time, wait_time) - print e.message + print('Took too long to pass the condition ({}>{} sec)'.format(time.time() - start_time, wait_time)) + print(e.message) raise e - except: + except BaseException: raise else: break @@ -998,46 +1135,49 @@ def verify_within(condition_checker_func, wait_time, delay_time=0.1): time.sleep(delay_time) _is_in_verify_within = old_is_in_verify_within -#----------------------------------------------------------------------------------------------------------------------- +# ----------------------------------------------------------------------------------------------------------------------- # Parsing `wpanctl` output -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class ScanResult(object): """ This object encapsulates a scan result (active/discover/energy scan)""" - TYPE_ACTIVE_SCAN = 'active-scan' - TYPE_DISCOVERY_SCAN = 'discover-scan' - TYPE_ENERGY_SCAN = 'energy-scan' + TYPE_ACTIVE_SCAN = 'active-scan' + TYPE_DISCOVERY_SCAN = 'discover-scan' + TYPE_ENERGY_SCAN = 'energy-scan' def __init__(self, result_text): items = [item.strip() for item in result_text.split('|')] if len(items) == 8: - self._type = ScanResult.TYPE_ACTIVE_SCAN - self._index = items[0] - self._joinable = (items[1] == 'YES') + self._type = ScanResult.TYPE_ACTIVE_SCAN + self._index = items[0] + self._joinable = (items[1] == 'YES') self._network_name = items[2][1:-1] - self._panid = items[3] - self._channel = items[4] - self._xpanid = items[5] - self._ext_address = items[6] - self._rssi = items[7] + self._panid = items[3] + self._channel = items[4] + self._xpanid = items[5] + self._ext_address = items[6] + self._rssi = items[7] elif len(items) == 7: - self._type = ScanResult.TYPE_DISCOVERY_SCAN - self._index = items[0] + self._type = ScanResult.TYPE_DISCOVERY_SCAN + self._index = items[0] self._network_name = items[1][1:-1] - self._panid = items[2] - self._channel = items[3] - self._xpanid = items[4] - self._ext_address = items[5] - self._rssi = items[6] + self._panid = items[2] + self._channel = items[3] + self._xpanid = items[4] + self._ext_address = items[5] + self._rssi = items[6] elif len(items) == 2: - self._type = ScanResult.TYPE_ENERGY_SCAN - self._channel = items[0] - self._rssi = items[1] + self._type = ScanResult.TYPE_ENERGY_SCAN + self._channel = items[0] + self._rssi = items[1] else: - raise ValueError('"{}" does not seem to be a valid scan result string'.result_text) + raise ValueError( + '"{}" does not seem to be a valid scan result string'.result_text) @property def type(self): @@ -1074,9 +1214,12 @@ class ScanResult(object): def __repr__(self): return 'ScanResult({})'.format(self.__dict__) + def parse_scan_result(scan_result): """ Parses scan result string and returns an array of `ScanResult` objects""" - return [ ScanResult(item) for item in scan_result.split('\n')[2:] ] # skip first two lines which are table headers + return [ScanResult(item) for item in scan_result.split( + '\n')[2:]] # skip first two lines which are table headers + def parse_list(list_string): """ @@ -1097,7 +1240,9 @@ def parse_list(list_string): # return [line[2:-1].split()[0] for line in list_string.split('\n')[1:-1]] -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class OnMeshPrefix(object): """ This object encapsulates an on-mesh prefix""" @@ -1108,25 +1253,26 @@ class OnMeshPrefix(object): # '\t"fd00:abba:cafe:: prefix_len:64 origin:user stable:yes flags:0x31' # ' [on-mesh:1 def-route:0 config:0 dhcp:0 slaac:1 pref:1 prio:med] rloc:0x0000"' - m = re.match('\t"([0-9a-fA-F:]+)\s*prefix_len:(\d+)\s+origin:(\w*)\s+stable:(\w*).* \[' + - 'on-mesh:(\d)\s+def-route:(\d)\s+config:(\d)\s+dhcp:(\d)\s+slaac:(\d)\s+pref:(\d)\s+prio:(\w*)\]' + - '\s+rloc:(0x[0-9a-fA-F]+)', - text) + m = re.match( + r'\t"([0-9a-fA-F:]+)\s*prefix_len:(\d+)\s+origin:(\w*)\s+stable:(\w*).* \[' + + r'on-mesh:(\d)\s+def-route:(\d)\s+config:(\d)\s+dhcp:(\d)\s+slaac:(\d)\s+pref:(\d)\s+prio:(\w*)\]' + + r'\s+rloc:(0x[0-9a-fA-F]+)', + text) verify(m is not None) data = m.groups() - self._prefix = data[0] + self._prefix = data[0] self._prefix_len = data[1] - self._origin = data[2] - self._stable = (data[3] == 'yes') - self._on_mesh = (data[4] == '1') - self._def_route = (data[5] == '1') - self._config = (data[6] == '1') - self._dhcp = (data[7] == '1') - self._slaac = (data[8] == '1') - self._preferred = (data[9] == '1') - self._priority = (data[10]) - self._rloc16 = (data[11]) + self._origin = data[2] + self._stable = (data[3] == 'yes') + self._on_mesh = (data[4] == '1') + self._def_route = (data[5] == '1') + self._config = (data[6] == '1') + self._dhcp = (data[7] == '1') + self._slaac = (data[8] == '1') + self._preferred = (data[9] == '1') + self._priority = (data[10]) + self._rloc16 = (data[11]) @property def prefix(self): @@ -1171,11 +1317,15 @@ class OnMeshPrefix(object): def __repr__(self): return 'OnMeshPrefix({})'.format(self.__dict__) + def parse_on_mesh_prefix_result(on_mesh_prefix_list): """ Parses on-mesh prefix list string and returns an array of `OnMeshPrefix` objects""" - return [ OnMeshPrefix(item) for item in on_mesh_prefix_list.split('\n')[1:-1] ] + return [OnMeshPrefix(item) + for item in on_mesh_prefix_list.split('\n')[1:-1]] + +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class ChildEntry(object): """ This object encapsulates a child entry""" @@ -1189,19 +1339,23 @@ class ChildEntry(object): # We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator. # Then remove any ',' at end of items in the list. - items = [item[:-1] if item[-1] ==',' else item for item in text[2:-1].split()] + items = [ + item[:-1] if item[-1] == ',' else item + for item in text[2:-1].split() + ] # First item in the extended address self._ext_address = items[0] - # Convert the rest into a dictionary by splitting using ':' as separator - dict = {item.split(':')[0] : item.split(':')[1] for item in items[1:]} + # Convert the rest into a dictionary by splitting using ':' as + # separator + dict = {item.split(':')[0]: item.split(':')[1] for item in items[1:]} - self._rloc16 = dict['RLOC16'] - self._timeout = dict['Timeout'] - self._rx_on_idle = (dict['RxOnIdle'] == 'yes') - self._ftd = (dict['FTD'] == 'yes') - self._sec_data_req = (dict['SecDataReq'] == 'yes') + self._rloc16 = dict['RLOC16'] + self._timeout = dict['Timeout'] + self._rx_on_idle = (dict['RxOnIdle'] == 'yes') + self._ftd = (dict['FTD'] == 'yes') + self._sec_data_req = (dict['SecDataReq'] == 'yes') self._full_net_data = (dict['FullNetData'] == 'yes') @property @@ -1231,11 +1385,14 @@ class ChildEntry(object): def __repr__(self): return 'ChildEntry({})'.format(self.__dict__) + def parse_child_table_result(child_table_list): """ Parses child table list string and returns an array of `ChildEntry` objects""" - return [ ChildEntry(item) for item in child_table_list.split('\n')[1:-1] ] + return [ChildEntry(item) for item in child_table_list.split('\n')[1:-1]] + +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class NeighborEntry(object): """ This object encapsulates a neighbor entry""" @@ -1243,24 +1400,28 @@ class NeighborEntry(object): # Example of expected text: # - # `\t"5AC95ED4646D6565, RLOC16:9403, LQIn:3, AveRssi:-20, LastRssi:-20, Age:0, LinkFC:8, MleFC:0, IsChild:yes, ' + # `\t"5AC95ED4646D6565, RLOC16:9403, LQIn:3, AveRssi:-20, LastRssi:-20, Age:0, LinkFC:8, MleFC:0, IsChild:yes,' # 'RxOnIdle:no, FTD:no, SecDataReq:yes, FullNetData:yes"' # # We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator. # Then remove any ',' at end of items in the list. - items = [item[:-1] if item[-1] ==',' else item for item in text[2:-1].split()] + items = [ + item[:-1] if item[-1] == ',' else item + for item in text[2:-1].split() + ] # First item in the extended address self._ext_address = items[0] - # Convert the rest into a dictionary by splitting the text using ':' as separator - dict = {item.split(':')[0] : item.split(':')[1] for item in items[1:]} + # Convert the rest into a dictionary by splitting the text using ':' as + # separator + dict = {item.split(':')[0]: item.split(':')[1] for item in items[1:]} - self._rloc16 = dict['RLOC16'] - self._is_child = (dict['IsChild'] == 'yes') + self._rloc16 = dict['RLOC16'] + self._is_child = (dict['IsChild'] == 'yes') self._rx_on_idle = (dict['RxOnIdle'] == 'yes') - self._ftd = (dict['FTD'] == 'yes') + self._ftd = (dict['FTD'] == 'yes') @property def ext_address(self): @@ -1282,11 +1443,15 @@ class NeighborEntry(object): def __repr__(self): return 'NeighborEntry({})'.format(self.__dict__) + def parse_neighbor_table_result(neighbor_table_list): """ Parses neighbor table list string and returns an array of `NeighborEntry` objects""" - return [ NeighborEntry(item) for item in neighbor_table_list.split('\n')[1:-1] ] + return [NeighborEntry(item) + for item in neighbor_table_list.split('\n')[1:-1]] + +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class RouterTableEntry(object): """ This object encapsulates a router table entry""" @@ -1299,20 +1464,24 @@ class RouterTableEntry(object): # We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator. # Then remove any ',' at end of items in the list. - items = [item[:-1] if item[-1] ==',' else item for item in text[2:-1].split()] + items = [ + item[:-1] if item[-1] == ',' else item + for item in text[2:-1].split() + ] # First item in the extended address self._ext_address = items[0] - # Convert the rest into a dictionary by splitting the text using ':' as separator - dict = {item.split(':')[0] : item.split(':')[1] for item in items[1:]} + # Convert the rest into a dictionary by splitting the text using ':' as + # separator + dict = {item.split(':')[0]: item.split(':')[1] for item in items[1:]} - self._rloc16 = int(dict['RLOC16'], 16) + self._rloc16 = int(dict['RLOC16'], 16) self._router_id = int(dict['RouterId'], 0) - self._next_hop = int(dict['NextHop'], 0) + self._next_hop = int(dict['NextHop'], 0) self._path_cost = int(dict['PathCost'], 0) - self._age = int(dict['Age'], 0) - self._le = (dict['LinkEst'] == 'yes') + self._age = int(dict['Age'], 0) + self._le = (dict['LinkEst'] == 'yes') @property def ext_address(self): @@ -1340,11 +1509,15 @@ class RouterTableEntry(object): def __repr__(self): return 'RouterTableEntry({})'.format(self.__dict__) + def parse_router_table_result(router_table_list): """ Parses router table list string and returns an array of `RouterTableEntry` objects""" - return [ RouterTableEntry(item) for item in router_table_list.split('\n')[1:-1] ] + return [RouterTableEntry(item) + for item in router_table_list.split('\n')[1:-1]] + +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + -#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class AddressCacheEntry(object): """ This object encapsulates an address cache entry""" @@ -1357,16 +1530,20 @@ class AddressCacheEntry(object): # We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator. # Then remove any ',' at end of items in the list. - items = [item[:-1] if item[-1] ==',' else item for item in text[2:-1].split()] + items = [ + item[:-1] if item[-1] == ',' else item + for item in text[2:-1].split() + ] # First item in the extended address self._address = items[0] - self._rloc16 = int(items[2], 16) + self._rloc16 = int(items[2], 16) - # Convert the rest into a dictionary by splitting the text using ':' as separator - dict = {item.split(':')[0] : item.split(':')[1] for item in items[3:]} + # Convert the rest into a dictionary by splitting the text using ':' as + # separator + dict = {item.split(':')[0]: item.split(':')[1] for item in items[3:]} - self._age = int(dict['age'], 0) + self._age = int(dict['age'], 0) @property def address(self): @@ -1383,6 +1560,8 @@ class AddressCacheEntry(object): def __repr__(self): return 'AddressCacheEntry({})'.format(self.__dict__) + def parse_address_cache_table_result(addr_cache_table_list): """ Parses address cache table list string and returns an array of `AddressCacheEntry` objects""" - return [ AddressCacheEntry(item) for item in addr_cache_table_list.split('\n')[1:-1] ] + return [AddressCacheEntry(item) + for item in addr_cache_table_list.split('\n')[1:-1]] diff --git a/tools/harness-automation/autothreadharness/exceptions.py b/tools/harness-automation/autothreadharness/exceptions.py index e299cc7a8..b0025f7ec 100644 --- a/tools/harness-automation/autothreadharness/exceptions.py +++ b/tools/harness-automation/autothreadharness/exceptions.py @@ -27,17 +27,17 @@ # POSSIBILITY OF SUCH DAMAGE. # + class FailError(Exception): """This error class is the base for all errors that cause the current test case fails. """ - pass + class FatalError(FailError): """This error class is the base for all errors that cause the whole test procedure stops. """ - pass + class GoldenDeviceNotEnoughError(FailError): """Raised when no more golden devices are available for trying. """ - pass diff --git a/tools/harness-automation/autothreadharness/harness_case.py b/tools/harness-automation/autothreadharness/harness_case.py index f303c06c9..62d6c9aec 100644 --- a/tools/harness-automation/autothreadharness/harness_case.py +++ b/tools/harness-automation/autothreadharness/harness_case.py @@ -36,6 +36,9 @@ import re import time import unittest +from builtins import input +from functools import reduce + from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.support.ui import Select @@ -43,7 +46,11 @@ from selenium.common.exceptions import UnexpectedAlertPresentException from selenium.common.exceptions import NoSuchElementException from autothreadharness import settings -from autothreadharness.exceptions import FailError, FatalError, GoldenDeviceNotEnoughError +from autothreadharness.exceptions import ( + FailError, + FatalError, + GoldenDeviceNotEnoughError, +) from autothreadharness.harness_controller import HarnessController from autothreadharness.helpers import HistoryHelper from autothreadharness.open_thread_controller import OpenThreadController @@ -61,6 +68,7 @@ THREAD_CHANNEL_MIN = 11 DEFAULT_TIMEOUT = 2700 """Timeout for each test case in seconds""" + def wait_until(what, times=-1): """Wait until `what` return True @@ -77,7 +85,7 @@ def wait_until(what, times=-1): try: if what() is True: return True - except: + except BaseException: logger.exception('Wait failed') else: logger.warning('Trial[%d] failed', times) @@ -86,6 +94,7 @@ def wait_until(what, times=-1): return False + class HarnessCase(unittest.TestCase): """This is the case class of all automation test cases. @@ -98,16 +107,16 @@ class HarnessCase(unittest.TestCase): Thread channel ranges from 11 to 26. """ - ROLE_LEADER = 1 - ROLE_ROUTER = 2 - ROLE_SED = 4 - ROLE_BORDER = 8 - ROLE_REED = 16 - ROLE_ED = 32 - ROLE_COMMISSIONER = 64 - ROLE_JOINER = 128 - ROLE_FED = 512 - ROLE_MED = 1024 + ROLE_LEADER = 1 + ROLE_ROUTER = 2 + ROLE_SED = 4 + ROLE_BORDER = 8 + ROLE_REED = 16 + ROLE_ED = 32 + ROLE_COMMISSIONER = 64 + ROLE_JOINER = 128 + ROLE_FED = 512 + ROLE_MED = 1024 role = None """int: role id. @@ -151,7 +160,9 @@ class HarnessCase(unittest.TestCase): auto_dut = settings.AUTO_DUT """bool: whether use harness auto dut feature""" - timeout = hasattr(settings, 'TIMEOUT') and settings.TIMEOUT or DEFAULT_TIMEOUT + timeout = ( + hasattr(settings, 'TIMEOUT') and settings.TIMEOUT or DEFAULT_TIMEOUT + ) """number: timeout in seconds to stop running this test case""" started = 0 @@ -161,7 +172,10 @@ class HarnessCase(unittest.TestCase): self.dut = None self._browser = None self._hc = None - self.result_dir = '%s\\%s' % (settings.OUTPUT_PATH, self.__class__.__name__) + self.result_dir = '%s\\%s' % ( + settings.OUTPUT_PATH, + self.__class__.__name__, + ) self.history = HistoryHelper() self.add_all_devices = False @@ -183,7 +197,7 @@ class HarnessCase(unittest.TestCase): with OpenThreadController(port) as otc: logger.info('Resetting %s', port) otc.reset() - except: + except BaseException: logger.exception('Failed to reset device %s', port) self.history.mark_bad_golden_device(device) @@ -194,7 +208,9 @@ class HarnessCase(unittest.TestCase): while True: try: - pdu = pdu_factory.create_pdu_controller(settings.PDU_CONTROLLER_TYPE) + pdu = pdu_factory.create_pdu_controller( + settings.PDU_CONTROLLER_TYPE + ) pdu.open(**settings.PDU_CONTROLLER_OPEN_PARAMS) except EOFError: logger.warning('Failed to connect to telnet') @@ -224,16 +240,32 @@ class HarnessCase(unittest.TestCase): time.sleep(2) harness_config = ConfigParser.ConfigParser() - harness_config.read('%s\\Config\\Configuration.ini' % settings.HARNESS_HOME) - if harness_config.has_option('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate') and \ - harness_config.getboolean('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate'): - logger.error('BrowserAutoNavigate in Configuration.ini should be False') - raise FailError('BrowserAutoNavigate in Configuration.ini should be False') + harness_config.read( + '%s\\Config\\Configuration.ini' % settings.HARNESS_HOME + ) + if harness_config.has_option( + 'THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate' + ) and harness_config.getboolean( + 'THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate' + ): + logger.error( + 'BrowserAutoNavigate in Configuration.ini should be False' + ) + raise FailError( + 'BrowserAutoNavigate in Configuration.ini should be False' + ) if settings.MIXED_DEVICE_TYPE: - if harness_config.has_option('THREAD_HARNESS_CONFIG', 'EnableDeviceSelection') and \ - not harness_config.getboolean('THREAD_HARNESS_CONFIG', 'EnableDeviceSelection'): - logger.error('EnableDeviceSelection in Configuration.ini should be True') - raise FailError('EnableDeviceSelection in Configuration.ini should be True') + if harness_config.has_option( + 'THREAD_HARNESS_CONFIG', 'EnableDeviceSelection' + ) and not harness_config.getboolean( + 'THREAD_HARNESS_CONFIG', 'EnableDeviceSelection' + ): + logger.error( + 'EnableDeviceSelection in Configuration.ini should be True' + ) + raise FailError( + 'EnableDeviceSelection in Configuration.ini should be True' + ) def _destroy_harness(self): """Stop harness backend service @@ -271,9 +303,10 @@ class HarnessCase(unittest.TestCase): chrome_options.add_argument('--disable-extensions') chrome_options.add_argument('--disable-infobars') chrome_options.add_argument('--ignore-certificate-errors') - chrome_options.add_experimental_option('prefs', { - 'profile.managed_default_content_settings.notifications': 1 - }) + chrome_options.add_experimental_option( + 'prefs', + {'profile.managed_default_content_settings.notifications': 1}, + ) browser = webdriver.Chrome(chrome_options=chrome_options) browser.set_page_load_timeout(10) @@ -291,10 +324,12 @@ class HarnessCase(unittest.TestCase): self._browser = None def _init_rf_shield(self): - if getattr(settings, 'SHIELD_CONTROLLER_TYPE', None) and getattr(settings, 'SHIELD_CONTROLLER_PARAMS', None): + if getattr(settings, 'SHIELD_CONTROLLER_TYPE', None) and getattr( + settings, 'SHIELD_CONTROLLER_PARAMS', None + ): self.rf_shield = get_rf_shield_controller( shield_type=settings.SHIELD_CONTROLLER_TYPE, - params=settings.SHIELD_CONTROLLER_PARAMS + params=settings.SHIELD_CONTROLLER_PARAMS, ) else: self.rf_shield = None @@ -315,13 +350,17 @@ class HarnessCase(unittest.TestCase): logger.info('Deleting all .pdf') os.system('del /q "%HOMEDRIVE%%HOMEPATH%\\Downloads\\NewPdf_*.pdf"') logger.info('Deleting all .xlsx') - os.system('del /q "%HOMEDRIVE%%HOMEPATH%\\Downloads\\ExcelReport*.xlsx"') + os.system( + 'del /q "%HOMEDRIVE%%HOMEPATH%\\Downloads\\ExcelReport*.xlsx"' + ) logger.info('Deleting all .pcapng') os.system('del /q "%s\\Captures\\*.pcapng"' % settings.HARNESS_HOME) # using temp files to fix excel downloading fail logger.info('Empty files in temps') - os.system('del /q "%s\\Thread_Harness\\temp\\*.*"' % settings.HARNESS_HOME) + os.system( + 'del /q "%s\\Thread_Harness\\temp\\*.*"' % settings.HARNESS_HOME + ) # create directory os.system('mkdir %s' % self.result_dir) @@ -350,33 +389,41 @@ class HarnessCase(unittest.TestCase): if not self.started: self.started = time.time() - if time.time() - self.started > 5*len(settings.GOLDEN_DEVICES): + if time.time() - self.started > 5 * len(settings.GOLDEN_DEVICES): self._browser.refresh() return # Detect Sniffer try: dialog = self._browser.find_element_by_id('capture-Setup-modal') - except: + except BaseException: logger.exception('Failed to get dialog.') else: if dialog and dialog.get_attribute('aria-hidden') == 'false': times = 100 while times: - status = dialog.find_element_by_class_name('status-notify').text + status = dialog.find_element_by_class_name( + 'status-notify' + ).text if 'Searching' in status: logger.info('Still detecting..') elif 'Not' in status: logger.warning('Sniffer device not verified!') - button = dialog.find_element_by_id('snifferAutoDetectBtn') + button = dialog.find_element_by_id( + 'snifferAutoDetectBtn' + ) button.click() elif 'Verified' in status: logger.info('Verified!') - button = dialog.find_element_by_id('saveCaptureSettings') + button = dialog.find_element_by_id( + 'saveCaptureSettings' + ) button.click() break else: - logger.warning('Unexpected sniffer verification status') + logger.warning( + 'Unexpected sniffer verification status' + ) times = times - 1 time.sleep(1) @@ -391,12 +438,12 @@ class HarnessCase(unittest.TestCase): if skip_button.is_enabled(): skip_button.click() time.sleep(1) - except: + except BaseException: logger.info('Still detecting sniffers') try: next_button = self._browser.find_element_by_id('nextButton') - except: + except BaseException: logger.exception('Failed to finish setup') return @@ -412,16 +459,22 @@ class HarnessCase(unittest.TestCase): button.click() time.sleep(2) - dialog = self._browser.find_element_by_id('general-Setup-modal') + dialog = self._browser.find_element_by_id( + 'general-Setup-modal' + ) if dialog.get_attribute('aria-hidden') != 'false': raise Exception('Missing General Setup dialog') - field = dialog.find_element_by_id('inp_general_child_update_wait_time') + field = dialog.find_element_by_id( + 'inp_general_child_update_wait_time' + ) field.clear() if self.child_timeout: field.send_keys(str(self.child_timeout)) - field = dialog.find_element_by_id('inp_general_sed_polling_rate') + field = dialog.find_element_by_id( + 'inp_general_sed_polling_rate' + ) field.clear() if self.sed_polling_interval: field.send_keys(str(self.sed_polling_interval)) @@ -430,7 +483,7 @@ class HarnessCase(unittest.TestCase): button.click() time.sleep(1) - except: + except BaseException: logger.info('general setup exception') logger.exception('Failed to do general setup') return @@ -478,28 +531,39 @@ class HarnessCase(unittest.TestCase): selected_hw_num = len(selected_hw_set) while selected_hw_num: - remove_button = selected_hw_set[selected_hw_num - 1].find_element_by_class_name( - 'removeSelectedDevice') + remove_button = selected_hw_set[ + selected_hw_num - 1 + ].find_element_by_class_name('removeSelectedDevice') remove_button.click() selected_hw_num = selected_hw_num - 1 - devices = [device for device in settings.GOLDEN_DEVICES - if not self.history.is_bad_golden_device(device[0]) and \ - not (settings.DUT_DEVICE and device[0] == settings.DUT_DEVICE[0])] - logger.info('Available golden devices: %s', json.dumps(devices, indent=2)) + devices = [ + device + for device in settings.GOLDEN_DEVICES + if not self.history.is_bad_golden_device(device[0]) + and not ( + settings.DUT_DEVICE and device[0] == settings.DUT_DEVICE[0] + ) + ] + logger.info( + 'Available golden devices: %s', json.dumps(devices, indent=2) + ) golden_devices_required = self.golden_devices_required # for test bed with mixed devices if settings.MIXED_DEVICE_TYPE: - topo_file = settings.HARNESS_HOME+"\\Thread_Harness\\TestScripts\\TopologyConfig.txt" + topo_file = ( + settings.HARNESS_HOME + + "\\Thread_Harness\\TestScripts\\TopologyConfig.txt" + ) try: f_topo = open(topo_file, 'r') - except IOError as e: + except IOError: logger.info('%s can NOT be found', topo_file) raise GoldenDeviceNotEnoughError() topo_mixed_devices = [] try: - while 1: + while True: topo_line = f_topo.readline().strip() if re.match(r'#.*', topo_line): continue @@ -509,7 +573,9 @@ class HarnessCase(unittest.TestCase): case_id = match_line.group(1) if re.sub(r'\.', ' ', case_id) == self.case: - logger.info('Get line by case %s: %s', case_id, topo_line) + logger.info( + 'Get line by case %s: %s', case_id, topo_line + ) topo_device_list = re.split(',', match_line.group(2)) for i in range(len(topo_device_list)): topo_device = re.split(':', topo_device_list[i]) @@ -518,9 +584,15 @@ class HarnessCase(unittest.TestCase): else: continue except Exception as e: - logger.info('Get devices from topology config file error: %s', e) + logger.info( + 'Get devices from topology config file error: %s', e + ) raise GoldenDeviceNotEnoughError() - logger.info('Golden devices in topology config file for case %s: %s', case_id, topo_mixed_devices) + logger.info( + 'Golden devices in topology config file for case %s: %s', + case_id, + topo_mixed_devices, + ) f_topo.close() golden_device_candidates = [] missing_golden_devices = topo_mixed_devices[:] @@ -532,7 +604,10 @@ class HarnessCase(unittest.TestCase): devices.remove(device_item) missing_golden_devices.remove(mixed_device_item) break - logger.info('Golden devices in topology config file mapped in settings : %s', golden_device_candidates) + logger.info( + 'Golden devices in topology config file mapped in settings : %s', + golden_device_candidates, + ) if len(topo_mixed_devices) != len(golden_device_candidates): device_dict = dict() for missing_device in missing_golden_devices: @@ -545,7 +620,10 @@ class HarnessCase(unittest.TestCase): else: devices = golden_device_candidates golden_devices_required = len(devices) - logger.info('All case-needed golden devices: %s', json.dumps(devices, indent=2)) + logger.info( + 'All case-needed golden devices: %s', + json.dumps(devices, indent=2), + ) if self.auto_dut and not settings.DUT_DEVICE: if settings.MIXED_DEVICE_TYPE: @@ -557,7 +635,9 @@ class HarnessCase(unittest.TestCase): raise GoldenDeviceNotEnoughError() # add golden devices - number_of_devices_to_add = len(devices) if self.add_all_devices else golden_devices_required + number_of_devices_to_add = ( + len(devices) if self.add_all_devices else golden_devices_required + ) for i in range(number_of_devices_to_add): self._add_device(*devices.pop()) @@ -567,13 +647,17 @@ class HarnessCase(unittest.TestCase): # enable AUTO DUT if self.auto_dut: - checkbox_auto_dut = browser.find_element_by_id('EnableAutoDutSelection') + checkbox_auto_dut = browser.find_element_by_id( + 'EnableAutoDutSelection' + ) if not checkbox_auto_dut.is_selected(): checkbox_auto_dut.click() time.sleep(1) if settings.DUT_DEVICE: - radio_auto_dut = browser.find_element_by_class_name('AutoDUT_RadBtns') + radio_auto_dut = browser.find_element_by_class_name( + 'AutoDUT_RadBtns' + ) if not radio_auto_dut.is_selected(): radio_auto_dut.click() @@ -581,23 +665,36 @@ class HarnessCase(unittest.TestCase): try: self._connect_devices() button_next = browser.find_element_by_id('nextBtn') - if not wait_until(lambda: 'disabled' not in button_next.get_attribute('class'), - times=(30 + 4 * number_of_devices_to_add)): + if not wait_until( + lambda: 'disabled' + not in button_next.get_attribute('class'), + times=(30 + 4 * number_of_devices_to_add), + ): bad_ones = [] - selected_hw_set = test_bed.find_elements_by_class_name('selected-hw') + selected_hw_set = test_bed.find_elements_by_class_name( + 'selected-hw' + ) for selected_hw in selected_hw_set: - form_inputs = selected_hw.find_elements_by_tag_name('input') + form_inputs = selected_hw.find_elements_by_tag_name( + 'input' + ) form_port = form_inputs[0] if form_port.is_enabled(): bad_ones.append(selected_hw) for selected_hw in bad_ones: - form_inputs = selected_hw.find_elements_by_tag_name('input') + form_inputs = selected_hw.find_elements_by_tag_name( + 'input' + ) form_port = form_inputs[0] port = form_port.get_attribute('value').encode('utf8') - if settings.DUT_DEVICE and port == settings.DUT_DEVICE[0]: + if ( + settings.DUT_DEVICE + and port == settings.DUT_DEVICE[0] + ): if settings.PDU_CONTROLLER_TYPE is None: - # connection error cannot recover without power cycling + # connection error cannot recover without power + # cycling raise FatalError('Failed to connect to DUT') else: raise FailError('Failed to connect to DUT') @@ -607,7 +704,9 @@ class HarnessCase(unittest.TestCase): self.history.mark_bad_golden_device(port) # remove the bad one - selected_hw.find_element_by_class_name('removeSelectedDevice').click() + selected_hw.find_element_by_class_name( + 'removeSelectedDevice' + ).click() time.sleep(0.1) if len(devices): @@ -623,18 +722,25 @@ class HarnessCase(unittest.TestCase): continue if self.auto_dut and not settings.DUT_DEVICE: - radio_auto_dut = browser.find_element_by_class_name('AutoDUT_RadBtns') + radio_auto_dut = browser.find_element_by_class_name( + 'AutoDUT_RadBtns' + ) if not radio_auto_dut.is_selected(): radio_auto_dut.click() time.sleep(5) button_next.click() - if not wait_until(lambda: self._browser.current_url.endswith('TestExecution.html'), 20): + if not wait_until( + lambda: self._browser.current_url.endswith( + 'TestExecution.html' + ), + 20, + ): raise Exception('Failed to load TestExecution page') except FailError: raise - except: + except BaseException: logger.exception('Unexpected error') else: break @@ -648,8 +754,15 @@ class HarnessCase(unittest.TestCase): time.sleep(1) checkbox = None - wait_until(lambda: self._browser.find_elements_by_css_selector('.tree-node .tree-title') and True) - elems = self._browser.find_elements_by_css_selector('.tree-node .tree-title') + wait_until( + lambda: self._browser.find_elements_by_css_selector( + '.tree-node .tree-title' + ) + and True + ) + elems = self._browser.find_elements_by_css_selector( + '.tree-node .tree-title' + ) finder = re.compile(r'.*\b' + case + r'\b') finder_dotted = re.compile(r'.*\b' + case.replace(' ', r'\.') + r'\b') for elem in elems: @@ -672,7 +785,9 @@ class HarnessCase(unittest.TestCase): elem = self._browser.find_element_by_id('runTest') elem.click() - if not wait_until(lambda: self._browser.find_element_by_id('stopTest') and True, 10): + if not wait_until( + lambda: self._browser.find_element_by_id('stopTest') and True, 10 + ): raise Exception('Failed to start test case') def _collect_result(self): @@ -685,17 +800,27 @@ class HarnessCase(unittest.TestCase): time.sleep(1) try: dialog = self._browser.find_element_by_id('Testinfo') - except: + except BaseException: logger.exception('Failed to get test info dialog.') else: if dialog.get_attribute('aria-hidden') != 'false': raise Exception('Test information dialog not ready') - version = self.auto_dut and settings.DUT_VERSION or self.dut.version - dialog.find_element_by_id('inp_dut_manufacturer').send_keys(settings.DUT_MANUFACTURER) - dialog.find_element_by_id('inp_dut_firmware_version').send_keys(version) - dialog.find_element_by_id('inp_tester_name').send_keys(settings.TESTER_NAME) - dialog.find_element_by_id('inp_remarks').send_keys(settings.TESTER_REMARKS) + version = ( + self.auto_dut and settings.DUT_VERSION or self.dut.version + ) + dialog.find_element_by_id('inp_dut_manufacturer').send_keys( + settings.DUT_MANUFACTURER + ) + dialog.find_element_by_id('inp_dut_firmware_version').send_keys( + version + ) + dialog.find_element_by_id('inp_tester_name').send_keys( + settings.TESTER_NAME + ) + dialog.find_element_by_id('inp_remarks').send_keys( + settings.TESTER_REMARKS + ) dialog.find_element_by_id('generatePdf').click() time.sleep(1) @@ -719,14 +844,22 @@ class HarnessCase(unittest.TestCase): self._browser.close() self._browser.switch_to.window(main_window) - os.system('copy "%%HOMEPATH%%\\Downloads\\NewPdf_*.pdf" %s\\' - % self.result_dir) - os.system('copy "%%HOMEPATH%%\\Downloads\\ExcelReport_*.xlsx" %s\\' - % self.result_dir) - os.system('copy "%s\\Captures\\*.pcapng" %s\\' - % (settings.HARNESS_HOME, self.result_dir)) - os.system('copy "%s\\Thread_Harness\\temp\\*.*" "%s"' - % (settings.HARNESS_HOME, self.result_dir)) + os.system( + 'copy "%%HOMEPATH%%\\Downloads\\NewPdf_*.pdf" %s\\' + % self.result_dir + ) + os.system( + 'copy "%%HOMEPATH%%\\Downloads\\ExcelReport_*.xlsx" %s\\' + % self.result_dir + ) + os.system( + 'copy "%s\\Captures\\*.pcapng" %s\\' + % (settings.HARNESS_HOME, self.result_dir) + ) + os.system( + 'copy "%s\\Thread_Harness\\temp\\*.*" "%s"' + % (settings.HARNESS_HOME, self.result_dir) + ) def _wait_dialog(self): """Wait for dialogs and handle them until done. @@ -735,21 +868,23 @@ class HarnessCase(unittest.TestCase): done = False error = False - logger.info("self timeout %d",self.timeout) + logger.info("self timeout %d", self.timeout) while not done and self.timeout: try: dialog = self._browser.find_element_by_id('RemoteConfirm') - except: + except BaseException: logger.exception('Failed to get dialog.') else: if dialog and dialog.get_attribute('aria-hidden') == 'false': - title = dialog.find_element_by_class_name('modal-title').text + title = dialog.find_element_by_class_name( + 'modal-title' + ).text time.sleep(1) logger.info('Handling dialog[%s]', title) try: done = self._handle_dialog(dialog, title) - except: + except BaseException: logger.exception('Error handling dialog: %s', title) error = True @@ -777,14 +912,25 @@ class HarnessCase(unittest.TestCase): if self.timeout % 10 == 0: lines = self._hc.tail() if 'SUCCESS: The process "dumpcap.exe" with PID ' in lines: - logger.info('Tshark should be ended now, lets wait at most 30 seconds.') - if not wait_until(lambda: 'tshark.exe' not in subprocess.check_output('tasklist'), 30): - res = subprocess.check_output('taskkill /t /f /im tshark.exe', - stderr=subprocess.STDOUT, shell=True) + logger.info( + 'Tshark should be ended now, lets wait at most 30 seconds.' + ) + if not wait_until( + lambda: 'tshark.exe' + not in subprocess.check_output('tasklist'), + 30, + ): + res = subprocess.check_output( + 'taskkill /t /f /im tshark.exe', + stderr=subprocess.STDOUT, + shell=True, + ) logger.info(res) # Wait until case really stopped - wait_until(lambda: self._browser.find_element_by_id('runTest') and True, 30) + wait_until( + lambda: self._browser.find_element_by_id('runTest') and True, 30 + ) if error: raise FailError('Fail for previous exceptions') @@ -821,8 +967,9 @@ class HarnessCase(unittest.TestCase): self.dut.extpanid = settings.THREAD_EXTPANID self.dut.start() - elif (title.startswith('MAC Address Required') - or title.startswith('DUT Random Extended MAC Address Required')): + elif title.startswith('MAC Address Required') or title.startswith( + 'DUT Random Extended MAC Address Required' + ): mac = self.dut.mac inp = dialog.find_element_by_id('cnfrmInpText') inp.clear() @@ -832,7 +979,9 @@ class HarnessCase(unittest.TestCase): ll64 = None for addr in self.dut.addrs: addr = addr.lower() - if addr.startswith('fe80') and not re.match('.+ff:fe00:[0-9a-f]{0,4}$', addr): + if addr.startswith('fe80') and not re.match( + '.+ff:fe00:[0-9a-f]{0,4}$', addr + ): ll64 = addr break @@ -865,7 +1014,9 @@ class HarnessCase(unittest.TestCase): elif title.startswith('ML64 Address'): ml64 = None for addr in self.dut.addrs: - if addr.startswith('fd') and not re.match('.+ff:fe00:[0-9a-f]{0,4}$', addr): + if addr.startswith('fd') and not re.match( + '.+ff:fe00:[0-9a-f]{0,4}$', addr + ): ml64 = addr break @@ -877,18 +1028,23 @@ class HarnessCase(unittest.TestCase): inp.clear() inp.send_keys(ml64) - elif title.startswith('Shield Devices') or title.startswith('Sheild DUT'): + elif title.startswith('Shield Devices') or title.startswith( + 'Sheild DUT' + ): if self.rf_shield: logger.info('Shielding devices') with self.rf_shield: self.rf_shield.shield() elif self.dut and settings.SHIELD_SIMULATION: - self.dut.channel = (self.channel == THREAD_CHANNEL_MAX - and THREAD_CHANNEL_MIN) or (self.channel + 1) + self.dut.channel = ( + self.channel == THREAD_CHANNEL_MAX and THREAD_CHANNEL_MIN + ) or (self.channel + 1) else: - raw_input('Shield DUT and press enter to continue..') + input('Shield DUT and press enter to continue..') - elif title.startswith('Unshield Devices') or title.startswith('Bring DUT Back to network'): + elif title.startswith('Unshield Devices') or title.startswith( + 'Bring DUT Back to network' + ): if self.rf_shield: logger.info('Unshielding devices') with self.rf_shield: @@ -896,13 +1052,19 @@ class HarnessCase(unittest.TestCase): elif self.dut and settings.SHIELD_SIMULATION: self.dut.channel = self.channel else: - raw_input('Bring DUT and press enter to continue..') + input('Bring DUT and press enter to continue..') elif title.startswith('Configure Prefix on DUT'): body = dialog.find_element_by_id('cnfrmMsg').text body = body.split(': ')[1] - params = reduce(lambda params, param: params.update(((param[0].strip(' '), param[1]),)) or params, - [it.split('=') for it in body.split(', ')], {}) + params = reduce( + lambda params, param: params.update( + ((param[0].strip(' '), param[1]),) + ) + or params, + [it.split('=') for it in body.split(', ')], + {}, + ) prefix = params['P_Prefix'].strip('\0\r\n\t ') flags = [] if params.get('P_slaac_preferred', 0) == '1': @@ -946,7 +1108,7 @@ class HarnessCase(unittest.TestCase): except FailError: logger.exception('Test failed') raise - except: + except BaseException: logger.exception('Something wrong') self._select_case(self.role, self.case) @@ -956,7 +1118,7 @@ class HarnessCase(unittest.TestCase): try: self._collect_result() - except: + except BaseException: logger.exception('Failed to collect results') raise diff --git a/tools/harness-automation/autothreadharness/harness_controller.py b/tools/harness-automation/autothreadharness/harness_controller.py index f70f69db0..b1dc19d3d 100644 --- a/tools/harness-automation/autothreadharness/harness_controller.py +++ b/tools/harness-automation/autothreadharness/harness_controller.py @@ -41,6 +41,7 @@ logger = logging.getLogger(__name__) HARNESS_SVN_VERSION_R44 = 1471 """int: this is the first published release that miniweb was removed from Harness""" + def _try_kill(proc): logger.info('Try kill process') times = 1 @@ -60,11 +61,13 @@ def _try_kill(proc): if times > 3: raise SystemExit() + class HarnessController(object): """Harness service control This controls harness service, including the harness back-end and front-end. """ + harness = None """harness back-end""" @@ -84,17 +87,27 @@ class HarnessController(object): if self.harness: logger.warning('Harness already started') else: - env = dict(os.environ, PYTHONPATH='%s\\Thread_Harness;%s\\ThirdParty\\hsdk-python\\src' - % (settings.HARNESS_HOME, settings.HARNESS_HOME)) + env = dict( + os.environ, + PYTHONPATH='%s\\Thread_Harness;%s\\ThirdParty\\hsdk-python\\src' + % (settings.HARNESS_HOME, settings.HARNESS_HOME), + ) - self.harness_file = '%s\\harness-%s.log' % (self.result_dir, time.strftime('%Y%m%d%H%M%S')) + self.harness_file = '%s\\harness-%s.log' % ( + self.result_dir, + time.strftime('%Y%m%d%H%M%S'), + ) with open(self.harness_file, 'w') as harness_out: - self.harness = subprocess.Popen([settings.HARNESS_HOME + '\\Python27\\python.exe', - settings.HARNESS_HOME + '\\Thread_Harness\\Run.py'], - cwd=settings.HARNESS_HOME, - stdout=harness_out, - stderr=harness_out, - env=env) + self.harness = subprocess.Popen( + [ + settings.HARNESS_HOME + '\\Python27\\python.exe', + settings.HARNESS_HOME + '\\Thread_Harness\\Run.py', + ], + cwd=settings.HARNESS_HOME, + stdout=harness_out, + stderr=harness_out, + env=env, + ) time.sleep(2) if self.version >= HARNESS_SVN_VERSION_R44: @@ -103,11 +116,17 @@ class HarnessController(object): if self.miniweb: logger.warning('Miniweb already started') else: - with open('%s\\miniweb-%s.log' % (self.result_dir, time.strftime('%Y%m%d%H%M%S')), 'w') as miniweb_out: - self.miniweb = subprocess.Popen([settings.HARNESS_HOME + '\\MiniWeb\\miniweb.exe'], - stdout=miniweb_out, - stderr=miniweb_out, - cwd=settings.HARNESS_HOME + '\\MiniWeb') + with open( + '%s\\miniweb-%s.log' + % (self.result_dir, time.strftime('%Y%m%d%H%M%S')), + 'w', + ) as miniweb_out: + self.miniweb = subprocess.Popen( + [settings.HARNESS_HOME + '\\MiniWeb\\miniweb.exe'], + stdout=miniweb_out, + stderr=miniweb_out, + cwd=settings.HARNESS_HOME + '\\MiniWeb', + ) def stop(self): logger.info('Stopping harness service') diff --git a/tools/harness-automation/autothreadharness/helpers.py b/tools/harness-automation/autothreadharness/helpers.py index d948cb3b9..1a931de85 100644 --- a/tools/harness-automation/autothreadharness/helpers.py +++ b/tools/harness-automation/autothreadharness/helpers.py @@ -41,9 +41,7 @@ class HistoryHelper(object): self.data = json.load(open(filename, 'r')) except Exception: self.logger.exception('file may not exists') - self.data = { - 'golden_device_black_list': [] - } + self.data = {'golden_device_black_list': []} self.save() def save(self): diff --git a/tools/harness-automation/autothreadharness/open_thread_controller.py b/tools/harness-automation/autothreadharness/open_thread_controller.py index e86479e5c..92ec83580 100644 --- a/tools/harness-automation/autothreadharness/open_thread_controller.py +++ b/tools/harness-automation/autothreadharness/open_thread_controller.py @@ -43,8 +43,10 @@ logger = logging.getLogger(__name__) linesepx = re.compile(r'\r\n|\n') + class OpenThreadController(threading.Thread): """This is an simple wrapper to communicate with openthread""" + _lock = threading.Lock() viewing = False @@ -93,7 +95,9 @@ class OpenThreadController(threading.Thread): def _connect(self): logger.debug('My port is %s', self.port) if self.port.startswith('NET'): - portnum = settings.SER2NET_PORTBASE + int(self.port.split('NET')[1]) + portnum = settings.SER2NET_PORTBASE + int( + self.port.split('NET')[1] + ) logger.debug('My port num is %d', portnum) address = (settings.SER2NET_HOSTNAME, portnum) self.handle = socket.create_connection(address) @@ -105,7 +109,9 @@ class OpenThreadController(threading.Thread): self.handle.setblocking(0) self._is_net = True else: - self.handle = serial.Serial(self.port, 115200, timeout=0, xonxoff=True) + self.handle = serial.Serial( + self.port, 115200, timeout=0, xonxoff=True + ) self._is_net = False def _read(self, size=512): @@ -223,7 +229,7 @@ class OpenThreadController(threading.Thread): res.append(line) break - except: + except BaseException: logger.exception('Failed to send command') self.close() self._init() @@ -238,7 +244,7 @@ class OpenThreadController(threading.Thread): while self.viewing and self._lock.acquire(): try: line = self._readline() - except: + except BaseException: pass else: logger.info(line) @@ -275,7 +281,6 @@ class OpenThreadController(threading.Thread): self._read() self._log and self.resume() - def resume(self): """Start dumping logs""" self._lock.release() @@ -283,6 +288,7 @@ class OpenThreadController(threading.Thread): def pause(self): """Start dumping logs""" self._lock.acquire() + @property def networkname(self): """str: Thread network name.""" diff --git a/tools/harness-automation/autothreadharness/pdu_controller.py b/tools/harness-automation/autothreadharness/pdu_controller.py index e5098aa92..4deb6af45 100644 --- a/tools/harness-automation/autothreadharness/pdu_controller.py +++ b/tools/harness-automation/autothreadharness/pdu_controller.py @@ -33,18 +33,27 @@ import re import telnetlib import time +from builtins import input + try: # python 2 - from urllib2 import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, build_opener + from urllib2 import ( + HTTPPasswordMgrWithDefaultRealm, + HTTPBasicAuthHandler, + build_opener, + ) except ImportError: # python 3 - from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, build_opener + from urllib.request import ( + HTTPPasswordMgrWithDefaultRealm, + HTTPBasicAuthHandler, + build_opener, + ) logger = logging.getLogger(__name__) class PduController(object): - def open(self, **params): """Open PDU controller connection""" raise NotImplementedError @@ -72,7 +81,6 @@ class DummyPduController(PduController): class ApcPduController(PduController): - def __init__(self): self.tn = None @@ -170,7 +178,6 @@ class ApcPduController(PduController): class NordicBoardPduController(PduController): - def open(self, **params): pass @@ -181,7 +188,9 @@ class NordicBoardPduController(PduController): boards_serial_numbers = params['boards_serial_numbers'] for serial_number in boards_serial_numbers: - logger.info('Resetting board with the serial number: %s', serial_number) + logger.info( + 'Resetting board with the serial number: %s', serial_number + ) self._pin_reset(serial_number) def close(self): @@ -189,11 +198,12 @@ class NordicBoardPduController(PduController): class IpPowerSocketPduController(PduController): - def open(self, **params): self._base_url = 'http://{}/outs.cgi?out'.format(params['ip']) password_manager = HTTPPasswordMgrWithDefaultRealm() - password_manager.add_password(None, self._base_url, params['user'], params['pass']) + password_manager.add_password( + None, self._base_url, params['user'], params['pass'] + ) authentication_handler = HTTPBasicAuthHandler(password_manager) self._opener = build_opener(authentication_handler) @@ -220,12 +230,11 @@ class IpPowerSocketPduController(PduController): class ManualPduController(PduController): - def open(self, **kwargs): pass def reboot(self, **kwargs): - raw_input('Reset all devices and press enter to continue..') + input('Reset all devices and press enter to continue..') def close(self): pass diff --git a/tools/harness-automation/autothreadharness/rf_shield_controller.py b/tools/harness-automation/autothreadharness/rf_shield_controller.py index 4c58ea1e4..40ad60f1d 100644 --- a/tools/harness-automation/autothreadharness/rf_shield_controller.py +++ b/tools/harness-automation/autothreadharness/rf_shield_controller.py @@ -39,7 +39,6 @@ logger = logging.getLogger(__name__) class RfShieldController(ABC): - @abc.abstractmethod def shield(self): pass @@ -58,7 +57,6 @@ class RfShieldController(ABC): class RfSwitchController(RfShieldController): - def __init__(self, channel, port): self._channel = channel self._port = port @@ -92,12 +90,12 @@ class RfSwitchController(RfShieldController): self._conn = None -CONTROLLERS = { - 'RF_SWITCH': RfSwitchController, -} +CONTROLLERS = {'RF_SWITCH': RfSwitchController} def get_rf_shield_controller(shield_type, params): if shield_type in CONTROLLERS: return CONTROLLERS[shield_type](**params) - logger.exception('Unknown RF shield controller type: {}'.format(shield_type)) + logger.exception( + 'Unknown RF shield controller type: {}'.format(shield_type) + ) diff --git a/tools/harness-automation/autothreadharness/runner.py b/tools/harness-automation/autothreadharness/runner.py index a710f9730..5276c8be7 100644 --- a/tools/harness-automation/autothreadharness/runner.py +++ b/tools/harness-automation/autothreadharness/runner.py @@ -36,6 +36,7 @@ import os import sys import time import unittest +from builtins import str from collections import OrderedDict from autothreadharness.harness_case import HarnessCase @@ -49,14 +50,23 @@ logger = logging.getLogger() logger.setLevel(logging.INFO) -RESUME_SCRIPT_PATH = '%appdata%\\Microsoft\\Windows\\Start Menu\\Programs\\' \ - 'Startup\\continue_harness.bat' +RESUME_SCRIPT_PATH = ( + '%appdata%\\Microsoft\\Windows\\Start Menu\\Programs\\' + 'Startup\\continue_harness.bat' +) + class SimpleTestResult(unittest.TestResult): executions = 0 - def __init__(self, path, auto_reboot_args=None, keep_explorer=False, add_all_devices=False): + def __init__( + self, + path, + auto_reboot_args=None, + keep_explorer=False, + add_all_devices=False, + ): """Record test results in json file Args: @@ -75,23 +85,37 @@ class SimpleTestResult(unittest.TestResult): logger.info('Initial state is %s', json.dumps(self.result, indent=2)) def startTest(self, test): - logger.info('\n========================================\n%s\n========================================', test.__class__.__name__) + logger.info( + '\n========================================\n%s\n========================================', + test.__class__.__name__, + ) test.add_all_devices = self.add_all_devices # create start up script if auto reboot enabled if self.auto_reboot_args: test.auto_reboot = True - os.system('echo %s > "%s"' - % (' '.join(self.auto_reboot_args + ['-c', test.__class__.__name__]), - RESUME_SCRIPT_PATH)) + os.system( + 'echo %s > "%s"' + % ( + ' '.join( + self.auto_reboot_args + ['-c', test.__class__.__name__] + ), + RESUME_SCRIPT_PATH, + ) + ) # record start timestamp self.started = time.strftime('%Y-%m-%dT%H:%M:%S') os.system('mkdir %s' % test.result_dir) - self.log_handler = logging.FileHandler('%s\\auto-%s.log' % (test.result_dir, time.strftime('%Y%m%d%H%M%S'))) + self.log_handler = logging.FileHandler( + '%s\\auto-%s.log' + % (test.result_dir, time.strftime('%Y%m%d%H%M%S')) + ) self.log_handler.setLevel(logging.DEBUG) - self.log_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) + self.log_handler.setFormatter( + logging.Formatter('%(asctime)s %(levelname)s %(message)s') + ) logger.addHandler(self.log_handler) def add_result(self, test, passed, error=None): @@ -101,18 +125,21 @@ class SimpleTestResult(unittest.TestResult): test (TestCase): The test just run passed (bool): Whether the case is passed """ - self.result[unicode(test.__class__.__name__)] = { + self.result[str(test.__class__.__name__)] = { 'started': self.started, 'stopped': time.strftime('%Y-%m-%dT%H:%M:%S'), 'passed': passed, 'error': error, - 'executions': SimpleTestResult.executions + 'executions': SimpleTestResult.executions, } if self.auto_reboot_args: os.system('del "%s"' % RESUME_SCRIPT_PATH) - json.dump(OrderedDict(sorted(self.result.items(), key=lambda t: t[0])), - open(self.path, 'w'), indent=2) + json.dump( + OrderedDict(sorted(self.result.items(), key=lambda t: t[0])), + open(self.path, 'w'), + indent=2, + ) # save logs logger.removeHandler(self.log_handler) @@ -148,11 +175,16 @@ class SimpleTestResult(unittest.TestResult): super(SimpleTestResult, self).addError(test, err) self.add_result(test, None, str(err[1])) + def list_devices(names=None, continue_from=None, **kwargs): """List devices in settings file and print versions""" if not names: - names = [device for device, _type in settings.GOLDEN_DEVICES if _type == 'OpenThread'] + names = [ + device + for device, _type in settings.GOLDEN_DEVICES + if _type == 'OpenThread' + ] if continue_from: continue_from = names.index(continue_from) @@ -163,13 +195,26 @@ def list_devices(names=None, continue_from=None, **kwargs): try: with OpenThreadController(port) as otc: print('%s: %s' % (port, otc.version)) - except: + except BaseException: logger.exception('failed to get version of %s' % port) -def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist=None, name_greps=None, - manual_reset=False, delete_history=False, max_devices=0, - continue_from=None, result_file='./result.json', auto_reboot=False, keep_explorer=False, - add_all_devices=False): + +def discover( + names=None, + pattern=['*.py'], + skip='efp', + dry_run=False, + blacklist=None, + name_greps=None, + manual_reset=False, + delete_history=False, + max_devices=0, + continue_from=None, + result_file='./result.json', + auto_reboot=False, + keep_explorer=False, + add_all_devices=False, +): """Discover all test cases and skip those passed Args: @@ -185,9 +230,12 @@ def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist= if blacklist: try: - excludes = [line.strip('\n') for line in open(blacklist, 'r').readlines() - if not line.startswith('#')] - except: + excludes = [ + line.strip('\n') + for line in open(blacklist, 'r').readlines() + if not line.startswith('#') + ] + except BaseException: logger.exception('Failed to open test case black list file') raise else: @@ -197,7 +245,7 @@ def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist= if os.path.isfile(result_file): try: log = json.load(open(result_file, 'r')) - except: + except BaseException: logger.exception('Failed to open result file') if not log: @@ -215,10 +263,13 @@ def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist= for case in s2: if case.__class__ is HarnessCase: continue - case_name = unicode(case.__class__.__name__) + case_name = str(case.__class__.__name__) # grep name - if name_greps and not any(fnmatch.fnmatch(case_name, name_grep) for name_grep in name_greps): + if name_greps and not any( + fnmatch.fnmatch(case_name, name_grep) + for name_grep in name_greps + ): logger.info('case[%s] skipped by name greps', case_name) continue @@ -229,16 +280,28 @@ def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist= # skip cases if case_name in log.keys(): - if (log[case_name]['passed'] and ('p' in skip)) \ - or (log[case_name]['passed'] is False and ('f' in skip)) \ - or (log[case_name]['passed'] is None and ('e' in skip)): - logger.warning('case[%s] skipped for its status[%s]', case_name, log[case_name]['passed']) + if ( + (log[case_name]['passed'] and ('p' in skip)) + or ( + log[case_name]['passed'] is False and ('f' in skip) + ) + or (log[case_name]['passed'] is None and ('e' in skip)) + ): + logger.warning( + 'case[%s] skipped for its status[%s]', + case_name, + log[case_name]['passed'], + ) continue # continue from if continue_from: if continue_from != case_name: - logger.warning('case[%s] skipped for continue from[%s]', case_name, continue_from) + logger.warning( + 'case[%s] skipped for continue from[%s]', + case_name, + continue_from, + ) continue else: continue_from = None @@ -250,7 +313,11 @@ def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist= # max devices if max_devices and case.golden_devices_required > max_devices: - logger.warning('case[%s] skipped for exceeding max golden devices allowed[%d]', case_name, max_devices) + logger.warning( + 'case[%s] skipped for exceeding max golden devices allowed[%d]', + case_name, + max_devices, + ) continue suite.addTest(case) @@ -281,7 +348,9 @@ def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist= settings.PDU_CONTROLLER_OPEN_PARAMS = {} settings.PDU_CONTROLLER_REBOOT_PARAMS = {} - result = SimpleTestResult(result_file, auto_reboot_args, keep_explorer, add_all_devices) + result = SimpleTestResult( + result_file, auto_reboot_args, keep_explorer, add_all_devices + ) for case in suite: logger.info(case.__class__.__name__) @@ -291,51 +360,145 @@ def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist= suite.run(result) return result + def main(): - parser = argparse.ArgumentParser(description='Thread harness test case runner') - parser.add_argument('--auto-reboot', '-a', action='store_true', default=False, - help='restart system when harness service die') - parser.add_argument('names', metavar='NAME', type=str, nargs='*', default=None, - help='test case name, omit to test all') - parser.add_argument('--blacklist', '-b', metavar='BLACKLIST_FILE', type=str, - help='file to list test cases to skip', default=None) - parser.add_argument('--continue-from', '-c', type=str, default=None, - help='first case to test') - parser.add_argument('--delete-history', '-d', action='store_true', default=False, - help='clear history on startup') - parser.add_argument('--keep-explorer', '-e', action='store_true', default=False, - help='do not restart explorer.exe at the end') - parser.add_argument('--name-greps', '-g', action='append', default=None, - help='grep case by names') - parser.add_argument('--list-file', '-i', type=str, default=None, - help='file to list cases names to test') - parser.add_argument('--skip', '-k', metavar='SKIP', type=str, - help='type of results to skip.' \ - 'e for error, f for fail, p for pass.', default='') - parser.add_argument('--list-devices', '-l', action='store_true', default=False, - help='list devices') - parser.add_argument('--manual-reset', '-m', action='store_true', default=False, - help='reset devices manually') - parser.add_argument('--dry-run', '-n', action='store_true', default=False, - help='just show what to run') - parser.add_argument('--result-file', '-o', type=str, default=settings.OUTPUT_PATH + '\\result.json', - help='file to store and read current status') - parser.add_argument('--pattern', '-p', metavar='PATTERN', type=str, - help='file name pattern, default to "*.py"', default='*.py') - parser.add_argument('--rerun-fails', '-r', type=int, default=0, - help='number of times to rerun failed test cases') - parser.add_argument('--add-all-devices', '-t', action='store_true', default=False, - help='add all devices to the test bed') - parser.add_argument('--max-devices', '-u', type=int, default=0, - help='max golden devices allowed') + parser = argparse.ArgumentParser( + description='Thread harness test case runner' + ) + parser.add_argument( + '--auto-reboot', + '-a', + action='store_true', + default=False, + help='restart system when harness service die', + ) + parser.add_argument( + 'names', + metavar='NAME', + type=str, + nargs='*', + default=None, + help='test case name, omit to test all', + ) + parser.add_argument( + '--blacklist', + '-b', + metavar='BLACKLIST_FILE', + type=str, + help='file to list test cases to skip', + default=None, + ) + parser.add_argument( + '--continue-from', + '-c', + type=str, + default=None, + help='first case to test', + ) + parser.add_argument( + '--delete-history', + '-d', + action='store_true', + default=False, + help='clear history on startup', + ) + parser.add_argument( + '--keep-explorer', + '-e', + action='store_true', + default=False, + help='do not restart explorer.exe at the end', + ) + parser.add_argument( + '--name-greps', + '-g', + action='append', + default=None, + help='grep case by names', + ) + parser.add_argument( + '--list-file', + '-i', + type=str, + default=None, + help='file to list cases names to test', + ) + parser.add_argument( + '--skip', + '-k', + metavar='SKIP', + type=str, + help='type of results to skip.' 'e for error, f for fail, p for pass.', + default='', + ) + parser.add_argument( + '--list-devices', + '-l', + action='store_true', + default=False, + help='list devices', + ) + parser.add_argument( + '--manual-reset', + '-m', + action='store_true', + default=False, + help='reset devices manually', + ) + parser.add_argument( + '--dry-run', + '-n', + action='store_true', + default=False, + help='just show what to run', + ) + parser.add_argument( + '--result-file', + '-o', + type=str, + default=settings.OUTPUT_PATH + '\\result.json', + help='file to store and read current status', + ) + parser.add_argument( + '--pattern', + '-p', + metavar='PATTERN', + type=str, + help='file name pattern, default to "*.py"', + default='*.py', + ) + parser.add_argument( + '--rerun-fails', + '-r', + type=int, + default=0, + help='number of times to rerun failed test cases', + ) + parser.add_argument( + '--add-all-devices', + '-t', + action='store_true', + default=False, + help='add all devices to the test bed', + ) + parser.add_argument( + '--max-devices', + '-u', + type=int, + default=0, + help='max golden devices allowed', + ) args = vars(parser.parse_args()) if args['list_file']: try: - names = [line.strip('\n') for line in open(args['list_file'], 'r').readlines() - if not line.startswith('#')] - except: + names = [ + line.strip('\n') + for line in open(args['list_file'], 'r').readlines() + if not line.startswith('#') + ] + except BaseException: logger.exception('Failed to open test case list file') raise else: @@ -352,15 +515,25 @@ def main(): if rerun_fails > 0: for i in range(rerun_fails): - failed_names = {name for name in result.result if result.result[name]['passed'] == False} - if not failed_names: break + failed_names = { + name + for name in result.result + if result.result[name]['passed'] is False + } + if not failed_names: + break logger.info('Rerunning failed test cases') - logger.info('Rerun #{}:'.format(i+1)) + logger.info('Rerun #{}:'.format(i + 1)) result = discover( - names=failed_names, pattern=args['pattern'], skip='', result_file=args['result_file'], - auto_reboot=args['auto_reboot'], keep_explorer=args['keep_explorer'], - add_all_devices=args['add_all_devices'] + names=failed_names, + pattern=args['pattern'], + skip='', + result_file=args['result_file'], + auto_reboot=args['auto_reboot'], + keep_explorer=args['keep_explorer'], + add_all_devices=args['add_all_devices'], ) + if __name__ == '__main__': main() diff --git a/tools/harness-automation/autothreadharness/settings_sample.py b/tools/harness-automation/autothreadharness/settings_sample.py index c2afce38e..92f4d209c 100644 --- a/tools/harness-automation/autothreadharness/settings_sample.py +++ b/tools/harness-automation/autothreadharness/settings_sample.py @@ -60,7 +60,7 @@ THREAD_SED_POLLING_INTERVAL = 0 """int: SED polling interval in seconds. Set to 0 to use Harness's default value.""" HARNESS_HOME = 'C:\\GRL\\Thread1.1' -"""str: Harness installation path, e.g. ``C:\GRL\Thread1.1``""" +r"""str: Harness installation path, e.g. ``C:\GRL\Thread1.1``""" HARNESS_URL = 'http://127.0.0.1:8000' """str: Harness front-end url""" @@ -81,7 +81,10 @@ For OpenThread golden devices, ser2net is also supported, just use IP:PORT for t """ MIXED_DEVICE_TYPE = True -"""bool: Whether golden devices are mixed-type. Must put TopologyConfig.txt under HARNESS_HOME\Thread_Harness\TestScripts before testing if True""" +r"""bool: Whether golden devices are mixed-type. Must put + TopologyConfig.txt under + HARNESS_HOME\Thread_Harness\TestScripts before testing if True +""" OUTPUT_PATH = '.\\output' """str: Path to store results and logs, MUST be writable.""" diff --git a/tools/harness-automation/cases/__init__.py b/tools/harness-automation/cases/__init__.py index 282d11bfa..a10b5bf43 100644 --- a/tools/harness-automation/cases/__init__.py +++ b/tools/harness-automation/cases/__init__.py @@ -26,5 +26,3 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # - - diff --git a/tools/harness-automation/cases/commissioner_8_1_1.py b/tools/harness-automation/cases/commissioner_8_1_1.py index f732ffea8..32b09f740 100644 --- a/tools/harness-automation/cases/commissioner_8_1_1.py +++ b/tools/harness-automation/cases/commissioner_8_1_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_8_1_1(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '8 1 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_8_1_2.py b/tools/harness-automation/cases/commissioner_8_1_2.py index 24d116662..f31177c47 100644 --- a/tools/harness-automation/cases/commissioner_8_1_2.py +++ b/tools/harness-automation/cases/commissioner_8_1_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_8_1_2(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '8 1 2' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_8_1_6.py b/tools/harness-automation/cases/commissioner_8_1_6.py index 06d0980c2..ab4d094fc 100644 --- a/tools/harness-automation/cases/commissioner_8_1_6.py +++ b/tools/harness-automation/cases/commissioner_8_1_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_8_1_6(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '8 1 6' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_8_2_1.py b/tools/harness-automation/cases/commissioner_8_2_1.py index 6dfb9a760..990f08abf 100644 --- a/tools/harness-automation/cases/commissioner_8_2_1.py +++ b/tools/harness-automation/cases/commissioner_8_2_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_8_2_1(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '8 2 1' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_8_2_2.py b/tools/harness-automation/cases/commissioner_8_2_2.py index 9c0c90760..5ada36a87 100644 --- a/tools/harness-automation/cases/commissioner_8_2_2.py +++ b/tools/harness-automation/cases/commissioner_8_2_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_8_2_2(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '8 2 2' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_8_2_5.py b/tools/harness-automation/cases/commissioner_8_2_5.py index d5977562c..a284b397a 100644 --- a/tools/harness-automation/cases/commissioner_8_2_5.py +++ b/tools/harness-automation/cases/commissioner_8_2_5.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_8_2_5(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '8 2 5' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_8_3_1.py b/tools/harness-automation/cases/commissioner_8_3_1.py index 2ec664844..385e62712 100644 --- a/tools/harness-automation/cases/commissioner_8_3_1.py +++ b/tools/harness-automation/cases/commissioner_8_3_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_8_3_1(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '8 3 1' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_9_2_1.py b/tools/harness-automation/cases/commissioner_9_2_1.py index 66320ff24..a264e55f0 100644 --- a/tools/harness-automation/cases/commissioner_9_2_1.py +++ b/tools/harness-automation/cases/commissioner_9_2_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_9_2_1(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '9 2 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_9_2_14.py b/tools/harness-automation/cases/commissioner_9_2_14.py index 2ff8726b0..d090d47f4 100644 --- a/tools/harness-automation/cases/commissioner_9_2_14.py +++ b/tools/harness-automation/cases/commissioner_9_2_14.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_9_2_14(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '9 2 14' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_9_2_19.py b/tools/harness-automation/cases/commissioner_9_2_19.py index 9fbf42617..78265a7b9 100755 --- a/tools/harness-automation/cases/commissioner_9_2_19.py +++ b/tools/harness-automation/cases/commissioner_9_2_19.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_9_2_19(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '9 2 19' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_9_2_2.py b/tools/harness-automation/cases/commissioner_9_2_2.py index d42bad752..7ea4ab5a2 100644 --- a/tools/harness-automation/cases/commissioner_9_2_2.py +++ b/tools/harness-automation/cases/commissioner_9_2_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_9_2_2(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '9 2 2' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_9_2_3.py b/tools/harness-automation/cases/commissioner_9_2_3.py index ba9fcc2ea..e13cae288 100644 --- a/tools/harness-automation/cases/commissioner_9_2_3.py +++ b/tools/harness-automation/cases/commissioner_9_2_3.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_9_2_3(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '9 2 3' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/commissioner_9_2_4.py b/tools/harness-automation/cases/commissioner_9_2_4.py index 305ac04b1..9d46c6e04 100644 --- a/tools/harness-automation/cases/commissioner_9_2_4.py +++ b/tools/harness-automation/cases/commissioner_9_2_4.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Commissioner_9_2_4(HarnessCase): role = HarnessCase.ROLE_COMMISSIONER case = '9 2 4' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_1_1.py b/tools/harness-automation/cases/ed_6_1_1.py index 599340e1a..52d2e4b68 100644 --- a/tools/harness-automation/cases/ed_6_1_1.py +++ b/tools/harness-automation/cases/ed_6_1_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_1_1(HarnessCase): role = HarnessCase.ROLE_ED case = '6 1 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_1_2.py b/tools/harness-automation/cases/ed_6_1_2.py index 7f0c9697d..a5eb4b01d 100644 --- a/tools/harness-automation/cases/ed_6_1_2.py +++ b/tools/harness-automation/cases/ed_6_1_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_1_2(HarnessCase): role = HarnessCase.ROLE_ED case = '6 1 2' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_1_3.py b/tools/harness-automation/cases/ed_6_1_3.py index 95e727773..c6a65ece7 100644 --- a/tools/harness-automation/cases/ed_6_1_3.py +++ b/tools/harness-automation/cases/ed_6_1_3.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_1_3(HarnessCase): role = HarnessCase.ROLE_ED case = '6 1 3' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_1_4.py b/tools/harness-automation/cases/ed_6_1_4.py index 14af10722..99894dcc2 100644 --- a/tools/harness-automation/cases/ed_6_1_4.py +++ b/tools/harness-automation/cases/ed_6_1_4.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_1_4(HarnessCase): role = HarnessCase.ROLE_ED case = '6 1 4' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_1_5.py b/tools/harness-automation/cases/ed_6_1_5.py index 6dba1cf39..9e09ab8f2 100644 --- a/tools/harness-automation/cases/ed_6_1_5.py +++ b/tools/harness-automation/cases/ed_6_1_5.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_1_5(HarnessCase): role = HarnessCase.ROLE_ED case = '6 1 5' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_1_6.py b/tools/harness-automation/cases/ed_6_1_6.py index ad1f8212d..399799b88 100644 --- a/tools/harness-automation/cases/ed_6_1_6.py +++ b/tools/harness-automation/cases/ed_6_1_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_1_6(HarnessCase): role = HarnessCase.ROLE_ED case = '6 1 6' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_2_1.py b/tools/harness-automation/cases/ed_6_2_1.py index 14de0e43b..5740c625e 100644 --- a/tools/harness-automation/cases/ed_6_2_1.py +++ b/tools/harness-automation/cases/ed_6_2_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_2_1(HarnessCase): role = HarnessCase.ROLE_ED case = '6 2 1' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_2_2.py b/tools/harness-automation/cases/ed_6_2_2.py index 0b81776e9..4ee44acd8 100644 --- a/tools/harness-automation/cases/ed_6_2_2.py +++ b/tools/harness-automation/cases/ed_6_2_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_2_2(HarnessCase): role = HarnessCase.ROLE_ED case = '6 2 2' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_3_1.py b/tools/harness-automation/cases/ed_6_3_1.py index b4217ffa0..e19a0a594 100644 --- a/tools/harness-automation/cases/ed_6_3_1.py +++ b/tools/harness-automation/cases/ed_6_3_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_3_1(HarnessCase): role = HarnessCase.ROLE_ED case = '6 3 1' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_4_1.py b/tools/harness-automation/cases/ed_6_4_1.py index 18c0c0fa1..261bfa6fa 100644 --- a/tools/harness-automation/cases/ed_6_4_1.py +++ b/tools/harness-automation/cases/ed_6_4_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_4_1(HarnessCase): role = HarnessCase.ROLE_ED case = '6 4 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_4_2.py b/tools/harness-automation/cases/ed_6_4_2.py index c6cd55024..cb5337dd9 100644 --- a/tools/harness-automation/cases/ed_6_4_2.py +++ b/tools/harness-automation/cases/ed_6_4_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_4_2(HarnessCase): role = HarnessCase.ROLE_ED case = '6 4 2' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_5_1.py b/tools/harness-automation/cases/ed_6_5_1.py index f062281ea..fae820c51 100644 --- a/tools/harness-automation/cases/ed_6_5_1.py +++ b/tools/harness-automation/cases/ed_6_5_1.py @@ -33,10 +33,12 @@ import time from autothreadharness.harness_case import HarnessCase + class ED_6_5_1(HarnessCase): role = HarnessCase.ROLE_ED case = '6 5 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): if title.startswith('Reset DUT'): self.dut.stop() @@ -44,5 +46,6 @@ class ED_6_5_1(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_5_2.py b/tools/harness-automation/cases/ed_6_5_2.py index 8bb08fb2c..08258801e 100644 --- a/tools/harness-automation/cases/ed_6_5_2.py +++ b/tools/harness-automation/cases/ed_6_5_2.py @@ -28,16 +28,16 @@ # -import time import unittest -import re from autothreadharness.harness_case import HarnessCase + class ED_6_5_2(HarnessCase): role = HarnessCase.ROLE_ED case = '6 5 2' golden_devices_required = 2 + def on_dialog(self, dialog, title): if title.startswith('Reset DUT'): self.dut.stop() @@ -46,7 +46,7 @@ class ED_6_5_2(HarnessCase): elif title.startswith('Rejoin Now'): self.dut.start() return False - + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_5_3.py b/tools/harness-automation/cases/ed_6_5_3.py index f6c51fbe4..2a9b20edb 100644 --- a/tools/harness-automation/cases/ed_6_5_3.py +++ b/tools/harness-automation/cases/ed_6_5_3.py @@ -28,15 +28,16 @@ # -import time import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_5_3(HarnessCase): role = HarnessCase.ROLE_ED case = '6 5 3' golden_devices_required = 1 + def on_dialog(self, dialog, title): if title.startswith('Reset DUT'): self.dut.stop() @@ -46,5 +47,6 @@ class ED_6_5_3(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_6_1.py b/tools/harness-automation/cases/ed_6_6_1.py index 6aaa8b37b..117c88153 100644 --- a/tools/harness-automation/cases/ed_6_6_1.py +++ b/tools/harness-automation/cases/ed_6_6_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_6_1(HarnessCase): role = HarnessCase.ROLE_ED case = '6 6 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_6_6_2.py b/tools/harness-automation/cases/ed_6_6_2.py index f9c9486c4..8bc84b435 100644 --- a/tools/harness-automation/cases/ed_6_6_2.py +++ b/tools/harness-automation/cases/ed_6_6_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_6_6_2(HarnessCase): role = HarnessCase.ROLE_ED case = '6 6 2' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_9_2_17.py b/tools/harness-automation/cases/ed_9_2_17.py index d578a96ce..e245fea48 100644 --- a/tools/harness-automation/cases/ed_9_2_17.py +++ b/tools/harness-automation/cases/ed_9_2_17.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_9_2_17(HarnessCase): role = HarnessCase.ROLE_ED case = '9 2 17' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/ed_9_2_8.py b/tools/harness-automation/cases/ed_9_2_8.py index 94bb8fd97..4e254b195 100644 --- a/tools/harness-automation/cases/ed_9_2_8.py +++ b/tools/harness-automation/cases/ed_9_2_8.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class ED_9_2_8(HarnessCase): role = HarnessCase.ROLE_ED case = '9 2 8' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/fed_5_7_1.py b/tools/harness-automation/cases/fed_5_7_1.py index 97e24a344..feb29e655 100755 --- a/tools/harness-automation/cases/fed_5_7_1.py +++ b/tools/harness-automation/cases/fed_5_7_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class FED_5_7_1(HarnessCase): role = HarnessCase.ROLE_FED case = '5 7 1' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/fed_5_7_3.py b/tools/harness-automation/cases/fed_5_7_3.py index d15df49cf..c34f1c381 100755 --- a/tools/harness-automation/cases/fed_5_7_3.py +++ b/tools/harness-automation/cases/fed_5_7_3.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class FED_5_7_3(HarnessCase): role = HarnessCase.ROLE_FED case = '5 7 3' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/fed_6_1_7.py b/tools/harness-automation/cases/fed_6_1_7.py index 7f4fc4cee..7fba55f9c 100644 --- a/tools/harness-automation/cases/fed_6_1_7.py +++ b/tools/harness-automation/cases/fed_6_1_7.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class FED_6_1_7(HarnessCase): role = HarnessCase.ROLE_FED case = '6 1 7' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/fed_9_2_13.py b/tools/harness-automation/cases/fed_9_2_13.py index 0db08a5b7..7b84b4537 100644 --- a/tools/harness-automation/cases/fed_9_2_13.py +++ b/tools/harness-automation/cases/fed_9_2_13.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class FED_9_2_13(HarnessCase): role = HarnessCase.ROLE_FED case = '9 2 13' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/joiner_8_1_1.py b/tools/harness-automation/cases/joiner_8_1_1.py index b6ecc8a95..d71a7b7d5 100644 --- a/tools/harness-automation/cases/joiner_8_1_1.py +++ b/tools/harness-automation/cases/joiner_8_1_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Joiner_8_1_1(HarnessCase): role = HarnessCase.ROLE_JOINER case = '8 1 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/joiner_8_1_6.py b/tools/harness-automation/cases/joiner_8_1_6.py index 3e593defb..844499735 100644 --- a/tools/harness-automation/cases/joiner_8_1_6.py +++ b/tools/harness-automation/cases/joiner_8_1_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Joiner_8_1_6(HarnessCase): role = HarnessCase.ROLE_JOINER case = '8 1 6' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_1_1.py b/tools/harness-automation/cases/leader_5_1_1.py index 529e1ae53..465d2bfd8 100644 --- a/tools/harness-automation/cases/leader_5_1_1.py +++ b/tools/harness-automation/cases/leader_5_1_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_1_1(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 1 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_1_13.py b/tools/harness-automation/cases/leader_5_1_13.py index 2caaccfc1..001736874 100644 --- a/tools/harness-automation/cases/leader_5_1_13.py +++ b/tools/harness-automation/cases/leader_5_1_13.py @@ -29,20 +29,24 @@ from autothreadharness.harness_case import HarnessCase +import time import unittest + class Leader_5_1_13(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 1 13' golden_devices_required = 1 + def on_dialog(self, dialog, title): if title.startswith('User Input Required'): - #body = dialog.find_element_by_id('cnfrmMsg').text - #if body.startswith('Reset Leader'): + # body = dialog.find_element_by_id('cnfrmMsg').text + # if body.startswith('Reset Leader'): self.dut.stop() time.sleep(1) self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_1_5.py b/tools/harness-automation/cases/leader_5_1_5.py index ffa582241..386496c4e 100644 --- a/tools/harness-automation/cases/leader_5_1_5.py +++ b/tools/harness-automation/cases/leader_5_1_5.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Leader_5_1_5(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 1 5' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_2_3.py b/tools/harness-automation/cases/leader_5_2_3.py index c73aa3d21..15bd2afb8 100644 --- a/tools/harness-automation/cases/leader_5_2_3.py +++ b/tools/harness-automation/cases/leader_5_2_3.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_2_3(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 2 3' golden_devices_required = 32 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_3_6.py b/tools/harness-automation/cases/leader_5_3_6.py index bc098a938..89cd19cae 100644 --- a/tools/harness-automation/cases/leader_5_3_6.py +++ b/tools/harness-automation/cases/leader_5_3_6.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Leader_5_3_6(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 3 6' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_3_7.py b/tools/harness-automation/cases/leader_5_3_7.py index 6f8005bdf..68df333af 100644 --- a/tools/harness-automation/cases/leader_5_3_7.py +++ b/tools/harness-automation/cases/leader_5_3_7.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_3_7(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 3 7' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_3_8.py b/tools/harness-automation/cases/leader_5_3_8.py index e668b07a8..1e642553c 100644 --- a/tools/harness-automation/cases/leader_5_3_8.py +++ b/tools/harness-automation/cases/leader_5_3_8.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_3_8(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 3 8' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_5_1.py b/tools/harness-automation/cases/leader_5_5_1.py index 4565d526d..9bbc273cf 100644 --- a/tools/harness-automation/cases/leader_5_5_1.py +++ b/tools/harness-automation/cases/leader_5_5_1.py @@ -34,10 +34,12 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_5_1(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 5 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): if title.startswith('User Input Required'): body = dialog.find_element_by_id('cnfrmMsg').text @@ -51,5 +53,6 @@ class Leader_5_5_1(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_5_2.py b/tools/harness-automation/cases/leader_5_5_2.py index 35dd33577..4f97befca 100644 --- a/tools/harness-automation/cases/leader_5_5_2.py +++ b/tools/harness-automation/cases/leader_5_5_2.py @@ -33,10 +33,12 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_5_2(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 5 2' golden_devices_required = 2 + def on_dialog(self, dialog, title): if title.startswith('User Input Required'): self.dut.stop() @@ -44,5 +46,6 @@ class Leader_5_5_2(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_5_3.py b/tools/harness-automation/cases/leader_5_5_3.py index a156050f9..70cccb29a 100644 --- a/tools/harness-automation/cases/leader_5_5_3.py +++ b/tools/harness-automation/cases/leader_5_5_3.py @@ -28,15 +28,16 @@ # -import time import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_5_3(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 5 3' golden_devices_required = 5 + def on_dialog(self, dialog, title): if title.startswith('Reset DUT'): self.dut.stop() @@ -46,5 +47,6 @@ class Leader_5_5_3(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_5_4.py b/tools/harness-automation/cases/leader_5_5_4.py index 97e5b582f..e04bbca80 100644 --- a/tools/harness-automation/cases/leader_5_5_4.py +++ b/tools/harness-automation/cases/leader_5_5_4.py @@ -28,15 +28,16 @@ # -import time import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_5_4(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 5 4' golden_devices_required = 5 + def on_dialog(self, dialog, title): if title.startswith('Reset DUT'): self.dut.stop() @@ -46,5 +47,6 @@ class Leader_5_5_4(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_5_7.py b/tools/harness-automation/cases/leader_5_5_7.py index fe0219c24..b9a5802a7 100644 --- a/tools/harness-automation/cases/leader_5_5_7.py +++ b/tools/harness-automation/cases/leader_5_5_7.py @@ -30,13 +30,14 @@ from autothreadharness.harness_case import HarnessCase -import time import unittest + class Leader_5_5_7(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 5 7' golden_devices_required = 3 + def on_dialog(self, dialog, title): if title.startswith('Reset DUT'): self.dut.stop() @@ -46,5 +47,6 @@ class Leader_5_5_7(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_6_2.py b/tools/harness-automation/cases/leader_5_6_2.py index fdf1ac5c3..06080a7a5 100644 --- a/tools/harness-automation/cases/leader_5_6_2.py +++ b/tools/harness-automation/cases/leader_5_6_2.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Leader_5_6_2(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 6 2' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_6_4.py b/tools/harness-automation/cases/leader_5_6_4.py index 2ebcea1b9..a588660a2 100644 --- a/tools/harness-automation/cases/leader_5_6_4.py +++ b/tools/harness-automation/cases/leader_5_6_4.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_6_4(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 6 4' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_6_5.py b/tools/harness-automation/cases/leader_5_6_5.py index 8fc393003..aa18f5306 100644 --- a/tools/harness-automation/cases/leader_5_6_5.py +++ b/tools/harness-automation/cases/leader_5_6_5.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_6_5(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 6 5' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_6_6.py b/tools/harness-automation/cases/leader_5_6_6.py index 3e0679804..51d80b135 100644 --- a/tools/harness-automation/cases/leader_5_6_6.py +++ b/tools/harness-automation/cases/leader_5_6_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_6_6(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 6 6' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_5_8_4.py b/tools/harness-automation/cases/leader_5_8_4.py index 6110e6900..ae080339c 100644 --- a/tools/harness-automation/cases/leader_5_8_4.py +++ b/tools/harness-automation/cases/leader_5_8_4.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_5_8_4(HarnessCase): role = HarnessCase.ROLE_LEADER case = '5 8 4' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_7_1_1.py b/tools/harness-automation/cases/leader_7_1_1.py index 9e1e79837..8f8253e86 100644 --- a/tools/harness-automation/cases/leader_7_1_1.py +++ b/tools/harness-automation/cases/leader_7_1_1.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Leader_7_1_1(HarnessCase): role = HarnessCase.ROLE_LEADER case = '7 1 1' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_7_1_3.py b/tools/harness-automation/cases/leader_7_1_3.py index 156680810..58db178f1 100644 --- a/tools/harness-automation/cases/leader_7_1_3.py +++ b/tools/harness-automation/cases/leader_7_1_3.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Leader_7_1_3(HarnessCase): role = HarnessCase.ROLE_LEADER case = '7 1 3' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_7_1_6.py b/tools/harness-automation/cases/leader_7_1_6.py index 8afd72e4c..96a3e7e0c 100755 --- a/tools/harness-automation/cases/leader_7_1_6.py +++ b/tools/harness-automation/cases/leader_7_1_6.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Leader_7_1_6(HarnessCase): role = HarnessCase.ROLE_LEADER case = '7 1 6' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_7_1_7.py b/tools/harness-automation/cases/leader_7_1_7.py index 84a9f35c7..30f6a5d5f 100755 --- a/tools/harness-automation/cases/leader_7_1_7.py +++ b/tools/harness-automation/cases/leader_7_1_7.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Leader_7_1_7(HarnessCase): role = HarnessCase.ROLE_LEADER case = '7 1 7' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_8_3_1.py b/tools/harness-automation/cases/leader_8_3_1.py index 9fbbb0bd4..35a3402c6 100644 --- a/tools/harness-automation/cases/leader_8_3_1.py +++ b/tools/harness-automation/cases/leader_8_3_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_8_3_1(HarnessCase): role = HarnessCase.ROLE_LEADER case = '8 3 1' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_1.py b/tools/harness-automation/cases/leader_9_2_1.py index 42447bc64..923782d46 100644 --- a/tools/harness-automation/cases/leader_9_2_1.py +++ b/tools/harness-automation/cases/leader_9_2_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_1(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_11.py b/tools/harness-automation/cases/leader_9_2_11.py index ee1d83ca4..0174d82fd 100644 --- a/tools/harness-automation/cases/leader_9_2_11.py +++ b/tools/harness-automation/cases/leader_9_2_11.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_11(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 11' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_12.py b/tools/harness-automation/cases/leader_9_2_12.py index 8adc441ac..b35f11033 100644 --- a/tools/harness-automation/cases/leader_9_2_12.py +++ b/tools/harness-automation/cases/leader_9_2_12.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_12(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 12' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_18.py b/tools/harness-automation/cases/leader_9_2_18.py index 13340c7b8..4677d7568 100644 --- a/tools/harness-automation/cases/leader_9_2_18.py +++ b/tools/harness-automation/cases/leader_9_2_18.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_18(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 18' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_19.py b/tools/harness-automation/cases/leader_9_2_19.py index a4f69154b..ae605354f 100755 --- a/tools/harness-automation/cases/leader_9_2_19.py +++ b/tools/harness-automation/cases/leader_9_2_19.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_19(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 19' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_2.py b/tools/harness-automation/cases/leader_9_2_2.py index 1e9fdbec0..449a63f53 100644 --- a/tools/harness-automation/cases/leader_9_2_2.py +++ b/tools/harness-automation/cases/leader_9_2_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_2(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 2' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_3.py b/tools/harness-automation/cases/leader_9_2_3.py index 6638ceb25..4d1762713 100644 --- a/tools/harness-automation/cases/leader_9_2_3.py +++ b/tools/harness-automation/cases/leader_9_2_3.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_3(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 3' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_4.py b/tools/harness-automation/cases/leader_9_2_4.py index 3bfccfea0..e18cb36cd 100644 --- a/tools/harness-automation/cases/leader_9_2_4.py +++ b/tools/harness-automation/cases/leader_9_2_4.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_4(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 4' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_5.py b/tools/harness-automation/cases/leader_9_2_5.py index 6b01f3782..e4626ce9e 100644 --- a/tools/harness-automation/cases/leader_9_2_5.py +++ b/tools/harness-automation/cases/leader_9_2_5.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_5(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 5' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_6.py b/tools/harness-automation/cases/leader_9_2_6.py index 1f7548c87..aecca92b4 100644 --- a/tools/harness-automation/cases/leader_9_2_6.py +++ b/tools/harness-automation/cases/leader_9_2_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_6(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 6' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_7.py b/tools/harness-automation/cases/leader_9_2_7.py index 103cc314e..a6f2deecd 100644 --- a/tools/harness-automation/cases/leader_9_2_7.py +++ b/tools/harness-automation/cases/leader_9_2_7.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_7(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 7' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/leader_9_2_9.py b/tools/harness-automation/cases/leader_9_2_9.py index 0d87fc02e..8749fd726 100644 --- a/tools/harness-automation/cases/leader_9_2_9.py +++ b/tools/harness-automation/cases/leader_9_2_9.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Leader_9_2_9(HarnessCase): role = HarnessCase.ROLE_LEADER case = '9 2 9' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/med_6_3_2.py b/tools/harness-automation/cases/med_6_3_2.py index 201945b45..d5fe42e8d 100644 --- a/tools/harness-automation/cases/med_6_3_2.py +++ b/tools/harness-automation/cases/med_6_3_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class MED_6_3_2(HarnessCase): role = HarnessCase.ROLE_MED case = '6 3 2' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/med_9_2_10.py b/tools/harness-automation/cases/med_9_2_10.py index 70f8c6da1..faaa3aa84 100644 --- a/tools/harness-automation/cases/med_9_2_10.py +++ b/tools/harness-automation/cases/med_9_2_10.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class MED_9_2_10(HarnessCase): role = HarnessCase.ROLE_MED case = '9 2 10' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/med_9_2_12.py b/tools/harness-automation/cases/med_9_2_12.py index 13cd24cc1..7c93f3c24 100644 --- a/tools/harness-automation/cases/med_9_2_12.py +++ b/tools/harness-automation/cases/med_9_2_12.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class MED_9_2_12(HarnessCase): role = HarnessCase.ROLE_MED case = '9 2 12' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/med_9_2_13.py b/tools/harness-automation/cases/med_9_2_13.py index 639bb5669..f45bf21d8 100644 --- a/tools/harness-automation/cases/med_9_2_13.py +++ b/tools/harness-automation/cases/med_9_2_13.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class MED_9_2_13(HarnessCase): role = HarnessCase.ROLE_MED case = '9 2 13' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/med_9_2_18.py b/tools/harness-automation/cases/med_9_2_18.py index a8f6cba0a..6831ac098 100644 --- a/tools/harness-automation/cases/med_9_2_18.py +++ b/tools/harness-automation/cases/med_9_2_18.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class MED_9_2_18(HarnessCase): role = HarnessCase.ROLE_MED case = '9 2 18' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/med_9_2_6.py b/tools/harness-automation/cases/med_9_2_6.py index 6822115a6..5b8411c5c 100644 --- a/tools/harness-automation/cases/med_9_2_6.py +++ b/tools/harness-automation/cases/med_9_2_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class MED_9_2_6(HarnessCase): role = HarnessCase.ROLE_MED case = '9 2 6' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/reed_5_2_4.py b/tools/harness-automation/cases/reed_5_2_4.py index 86471752e..8deba1c3b 100644 --- a/tools/harness-automation/cases/reed_5_2_4.py +++ b/tools/harness-automation/cases/reed_5_2_4.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class REED_5_2_4(HarnessCase): role = HarnessCase.ROLE_REED case = '5 2 4' golden_devices_required = 17 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/reed_5_2_5.py b/tools/harness-automation/cases/reed_5_2_5.py index 8d05e4795..f9e3a8ed1 100644 --- a/tools/harness-automation/cases/reed_5_2_5.py +++ b/tools/harness-automation/cases/reed_5_2_5.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class REED_5_2_5(HarnessCase): role = HarnessCase.ROLE_REED case = '5 2 5' golden_devices_required = 17 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/reed_5_2_7.py b/tools/harness-automation/cases/reed_5_2_7.py index c0aafda4a..d77e80f86 100644 --- a/tools/harness-automation/cases/reed_5_2_7.py +++ b/tools/harness-automation/cases/reed_5_2_7.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class REED_5_2_7(HarnessCase): role = HarnessCase.ROLE_REED case = '5 2 7' golden_devices_required = 16 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/reed_5_5_5.py b/tools/harness-automation/cases/reed_5_5_5.py index 7160b99cb..c2d71b902 100644 --- a/tools/harness-automation/cases/reed_5_5_5.py +++ b/tools/harness-automation/cases/reed_5_5_5.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class REED_5_5_5(HarnessCase): role = HarnessCase.ROLE_REED case = '5 5 5' golden_devices_required = 16 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/reed_5_6_7.py b/tools/harness-automation/cases/reed_5_6_7.py index 71076fac0..eca3eca76 100644 --- a/tools/harness-automation/cases/reed_5_6_7.py +++ b/tools/harness-automation/cases/reed_5_6_7.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class REED_5_6_7(HarnessCase): role = HarnessCase.ROLE_REED case = '5 6 7' golden_devices_required = 16 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/reed_5_7_2.py b/tools/harness-automation/cases/reed_5_7_2.py index 632b7afa4..6b357812d 100755 --- a/tools/harness-automation/cases/reed_5_7_2.py +++ b/tools/harness-automation/cases/reed_5_7_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class REED_5_7_2(HarnessCase): role = HarnessCase.ROLE_REED case = '5 7 2' golden_devices_required = 16 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_1.py b/tools/harness-automation/cases/router_5_1_1.py index 6205502fc..637a15c60 100644 --- a/tools/harness-automation/cases/router_5_1_1.py +++ b/tools/harness-automation/cases/router_5_1_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_1(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_10.py b/tools/harness-automation/cases/router_5_1_10.py index 0cfbb9c22..8ac88174a 100644 --- a/tools/harness-automation/cases/router_5_1_10.py +++ b/tools/harness-automation/cases/router_5_1_10.py @@ -32,10 +32,12 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_10(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 10' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass diff --git a/tools/harness-automation/cases/router_5_1_11.py b/tools/harness-automation/cases/router_5_1_11.py index dc08d7fce..a818612cc 100644 --- a/tools/harness-automation/cases/router_5_1_11.py +++ b/tools/harness-automation/cases/router_5_1_11.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_11(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 11' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_12.py b/tools/harness-automation/cases/router_5_1_12.py index 32c9224c6..d69b9e80d 100644 --- a/tools/harness-automation/cases/router_5_1_12.py +++ b/tools/harness-automation/cases/router_5_1_12.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_12(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 12' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_13.py b/tools/harness-automation/cases/router_5_1_13.py index 580c02ecd..80e741327 100644 --- a/tools/harness-automation/cases/router_5_1_13.py +++ b/tools/harness-automation/cases/router_5_1_13.py @@ -29,14 +29,15 @@ import unittest -import time from autothreadharness.harness_case import HarnessCase + class Router_5_1_13(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 13' golden_devices_required = 1 + def on_dialog(self, dialog, title): if title.startswith('Reset DUT'): self.dut.stop() @@ -46,5 +47,6 @@ class Router_5_1_13(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_2.py b/tools/harness-automation/cases/router_5_1_2.py index b482f8231..c430acab9 100644 --- a/tools/harness-automation/cases/router_5_1_2.py +++ b/tools/harness-automation/cases/router_5_1_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_2(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 2' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_3.py b/tools/harness-automation/cases/router_5_1_3.py index fd977230c..b60d16fa2 100644 --- a/tools/harness-automation/cases/router_5_1_3.py +++ b/tools/harness-automation/cases/router_5_1_3.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_3(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 3' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_4.py b/tools/harness-automation/cases/router_5_1_4.py index ce6799d0e..477336f39 100644 --- a/tools/harness-automation/cases/router_5_1_4.py +++ b/tools/harness-automation/cases/router_5_1_4.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_4(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 4' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_6.py b/tools/harness-automation/cases/router_5_1_6.py index d56b3d8ef..f64160922 100644 --- a/tools/harness-automation/cases/router_5_1_6.py +++ b/tools/harness-automation/cases/router_5_1_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_6(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 6' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_7.py b/tools/harness-automation/cases/router_5_1_7.py index 5116d9428..dfecd892d 100644 --- a/tools/harness-automation/cases/router_5_1_7.py +++ b/tools/harness-automation/cases/router_5_1_7.py @@ -32,10 +32,12 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_7(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 7' golden_devices_required = 11 + def on_dialog(self, dialog, title): if title.startswith('Enter Router Max Child Count'): inp = dialog.find_element_by_id('cnfrmInpText') @@ -43,5 +45,6 @@ class Router_5_1_7(HarnessCase): inp.send_keys('5') return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_8.py b/tools/harness-automation/cases/router_5_1_8.py index 396570ba2..adfcf26ff 100644 --- a/tools/harness-automation/cases/router_5_1_8.py +++ b/tools/harness-automation/cases/router_5_1_8.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_8(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 8' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_1_9.py b/tools/harness-automation/cases/router_5_1_9.py index ef403745e..85f30839f 100644 --- a/tools/harness-automation/cases/router_5_1_9.py +++ b/tools/harness-automation/cases/router_5_1_9.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_1_9(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 9' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_2_1.py b/tools/harness-automation/cases/router_5_2_1.py index 2807633bc..9ac6fb290 100644 --- a/tools/harness-automation/cases/router_5_2_1.py +++ b/tools/harness-automation/cases/router_5_2_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_2_1(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 2 1' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_2_6.py b/tools/harness-automation/cases/router_5_2_6.py index d40be6737..d572e00e0 100644 --- a/tools/harness-automation/cases/router_5_2_6.py +++ b/tools/harness-automation/cases/router_5_2_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_2_6(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 2 6' golden_devices_required = 23 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_2_7.py b/tools/harness-automation/cases/router_5_2_7.py index 38e00f1a5..90b5ba0d2 100644 --- a/tools/harness-automation/cases/router_5_2_7.py +++ b/tools/harness-automation/cases/router_5_2_7.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_2_7(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 2 7' golden_devices_required = 16 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_3_1.py b/tools/harness-automation/cases/router_5_3_1.py index 8a1af7ccf..7bedcf637 100644 --- a/tools/harness-automation/cases/router_5_3_1.py +++ b/tools/harness-automation/cases/router_5_3_1.py @@ -31,11 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_3_1(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 3 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_3_10.py b/tools/harness-automation/cases/router_5_3_10.py index 506347144..b55513a2e 100644 --- a/tools/harness-automation/cases/router_5_3_10.py +++ b/tools/harness-automation/cases/router_5_3_10.py @@ -31,11 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_3_10(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 3 10' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_3_11.py b/tools/harness-automation/cases/router_5_3_11.py index 5e38bad00..74c25b16d 100644 --- a/tools/harness-automation/cases/router_5_3_11.py +++ b/tools/harness-automation/cases/router_5_3_11.py @@ -31,11 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_3_11(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 3 11' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_3_2.py b/tools/harness-automation/cases/router_5_3_2.py index 70b13a1a5..e91513622 100644 --- a/tools/harness-automation/cases/router_5_3_2.py +++ b/tools/harness-automation/cases/router_5_3_2.py @@ -31,11 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_3_2(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 3 2' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_3_3.py b/tools/harness-automation/cases/router_5_3_3.py index 1feeb02a8..9b1d50deb 100644 --- a/tools/harness-automation/cases/router_5_3_3.py +++ b/tools/harness-automation/cases/router_5_3_3.py @@ -31,14 +31,17 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_3_3(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 3 3' golden_devices_required = 4 + def on_dialog(self, dialog, title): if title.startswith('Start DUT'): self.dut.enable_blacklist() self.dut.add_blacklist('166e0a000000005') + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_3_4.py b/tools/harness-automation/cases/router_5_3_4.py index 57dca7681..19170b8d0 100644 --- a/tools/harness-automation/cases/router_5_3_4.py +++ b/tools/harness-automation/cases/router_5_3_4.py @@ -31,11 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_3_4(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 3 4' golden_devices_required = 6 + def on_dialog(self, dialog, title): pass + + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_3_5.py b/tools/harness-automation/cases/router_5_3_5.py index f84c0e844..d527431e7 100644 --- a/tools/harness-automation/cases/router_5_3_5.py +++ b/tools/harness-automation/cases/router_5_3_5.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_3_5(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 3 5' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_3_9.py b/tools/harness-automation/cases/router_5_3_9.py index 3c454ed61..c6388c4c7 100644 --- a/tools/harness-automation/cases/router_5_3_9.py +++ b/tools/harness-automation/cases/router_5_3_9.py @@ -31,11 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_3_9(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 3 9' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_5_1.py b/tools/harness-automation/cases/router_5_5_1.py index fd11f5b70..10199705c 100644 --- a/tools/harness-automation/cases/router_5_5_1.py +++ b/tools/harness-automation/cases/router_5_5_1.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_5_1(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 5 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_5_2.py b/tools/harness-automation/cases/router_5_5_2.py index 62bde02e9..a1e736438 100644 --- a/tools/harness-automation/cases/router_5_5_2.py +++ b/tools/harness-automation/cases/router_5_5_2.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_5_2(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 5 2' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_5_3.py b/tools/harness-automation/cases/router_5_5_3.py index e5de7c8e1..efad77980 100644 --- a/tools/harness-automation/cases/router_5_5_3.py +++ b/tools/harness-automation/cases/router_5_5_3.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_5_3(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 5 3' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_5_4.py b/tools/harness-automation/cases/router_5_5_4.py index 1eab96250..effcf09e5 100644 --- a/tools/harness-automation/cases/router_5_5_4.py +++ b/tools/harness-automation/cases/router_5_5_4.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_5_4(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 5 4' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_5_7.py b/tools/harness-automation/cases/router_5_5_7.py index 81481bdb1..45c5a73ef 100644 --- a/tools/harness-automation/cases/router_5_5_7.py +++ b/tools/harness-automation/cases/router_5_5_7.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_5_7(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 5 7' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_6_1.py b/tools/harness-automation/cases/router_5_6_1.py index ad6d00990..90a260e5c 100644 --- a/tools/harness-automation/cases/router_5_6_1.py +++ b/tools/harness-automation/cases/router_5_6_1.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_6_1(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 6 1' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_6_3.py b/tools/harness-automation/cases/router_5_6_3.py index 17ffb1616..16d75cd5e 100644 --- a/tools/harness-automation/cases/router_5_6_3.py +++ b/tools/harness-automation/cases/router_5_6_3.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_6_3(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 6 3' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_6_9.py b/tools/harness-automation/cases/router_5_6_9.py index 86d42a6aa..29effa054 100644 --- a/tools/harness-automation/cases/router_5_6_9.py +++ b/tools/harness-automation/cases/router_5_6_9.py @@ -31,12 +31,15 @@ from autothreadharness.harness_case import HarnessCase import unittest + class Router_5_6_9(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 6 9' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_7_1.py b/tools/harness-automation/cases/router_5_7_1.py index e23a1894e..8e2f18fff 100644 --- a/tools/harness-automation/cases/router_5_7_1.py +++ b/tools/harness-automation/cases/router_5_7_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_7_1(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 7 1' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_7_3.py b/tools/harness-automation/cases/router_5_7_3.py index 00e60960b..f3c475232 100755 --- a/tools/harness-automation/cases/router_5_7_3.py +++ b/tools/harness-automation/cases/router_5_7_3.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_5_7_3(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 7 3' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_8_2.py b/tools/harness-automation/cases/router_5_8_2.py index e4a622167..f7ea1e7da 100644 --- a/tools/harness-automation/cases/router_5_8_2.py +++ b/tools/harness-automation/cases/router_5_8_2.py @@ -30,12 +30,16 @@ from autothreadharness.harness_case import HarnessCase import unittest + + class Router_5_8_2(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 8 2' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_5_8_3.py b/tools/harness-automation/cases/router_5_8_3.py index b129bb593..e6ceff5c3 100644 --- a/tools/harness-automation/cases/router_5_8_3.py +++ b/tools/harness-automation/cases/router_5_8_3.py @@ -30,12 +30,16 @@ from autothreadharness.harness_case import HarnessCase import unittest + + class Router_5_8_3(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 8 3' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_7_1_2.py b/tools/harness-automation/cases/router_7_1_2.py index 825bd4437..e6a93c55a 100644 --- a/tools/harness-automation/cases/router_7_1_2.py +++ b/tools/harness-automation/cases/router_7_1_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_7_1_2(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '7 1 2' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_7_1_4.py b/tools/harness-automation/cases/router_7_1_4.py index 17e3418c2..9b5a189e3 100644 --- a/tools/harness-automation/cases/router_7_1_4.py +++ b/tools/harness-automation/cases/router_7_1_4.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_7_1_4(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '7 1 4' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_7_1_5.py b/tools/harness-automation/cases/router_7_1_5.py index 9c9b9f558..c4fbcaf08 100644 --- a/tools/harness-automation/cases/router_7_1_5.py +++ b/tools/harness-automation/cases/router_7_1_5.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_7_1_5(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '7 1 5' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_7_1_8.py b/tools/harness-automation/cases/router_7_1_8.py index db1f288d2..1cd9a3dac 100644 --- a/tools/harness-automation/cases/router_7_1_8.py +++ b/tools/harness-automation/cases/router_7_1_8.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_7_1_8(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '7 1 8' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_8_2_1.py b/tools/harness-automation/cases/router_8_2_1.py index 0552ccd0f..dd98c870a 100644 --- a/tools/harness-automation/cases/router_8_2_1.py +++ b/tools/harness-automation/cases/router_8_2_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_8_2_1(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '8 2 1' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_8_2_2.py b/tools/harness-automation/cases/router_8_2_2.py index 175160b19..3701ec4e2 100644 --- a/tools/harness-automation/cases/router_8_2_2.py +++ b/tools/harness-automation/cases/router_8_2_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_8_2_2(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '8 2 2' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_8_2_5.py b/tools/harness-automation/cases/router_8_2_5.py index 0aeb14360..553fd6dad 100644 --- a/tools/harness-automation/cases/router_8_2_5.py +++ b/tools/harness-automation/cases/router_8_2_5.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_8_2_5(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '8 2 5' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_9_2_10.py b/tools/harness-automation/cases/router_9_2_10.py index 344bd3e4a..bfe508d9d 100644 --- a/tools/harness-automation/cases/router_9_2_10.py +++ b/tools/harness-automation/cases/router_9_2_10.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_9_2_10(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 10' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_9_2_12.py b/tools/harness-automation/cases/router_9_2_12.py index b5f0f3d2e..003e34820 100644 --- a/tools/harness-automation/cases/router_9_2_12.py +++ b/tools/harness-automation/cases/router_9_2_12.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_9_2_12(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 12' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_9_2_13.py b/tools/harness-automation/cases/router_9_2_13.py index 1b608a72f..eea25994c 100644 --- a/tools/harness-automation/cases/router_9_2_13.py +++ b/tools/harness-automation/cases/router_9_2_13.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_9_2_13(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 13' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_9_2_14.py b/tools/harness-automation/cases/router_9_2_14.py index 17b7fd051..1ebff32c1 100644 --- a/tools/harness-automation/cases/router_9_2_14.py +++ b/tools/harness-automation/cases/router_9_2_14.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_9_2_14(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 14' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_9_2_15.py b/tools/harness-automation/cases/router_9_2_15.py index be7938f53..23f58f93b 100644 --- a/tools/harness-automation/cases/router_9_2_15.py +++ b/tools/harness-automation/cases/router_9_2_15.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_9_2_15(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 15' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_9_2_16.py b/tools/harness-automation/cases/router_9_2_16.py index dd1f93eff..9283de78d 100644 --- a/tools/harness-automation/cases/router_9_2_16.py +++ b/tools/harness-automation/cases/router_9_2_16.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_9_2_16(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 16' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_9_2_18.py b/tools/harness-automation/cases/router_9_2_18.py index 24222b8cf..e0a8b16d5 100644 --- a/tools/harness-automation/cases/router_9_2_18.py +++ b/tools/harness-automation/cases/router_9_2_18.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_9_2_18(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 18' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_9_2_6.py b/tools/harness-automation/cases/router_9_2_6.py index 746f7e6f4..7b2deb6f7 100644 --- a/tools/harness-automation/cases/router_9_2_6.py +++ b/tools/harness-automation/cases/router_9_2_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_9_2_6(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 6' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_9_2_8.py b/tools/harness-automation/cases/router_9_2_8.py index d4fe6dbe1..1f20cc697 100644 --- a/tools/harness-automation/cases/router_9_2_8.py +++ b/tools/harness-automation/cases/router_9_2_8.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_9_2_8(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 8' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/router_9_2_9.py b/tools/harness-automation/cases/router_9_2_9.py index 72bf3e9a3..665f9fed2 100644 --- a/tools/harness-automation/cases/router_9_2_9.py +++ b/tools/harness-automation/cases/router_9_2_9.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class Router_9_2_9(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 9' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_1_1.py b/tools/harness-automation/cases/sed_6_1_1.py index 9284944f3..81221a702 100644 --- a/tools/harness-automation/cases/sed_6_1_1.py +++ b/tools/harness-automation/cases/sed_6_1_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_1_1(HarnessCase): role = HarnessCase.ROLE_SED case = '6 1 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_1_2.py b/tools/harness-automation/cases/sed_6_1_2.py index be01fdf58..c3acbc6da 100644 --- a/tools/harness-automation/cases/sed_6_1_2.py +++ b/tools/harness-automation/cases/sed_6_1_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_1_2(HarnessCase): role = HarnessCase.ROLE_SED case = '6 1 2' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_1_3.py b/tools/harness-automation/cases/sed_6_1_3.py index 329ca46da..42fab2306 100644 --- a/tools/harness-automation/cases/sed_6_1_3.py +++ b/tools/harness-automation/cases/sed_6_1_3.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_1_3(HarnessCase): role = HarnessCase.ROLE_SED case = '6 1 3' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_1_4.py b/tools/harness-automation/cases/sed_6_1_4.py index 2ea2e7b20..c508b8277 100644 --- a/tools/harness-automation/cases/sed_6_1_4.py +++ b/tools/harness-automation/cases/sed_6_1_4.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_1_4(HarnessCase): role = HarnessCase.ROLE_SED case = '6 1 4' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_1_5.py b/tools/harness-automation/cases/sed_6_1_5.py index 3b5946491..49048f443 100644 --- a/tools/harness-automation/cases/sed_6_1_5.py +++ b/tools/harness-automation/cases/sed_6_1_5.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_1_5(HarnessCase): role = HarnessCase.ROLE_SED case = '6 1 5' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_1_6.py b/tools/harness-automation/cases/sed_6_1_6.py index 9e681cfc6..5c20abc24 100644 --- a/tools/harness-automation/cases/sed_6_1_6.py +++ b/tools/harness-automation/cases/sed_6_1_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_1_6(HarnessCase): role = HarnessCase.ROLE_SED case = '6 1 6' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_2_1.py b/tools/harness-automation/cases/sed_6_2_1.py index ba8d7ea17..8f340d829 100644 --- a/tools/harness-automation/cases/sed_6_2_1.py +++ b/tools/harness-automation/cases/sed_6_2_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_2_1(HarnessCase): role = HarnessCase.ROLE_SED case = '6 2 1' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_2_2.py b/tools/harness-automation/cases/sed_6_2_2.py index 9bbd8145b..a8e317658 100644 --- a/tools/harness-automation/cases/sed_6_2_2.py +++ b/tools/harness-automation/cases/sed_6_2_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_2_2(HarnessCase): role = HarnessCase.ROLE_SED case = '6 2 2' golden_devices_required = 3 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_3_1.py b/tools/harness-automation/cases/sed_6_3_1.py index 86e87fd95..c79034906 100644 --- a/tools/harness-automation/cases/sed_6_3_1.py +++ b/tools/harness-automation/cases/sed_6_3_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_3_1(HarnessCase): role = HarnessCase.ROLE_SED case = '6 3 1' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_3_2.py b/tools/harness-automation/cases/sed_6_3_2.py index b31b601af..e2ca907ba 100644 --- a/tools/harness-automation/cases/sed_6_3_2.py +++ b/tools/harness-automation/cases/sed_6_3_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_3_2(HarnessCase): role = HarnessCase.ROLE_SED case = '6 3 2' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_4_1.py b/tools/harness-automation/cases/sed_6_4_1.py index b5f8f8eca..092ce6306 100644 --- a/tools/harness-automation/cases/sed_6_4_1.py +++ b/tools/harness-automation/cases/sed_6_4_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_4_1(HarnessCase): role = HarnessCase.ROLE_SED case = '6 4 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_4_2.py b/tools/harness-automation/cases/sed_6_4_2.py index 9c3d2bdfa..d79886714 100644 --- a/tools/harness-automation/cases/sed_6_4_2.py +++ b/tools/harness-automation/cases/sed_6_4_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_4_2(HarnessCase): role = HarnessCase.ROLE_SED case = '6 4 2' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_5_1.py b/tools/harness-automation/cases/sed_6_5_1.py index e539580c3..c9704e24e 100644 --- a/tools/harness-automation/cases/sed_6_5_1.py +++ b/tools/harness-automation/cases/sed_6_5_1.py @@ -33,10 +33,12 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_5_1(HarnessCase): role = HarnessCase.ROLE_SED case = '6 5 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): if title.startswith('Reset DUT'): time.sleep(self.child_timeout + 5) @@ -45,5 +47,6 @@ class SED_6_5_1(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_5_2.py b/tools/harness-automation/cases/sed_6_5_2.py index 8be5b6729..e2f3b410f 100644 --- a/tools/harness-automation/cases/sed_6_5_2.py +++ b/tools/harness-automation/cases/sed_6_5_2.py @@ -28,15 +28,16 @@ # -import time import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_5_2(HarnessCase): role = HarnessCase.ROLE_SED case = '6 5 2' golden_devices_required = 2 + def on_dialog(self, dialog, title): if title.startswith('Reset DUT'): self.dut.stop() @@ -46,5 +47,6 @@ class SED_6_5_2(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_5_3.py b/tools/harness-automation/cases/sed_6_5_3.py index 1f893f006..f8a0ca373 100644 --- a/tools/harness-automation/cases/sed_6_5_3.py +++ b/tools/harness-automation/cases/sed_6_5_3.py @@ -28,15 +28,16 @@ # -import time import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_5_3(HarnessCase): role = HarnessCase.ROLE_SED case = '6 5 3' golden_devices_required = 1 + def on_dialog(self, dialog, title): if title.startswith('Reset DUT'): self.dut.stop() @@ -46,5 +47,6 @@ class SED_6_5_3(HarnessCase): self.dut.start() return False + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_6_1.py b/tools/harness-automation/cases/sed_6_6_1.py index 5b60eee6e..f948aa92e 100644 --- a/tools/harness-automation/cases/sed_6_6_1.py +++ b/tools/harness-automation/cases/sed_6_6_1.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_6_1(HarnessCase): role = HarnessCase.ROLE_SED case = '6 6 1' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_6_6_2.py b/tools/harness-automation/cases/sed_6_6_2.py index 7c1e159b8..99d423cfe 100644 --- a/tools/harness-automation/cases/sed_6_6_2.py +++ b/tools/harness-automation/cases/sed_6_6_2.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_6_6_2(HarnessCase): role = HarnessCase.ROLE_SED case = '6 6 2' golden_devices_required = 1 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_9_2_10.py b/tools/harness-automation/cases/sed_9_2_10.py index 88b9855a4..b353220c5 100644 --- a/tools/harness-automation/cases/sed_9_2_10.py +++ b/tools/harness-automation/cases/sed_9_2_10.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_9_2_10(HarnessCase): role = HarnessCase.ROLE_SED case = '9 2 10' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_9_2_13.py b/tools/harness-automation/cases/sed_9_2_13.py index c703f185c..f4e877f93 100644 --- a/tools/harness-automation/cases/sed_9_2_13.py +++ b/tools/harness-automation/cases/sed_9_2_13.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_9_2_13(HarnessCase): role = HarnessCase.ROLE_SED case = '9 2 13' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_9_2_17.py b/tools/harness-automation/cases/sed_9_2_17.py index 731750387..5b718d633 100644 --- a/tools/harness-automation/cases/sed_9_2_17.py +++ b/tools/harness-automation/cases/sed_9_2_17.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_9_2_17(HarnessCase): role = HarnessCase.ROLE_SED case = '9 2 17' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_9_2_18.py b/tools/harness-automation/cases/sed_9_2_18.py index ca43ed83d..ddbc169ea 100644 --- a/tools/harness-automation/cases/sed_9_2_18.py +++ b/tools/harness-automation/cases/sed_9_2_18.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_9_2_18(HarnessCase): role = HarnessCase.ROLE_SED case = '9 2 18' golden_devices_required = 5 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_9_2_6.py b/tools/harness-automation/cases/sed_9_2_6.py index 482082583..c32a2f2ad 100644 --- a/tools/harness-automation/cases/sed_9_2_6.py +++ b/tools/harness-automation/cases/sed_9_2_6.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_9_2_6(HarnessCase): role = HarnessCase.ROLE_SED case = '9 2 6' golden_devices_required = 4 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/cases/sed_9_2_8.py b/tools/harness-automation/cases/sed_9_2_8.py index 67889d3c4..49cf7cb76 100644 --- a/tools/harness-automation/cases/sed_9_2_8.py +++ b/tools/harness-automation/cases/sed_9_2_8.py @@ -32,12 +32,15 @@ import unittest from autothreadharness.harness_case import HarnessCase + class SED_9_2_8(HarnessCase): role = HarnessCase.ROLE_SED case = '9 2 8' golden_devices_required = 2 + def on_dialog(self, dialog, title): pass + if __name__ == '__main__': unittest.main() diff --git a/tools/harness-automation/doc/conf.py b/tools/harness-automation/doc/conf.py index deb2045f4..b08e7b29e 100644 --- a/tools/harness-automation/doc/conf.py +++ b/tools/harness-automation/doc/conf.py @@ -60,10 +60,7 @@ sys.path.insert(0, os.path.abspath('..')) # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = [ - 'sphinx.ext.autodoc', - 'sphinxcontrib.napoleon' -] +extensions = ['sphinx.ext.autodoc', 'sphinxcontrib.napoleon'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -153,7 +150,7 @@ todo_include_todos = False # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -#html_theme = 'alabaster' +# html_theme = 'alabaster' html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme @@ -274,29 +271,31 @@ htmlhelp_basename = 'ThreadHarnessAutomationdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'ThreadHarnessAutomation.tex', u'Thread Harness Automation Documentation', - u'Yakun Xu', 'manual'), + ( + master_doc, + 'ThreadHarnessAutomation.tex', + u'Thread Harness Automation Documentation', + u'Yakun Xu', + 'manual', + ) ] # The name of an image file (relative to this directory) to place at the top of @@ -331,8 +330,13 @@ latex_documents = [ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'threadharnessautomation', u'Thread Harness Automation Documentation', - [author], 1) + ( + master_doc, + 'threadharnessautomation', + u'Thread Harness Automation Documentation', + [author], + 1, + ) ] # If true, show URL addresses after external links. @@ -346,9 +350,15 @@ man_pages = [ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'ThreadHarnessAutomation', u'Thread Harness Automation Documentation', - author, 'ThreadHarnessAutomation', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + 'ThreadHarnessAutomation', + u'Thread Harness Automation Documentation', + author, + 'ThreadHarnessAutomation', + 'One line description of project.', + 'Miscellaneous', + ) ] # Documents to append as an appendix to all manuals. diff --git a/tools/harness-automation/gencsv.py b/tools/harness-automation/gencsv.py index e5d152f74..93a4c2448 100755 --- a/tools/harness-automation/gencsv.py +++ b/tools/harness-automation/gencsv.py @@ -8,14 +8,25 @@ if len(sys.argv) > 1: else: filename = './result.json' + def get_key(item): ds = item[0].split('_') no = int(ds[1]) * 10000 + int(ds[2]) * 100 + int(ds[3]) ro = ds[0] return '%d-%s' % (no, ro) + result = json.load(open(filename, 'r')) o = open('./result.csv', 'w') o.write('Case,Status,Started,Stopped,Reason\n') for k, v in sorted(result.items(), key=get_key): - o.write('%s,%s,%s,%s,%s\n' % (k, (v['passed'] and 'Pass') or 'Fail', v['started'], v['stopped'], (v['error'] or '').replace('\n', ' '))) + o.write( + '%s,%s,%s,%s,%s\n' + % ( + k, + (v['passed'] and 'Pass') or 'Fail', + v['started'], + v['stopped'], + (v['error'] or '').replace('\n', ' '), + ) + ) diff --git a/tools/harness-thci/OpenThread.py b/tools/harness-thci/OpenThread.py index 5f5e9b782..20bb89c98 100644 --- a/tools/harness-thci/OpenThread.py +++ b/tools/harness-thci/OpenThread.py @@ -115,15 +115,15 @@ class OpenThread(IThci): expected str: the expected string times int: number of trials """ - print ('[%s] Expecting [%s]' % (self.port, expected)) + print('[%s] Expecting [%s]' % (self.port, expected)) retry_times = 10 while times > 0 and retry_times > 0: line = self._readline() - print ('[%s] Got line [%s]' % (self.port, line)) + print('[%s] Got line [%s]' % (self.port, line)) if line == expected: - print ('[%s] Expected [%s]' % (self.port, expected)) + print('[%s] Expected [%s]' % (self.port, expected)) return if not line: @@ -186,7 +186,7 @@ class OpenThread(IThci): except socket.error: logging.debug('%s: Nothing cleared', self.port) - print ('sending [%s]' % line) + print('sending [%s]' % line) self._write(line + '\r\n') # wait for write to complete @@ -269,8 +269,8 @@ class OpenThread(IThci): True: successful to set the device mode False: fail to set the device mode """ - print ('call __setDeviceMode') - print (mode) + print('call __setDeviceMode') + print(mode) try: cmd = 'mode %s' % mode return self.__sendCommand(cmd)[-1] == 'Done' @@ -290,10 +290,10 @@ class OpenThread(IThci): True: successful to set the ROUTER_UPGRADE_THRESHOLD False: fail to set ROUTER_UPGRADE_THRESHOLD """ - print ('call __setRouterUpgradeThreshold') + print('call __setRouterUpgradeThreshold') try: cmd = 'routerupgradethreshold %s' % str(iThreshold) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -312,10 +312,10 @@ class OpenThread(IThci): True: successful to set the ROUTER_DOWNGRADE_THRESHOLD False: fail to set ROUTER_DOWNGRADE_THRESHOLD """ - print ('call __setRouterDowngradeThreshold') + print('call __setRouterDowngradeThreshold') try: cmd = 'routerdowngradethreshold %s' % str(iThreshold) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -332,10 +332,10 @@ class OpenThread(IThci): True: successful to set the ROUTER_SELECTION_JITTER False: fail to set ROUTER_SELECTION_JITTER """ - print ('call _setRouterSelectionJitter') + print('call _setRouterSelectionJitter') try: cmd = 'routerselectionjitter %s' % str(iRouterJitter) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -349,7 +349,7 @@ class OpenThread(IThci): True: successful to set address filter mode. False: fail to set address filter mode. """ - print ('call setAddressFilterMode() ' + mode) + print('call setAddressFilterMode() ' + mode) try: cmd = 'macfilter addr ' + mode if self.__sendCommand(cmd)[-1] == 'Done': @@ -367,7 +367,7 @@ class OpenThread(IThci): True: successful to start OpenThread stack and thread interface up False: fail to start OpenThread stack """ - print ('call startOpenThread') + print('call startOpenThread') try: if self.hasActiveDatasetToCommit: if self.__sendCommand('dataset commit active')[0] != 'Done': @@ -412,7 +412,7 @@ class OpenThread(IThci): True: successful to stop OpenThread stack and thread interface down False: fail to stop OpenThread stack """ - print ('call stopOpenThread') + print('call stopOpenThread') try: if self.__sendCommand('thread stop')[-1] == 'Done': return self.__sendCommand('ifconfig down')[-1] == 'Done' @@ -430,7 +430,7 @@ class OpenThread(IThci): True: OpenThread is running False: OpenThread is not running """ - print ('call isOpenThreadRunning') + print('call isOpenThreadRunning') return self.__sendCommand('state')[0] != 'disabled' # rloc16 might be hex string or integer, need to return actual allocated @@ -446,8 +446,8 @@ class OpenThread(IThci): """ routerList = [] routerList = self.__sendCommand('router list')[0].split() - print (routerList) - print (xRloc16) + print(routerList) + print(xRloc16) for index in routerList: router = [] @@ -542,7 +542,7 @@ class OpenThread(IThci): try: line = self._readline() if line: - print (line) + print(line) logs.put(line) if 'Join success' in line: @@ -578,7 +578,7 @@ class OpenThread(IThci): return maskSet def __setChannelMask(self, channelMask): - print ('call _setChannelMask') + print('call _setChannelMask') try: cmd = 'dataset channelmask %s' % channelMask self.hasActiveDatasetToCommit = True @@ -589,7 +589,7 @@ class OpenThread(IThci): ) def __setSecurityPolicy(self, securityPolicySecs, securityPolicyFlags): - print ('call _setSecurityPolicy') + print('call _setSecurityPolicy') try: cmd = 'dataset securitypolicy %s %s' % ( str(securityPolicySecs), @@ -612,8 +612,8 @@ class OpenThread(IThci): True: successful to set key switch guard time False: fail to set key switch guard time """ - print ('%s call setKeySwitchGuardTime' % self.port) - print (iKeySwitchGuardTime) + print('%s call setKeySwitchGuardTime' % self.port) + print(iKeySwitchGuardTime) try: cmd = 'keysequence guardtime %s' % str(iKeySwitchGuardTime) if self.__sendCommand(cmd)[-1] == 'Done': @@ -628,11 +628,11 @@ class OpenThread(IThci): def __getCommissionerSessionId(self): """ get the commissioner session id allocated from Leader """ - print ('%s call getCommissionerSessionId' % self.port) + print('%s call getCommissionerSessionId' % self.port) return self.__sendCommand('commissioner sessionid')[0] def _connect(self): - print ('My port is %s' % self.port) + print('My port is %s' % self.port) if self.port.startswith('COM'): self.handle = serial.Serial(self.port, 115200, timeout=0) time.sleep(1) @@ -650,7 +650,7 @@ class OpenThread(IThci): def closeConnection(self): """close current serial port connection""" - print ('%s call closeConnection' % self.port) + print('%s call closeConnection' % self.port) try: if self.handle: self.handle.close() @@ -662,7 +662,7 @@ class OpenThread(IThci): def intialize(self): """initialize the serial port with baudrate, timeout parameters""" - print ('%s call intialize' % self.port) + print('%s call intialize' % self.port) try: self.deviceConnected = False @@ -696,8 +696,8 @@ class OpenThread(IThci): True: successful to set the Thread Networkname False: fail to set the Thread Networkname """ - print ('%s call setNetworkName' % self.port) - print (networkName) + print('%s call setNetworkName' % self.port) + print(networkName) try: cmd = 'networkname %s' % networkName datasetCmd = 'dataset networkname %s' % networkName @@ -713,7 +713,7 @@ class OpenThread(IThci): def getNetworkName(self): """get Thread Network name""" - print ('%s call getNetworkname' % self.port) + print('%s call getNetworkname' % self.port) return self.__sendCommand('networkname')[0] def setChannel(self, channel=11): @@ -729,8 +729,8 @@ class OpenThread(IThci): True: successful to set the channel False: fail to set the channel """ - print ('%s call setChannel' % self.port) - print (channel) + print('%s call setChannel' % self.port) + print(channel) try: cmd = 'channel %s' % channel datasetCmd = 'dataset channel %s' % channel @@ -744,7 +744,7 @@ class OpenThread(IThci): def getChannel(self): """get current channel""" - print ('%s call getChannel' % self.port) + print('%s call getChannel' % self.port) return self.__sendCommand('channel')[0] def setMAC(self, xEUI): @@ -757,8 +757,8 @@ class OpenThread(IThci): True: successful to set the extended address False: fail to set the extended address """ - print ('%s call setMAC' % self.port) - print (xEUI) + print('%s call setMAC' % self.port) + print(xEUI) address64 = '' try: if not xEUI: @@ -770,12 +770,12 @@ class OpenThread(IThci): # prepend 0 at the beginning if len(address64) < 16: address64 = address64.zfill(16) - print (address64) + print(address64) else: address64 = xEUI cmd = 'extaddr %s' % address64 - print (cmd) + print(cmd) if self.__sendCommand(cmd)[-1] == 'Done': self.mac = address64 return True @@ -794,8 +794,8 @@ class OpenThread(IThci): Returns: specific type of MAC address """ - print ('%s call getMAC' % self.port) - print (bType) + print('%s call getMAC' % self.port) + print(bType) # if power down happens, return extended address assigned previously if self.isPowerDown: macAddr64 = self.mac @@ -806,31 +806,31 @@ class OpenThread(IThci): macAddr64 = self.__sendCommand('joiner id')[0] else: macAddr64 = self.__sendCommand('extaddr')[0] - print (macAddr64) + print(macAddr64) return int(macAddr64, 16) def getLL64(self): """get link local unicast IPv6 address""" - print ('%s call getLL64' % self.port) + print('%s call getLL64' % self.port) return self.__sendCommand('ipaddr linklocal')[0] def getRloc16(self): """get rloc16 short address""" - print ('%s call getRloc16' % self.port) + print('%s call getRloc16' % self.port) rloc16 = self.__sendCommand('rloc16')[0] return int(rloc16, 16) def getRloc(self): """get router locator unicast Ipv6 address""" - print ('%s call getRloc' % self.port) + print('%s call getRloc' % self.port) return self.__sendCommand('ipaddr rloc')[0] def __getGlobal(self): """get global unicast IPv6 address set if configuring multiple entries """ - print ('%s call getGlobal' % self.port) + print('%s call getGlobal' % self.port) globalAddrs = [] rlocAddr = self.getRloc() @@ -845,18 +845,18 @@ class OpenThread(IThci): fullIp = ModuleHelper.GetFullIpv6Address(ip6Addr).lower() - print ('address %s' % fullIp) + print('address %s' % fullIp) if fullIp.startswith('fe80'): - print ('link local') + print('link local') continue if fullIp.startswith(rlocAddr[0:19]): - print ('mesh local') + print('mesh local') continue globalAddrs.append(fullIp) - print ('global') + print('global') return globalAddrs @@ -871,8 +871,8 @@ class OpenThread(IThci): False: fail to set the Thread Network master key """ masterKey = '' - print ('%s call setNetworkKey' % self.port) - print (key) + print('%s call setNetworkKey' % self.port) + print(key) try: if not isinstance(key, str): masterKey = self.__convertLongToString(key) @@ -880,7 +880,7 @@ class OpenThread(IThci): # prpend '0' at the beginning if len(masterKey) < 32: masterKey = masterKey.zfill(32) - print (masterKey) + print(masterKey) cmd = 'masterkey %s' % masterKey datasetCmd = 'dataset masterkey %s' % masterKey @@ -902,7 +902,7 @@ class OpenThread(IThci): def getNetworkKey(self): """get the current Thread Network master key""" - print ('%s call getNetwokKey' % self.port) + print('%s call getNetwokKey' % self.port) return self.networkKey def addBlockedMAC(self, xEUI): @@ -915,8 +915,8 @@ class OpenThread(IThci): True: successful to add a given extended address to the blacklist entry False: fail to add a given extended address to the blacklist entry """ - print ('%s call addBlockedMAC' % self.port) - print (xEUI) + print('%s call addBlockedMAC' % self.port) + print(xEUI) if isinstance(xEUI, str): macAddr = xEUI else: @@ -925,7 +925,7 @@ class OpenThread(IThci): try: # if blocked device is itself if macAddr == self.mac: - print ('block device itself') + print('block device itself') return True if self._addressfilterMode != 'blacklist': @@ -933,13 +933,13 @@ class OpenThread(IThci): self._addressfilterMode = 'blacklist' cmd = 'macfilter addr add %s' % macAddr - print (cmd) + print(cmd) ret = self.__sendCommand(cmd)[-1] == 'Done' self._addressfilterSet.add(macAddr) - print ('current blacklist entries:') + print('current blacklist entries:') for addr in self._addressfilterSet: - print (addr) + print(addr) return ret except Exception as e: @@ -957,8 +957,8 @@ class OpenThread(IThci): True: successful to add a given extended address to the whitelist entry False: fail to add a given extended address to the whitelist entry """ - print ('%s call addAllowMAC' % self.port) - print (xEUI) + print('%s call addAllowMAC' % self.port) + print(xEUI) if isinstance(xEUI, str): macAddr = xEUI else: @@ -970,13 +970,13 @@ class OpenThread(IThci): self._addressfilterMode = 'whitelist' cmd = 'macfilter addr add %s' % macAddr - print (cmd) + print(cmd) ret = self.__sendCommand(cmd)[-1] == 'Done' self._addressfilterSet.add(macAddr) - print ('current whitelist entries:') + print('current whitelist entries:') for addr in self._addressfilterSet: - print (addr) + print(addr) return ret except Exception as e: @@ -989,13 +989,13 @@ class OpenThread(IThci): True: successful to clear the blacklist False: fail to clear the blacklist """ - print ('%s call clearBlockList' % self.port) + print('%s call clearBlockList' % self.port) # remove all entries in blacklist try: - print ('clearing blacklist entries:') + print('clearing blacklist entries:') for addr in self._addressfilterSet: - print (addr) + print(addr) # disable blacklist if self.__setAddressfilterMode('disable'): @@ -1018,13 +1018,13 @@ class OpenThread(IThci): True: successful to clear the whitelist False: fail to clear the whitelist """ - print ('%s call clearAllowList' % self.port) + print('%s call clearAllowList' % self.port) # remove all entries in whitelist try: - print ('clearing whitelist entries:') + print('clearing whitelist entries:') for addr in self._addressfilterSet: - print (addr) + print(addr) # disable whitelist if self.__setAddressfilterMode('disable'): @@ -1042,7 +1042,7 @@ class OpenThread(IThci): def getDeviceRole(self): """get current device role in Thread Network""" - print ('%s call getDeviceRole' % self.port) + print('%s call getDeviceRole' % self.port) return self.__sendCommand('state')[0] def joinNetwork(self, eRoleId): @@ -1054,8 +1054,8 @@ class OpenThread(IThci): Returns: True: ready to set Thread Network parameter for joining desired Network """ - print ('%s call joinNetwork' % self.port) - print (eRoleId) + print('%s call joinNetwork' % self.port) + print(eRoleId) self.deviceRole = eRoleId mode = '' @@ -1066,37 +1066,37 @@ class OpenThread(IThci): # FIXME: when Harness call setNetworkDataRequirement()? # only sleep end device requires stable networkdata now if eRoleId == Thread_Device_Role.Leader: - print ('join as leader') + print('join as leader') mode = 'rsdn' if self.AutoDUTEnable is False: # set ROUTER_DOWNGRADE_THRESHOLD self.__setRouterDowngradeThreshold(33) elif eRoleId == Thread_Device_Role.Router: - print ('join as router') + print('join as router') mode = 'rsdn' if self.AutoDUTEnable is False: # set ROUTER_DOWNGRADE_THRESHOLD self.__setRouterDowngradeThreshold(33) elif eRoleId == Thread_Device_Role.SED: - print ('join as sleepy end device') + print('join as sleepy end device') mode = 's' self.__setPollPeriod(self.__sedPollPeriod) elif eRoleId == Thread_Device_Role.EndDevice: - print ('join as end device') + print('join as end device') mode = 'rsn' elif eRoleId == Thread_Device_Role.REED: - print ('join as REED') + print('join as REED') mode = 'rsdn' # set ROUTER_UPGRADE_THRESHOLD self.__setRouterUpgradeThreshold(0) elif eRoleId == Thread_Device_Role.EndDevice_FED: # always remain an ED, never request to be a router - print ('join as FED') + print('join as FED') mode = 'rsdn' # set ROUTER_UPGRADE_THRESHOLD self.__setRouterUpgradeThreshold(0) elif eRoleId == Thread_Device_Role.EndDevice_MED: - print ('join as MED') + print('join as MED') mode = 'rsn' else: pass @@ -1119,9 +1119,9 @@ class OpenThread(IThci): Returns: The Thread network Partition Id """ - print ('%s call getNetworkFragmentID' % self.port) + print('%s call getNetworkFragmentID' % self.port) if not self.__isOpenThreadRunning(): - print ('OpenThread is not running') + print('OpenThread is not running') return None leaderData = [] @@ -1134,7 +1134,7 @@ class OpenThread(IThci): Returns: The extended address of parent in hex format """ - print ('%s call getParentAddress' % self.port) + print('%s call getParentAddress' % self.port) parentInfo = [] parentInfo = self.__sendCommand('parent') @@ -1143,7 +1143,7 @@ class OpenThread(IThci): break elif 'Ext Addr' in line: eui = line.split()[2] - print (eui) + print(eui) # elif 'Rloc' in line: # rloc16 = line.split()[1] # print(rloc16) @@ -1154,13 +1154,13 @@ class OpenThread(IThci): def powerDown(self): """power down the Thread device""" - print ('%s call powerDown' % self.port) + print('%s call powerDown' % self.port) self._sendline('reset') self.isPowerDown = True def powerUp(self): """power up the Thread device""" - print ('%s call powerUp' % self.port) + print('%s call powerUp' % self.port) if not self.handle: self._connect() @@ -1176,7 +1176,7 @@ class OpenThread(IThci): True: successful to reset and rejoin the Thread Network False: fail to reset and rejoin the Thread Network """ - print ('%s call reboot' % self.port) + print('%s call reboot' % self.port) try: self._sendline('reset') self.isPowerDown = True @@ -1186,7 +1186,7 @@ class OpenThread(IThci): time.sleep(3) if self.__sendCommand('state')[0] == 'disabled': - print ('[FAIL] reboot') + print('[FAIL] reboot') return False else: return True @@ -1201,11 +1201,11 @@ class OpenThread(IThci): destination: the unicast destination address of ICMPv6 echo request length: the size of ICMPv6 echo request payload """ - print ('%s call ping' % self.port) - print ('destination: %s' % destination) + print('%s call ping' % self.port) + print('destination: %s' % destination) try: cmd = 'ping %s %s' % (destination, str(length)) - print (cmd) + print(cmd) self._sendline(cmd) self._expect(cmd) # wait echo reply @@ -1221,11 +1221,11 @@ class OpenThread(IThci): destination: the multicast destination address of ICMPv6 echo request length: the size of ICMPv6 echo request payload """ - print ('%s call multicast_Ping' % self.port) - print ('destination: %s' % destination) + print('%s call multicast_Ping' % self.port) + print('destination: %s' % destination) try: cmd = 'ping %s %s' % (destination, str(length)) - print (cmd) + print(cmd) self._sendline(cmd) self._expect(cmd) # wait echo reply @@ -1237,7 +1237,7 @@ class OpenThread(IThci): def getVersionNumber(self): """get OpenThread stack firmware version number""" - print ('%s call getVersionNumber' % self.port) + print('%s call getVersionNumber' % self.port) return self.__sendCommand('version')[0] def setPANID(self, xPAN): @@ -1250,13 +1250,13 @@ class OpenThread(IThci): True: successful to set the Thread Network PAN ID False: fail to set the Thread Network PAN ID """ - print ('%s call setPANID' % self.port) - print (xPAN) + print('%s call setPANID' % self.port) + print(xPAN) panid = '' try: if not isinstance(xPAN, str): panid = str(hex(xPAN)) - print (panid) + print(panid) cmd = 'panid %s' % panid datasetCmd = 'dataset panid %s' % panid @@ -1270,12 +1270,12 @@ class OpenThread(IThci): def getPANID(self): """get current Thread Network PAN ID""" - print ('%s call getPANID' % self.port) + print('%s call getPANID' % self.port) return self.__sendCommand('panid')[0] def reset(self): """factory reset""" - print ('%s call reset' % self.port) + print('%s call reset' % self.port) try: self._sendline('factoryreset') self._read() @@ -1294,14 +1294,14 @@ class OpenThread(IThci): True: successful to remove the router from the Thread Network False: fail to remove the router from the Thread Network """ - print ('%s call removeRouter' % self.port) - print (xRouterId) + print('%s call removeRouter' % self.port) + print(xRouterId) routerId = '' routerId = self.__convertRlocToRouterId(xRouterId) - print (routerId) + print(routerId) if routerId is None: - print ('no matched xRouterId') + print('no matched xRouterId') return False try: @@ -1314,7 +1314,7 @@ class OpenThread(IThci): def setDefaultValues(self): """set default mandatory Thread Network parameter value""" - print ('%s call setDefaultValues' % self.port) + print('%s call setDefaultValues' % self.port) # initialize variables self.networkName = ModuleHelper.Default_NwkName @@ -1370,14 +1370,14 @@ class OpenThread(IThci): def getDeviceConncetionStatus(self): """check if serial port connection is ready or not""" - print ('%s call getDeviceConnectionStatus' % self.port) + print('%s call getDeviceConnectionStatus' % self.port) return self.deviceConnected def getPollingRate(self): """get data polling rate for sleepy end device (in milliseconds) note: not used for now """ - print ('%s call getPollingRate' % self.port) + print('%s call getPollingRate' % self.port) return self.__sendCommand('pollperiod')[0] def setPollingRate(self, iPollingRate): @@ -1390,10 +1390,10 @@ class OpenThread(IThci): True: successful to set the data polling rate for sleepy end device False: fail to set the data polling rate for sleepy end device """ - print ('%s call setPollingRate' % self.port) + print('%s call setPollingRate' % self.port) iPollingRate = int(iPollingRate * 1000) - print (iPollingRate) + print(iPollingRate) if self.__sedPollPeriod != iPollingRate: self.__sedPollPeriod = iPollingRate @@ -1416,7 +1416,7 @@ class OpenThread(IThci): """ try: cmd = 'pollperiod %d' % iPollPeriod - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -1439,9 +1439,9 @@ class OpenThread(IThci): True: successful to set the link quality False: fail to set the link quality """ - print ('%s call setLinkQuality' % self.port) - print (EUIadr) - print (LinkQuality) + print('%s call setLinkQuality' % self.port) + print(EUIadr) + print(LinkQuality) try: # process EUIadr euiHex = hex(EUIadr) @@ -1453,10 +1453,10 @@ class OpenThread(IThci): # prepend 0 at the beginning if len(address64) < 16: address64 = address64.zfill(16) - print (address64) + print(address64) cmd = 'macfilter rss add-lqi %s %s' % (address64, str(LinkQuality)) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -1478,11 +1478,11 @@ class OpenThread(IThci): True: successful to set the link quality False: fail to set the link quality """ - print ('%s call setOutBoundLinkQuality' % self.port) - print (LinkQuality) + print('%s call setOutBoundLinkQuality' % self.port) + print(LinkQuality) try: cmd = 'macfilter rss add-lqi * %s' % str(LinkQuality) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -1499,13 +1499,13 @@ class OpenThread(IThci): True: successful to remove the prefix entry from border router False: fail to remove the prefix entry from border router """ - print ('%s call removeRouterPrefix' % self.port) - print (prefixEntry) + print('%s call removeRouterPrefix' % self.port) + print(prefixEntry) prefix = self.__convertIp6PrefixStringToIp6Address(str(prefixEntry)) try: prefixLen = 64 cmd = 'prefix remove %s/%d' % (prefix, prefixLen) - print (cmd) + print(cmd) if self.__sendCommand(cmd)[-1] == 'Done': # send server data ntf to leader return self.__sendCommand('netdataregister')[-1] == 'Done' @@ -1526,8 +1526,8 @@ class OpenThread(IThci): True: successful to reset and rejoin Thread Network False: fail to reset and rejoin the Thread Network """ - print ('%s call resetAndRejoin' % self.port) - print (timeout) + print('%s call resetAndRejoin' % self.port) + print(timeout) try: self._sendline('reset') self.isPowerDown = True @@ -1540,7 +1540,7 @@ class OpenThread(IThci): time.sleep(3) if self.__sendCommand('state')[0] == 'disabled': - print ('[FAIL] reset and rejoin') + print('[FAIL] reset and rejoin') return False return True except Exception as e: @@ -1575,9 +1575,9 @@ class OpenThread(IThci): True: successful to configure the border router with a given prefix entry False: fail to configure the border router with a given prefix entry """ - print ('%s call configBorderRouter' % self.port) + print('%s call configBorderRouter' % self.port) prefix = self.__convertIp6PrefixStringToIp6Address(str(P_Prefix)) - print (prefix) + print(prefix) try: parameter = '' prf = '' @@ -1608,7 +1608,7 @@ class OpenThread(IThci): pass cmd = 'prefix add %s/64 %s %s' % (prefix, parameter, prf) - print (cmd) + print(cmd) if self.__sendCommand(cmd)[-1] == 'Done': # if prefix configured before starting OpenThread stack # do not send out server data ntf pro-actively @@ -1634,12 +1634,12 @@ class OpenThread(IThci): True: successful to set NETWORK_ID_TIMEOUT False: fail to set NETWORK_ID_TIMEOUT """ - print ('%s call setNetworkIDTimeout' % self.port) - print (iNwkIDTimeOut) + print('%s call setNetworkIDTimeout' % self.port) + print(iNwkIDTimeOut) iNwkIDTimeOut /= 1000 try: cmd = 'networkidtimeout %s' % str(iNwkIDTimeOut) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -1657,12 +1657,12 @@ class OpenThread(IThci): True: successful to set the data poll period for SED False: fail to set the data poll period for SED """ - print ('%s call setKeepAliveTimeOut' % self.port) + print('%s call setKeepAliveTimeOut' % self.port) iTimeOut *= 1000 - print (int(iTimeOut)) + print(int(iTimeOut)) try: cmd = 'pollperiod %d' % int(iTimeOut) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -1679,8 +1679,8 @@ class OpenThread(IThci): True: successful to set the key sequence False: fail to set the key sequence """ - print ('%s call setKeySequenceCounter' % self.port) - print (iKeySequenceValue) + print('%s call setKeySequenceCounter' % self.port) + print(iKeySequenceValue) try: cmd = 'keysequence counter %s' % str(iKeySequenceValue) if self.__sendCommand(cmd)[-1] == 'Done': @@ -1695,7 +1695,7 @@ class OpenThread(IThci): def getKeySequenceCounter(self): """get current Thread Network key sequence""" - print ('%s call getKeySequenceCounter' % self.port) + print('%s call getKeySequenceCounter' % self.port) keySequence = '' keySequence = self.__sendCommand('keysequence counter')[0] return keySequence @@ -1710,13 +1710,13 @@ class OpenThread(IThci): True: successful to increment the key sequence with a given value False: fail to increment the key sequence with a given value """ - print ('%s call incrementKeySequenceCounter' % self.port) - print (iIncrementValue) + print('%s call incrementKeySequenceCounter' % self.port) + print(iIncrementValue) currentKeySeq = '' try: currentKeySeq = self.getKeySequenceCounter() keySequence = int(currentKeySeq, 10) + iIncrementValue - print (keySequence) + print(keySequence) return self.setKeySequenceCounter(keySequence) except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -1733,8 +1733,8 @@ class OpenThread(IThci): Returns: True: successful to set the network requirement """ - print ('%s call setNetworkDataRequirement' % self.port) - print (eDataRequirement) + print('%s call setNetworkDataRequirement' % self.port) + print(eDataRequirement) if eDataRequirement == Device_Data_Requirement.ALL_DATA: self.networkDataRequirement = 'n' @@ -1755,8 +1755,8 @@ class OpenThread(IThci): True: successful to configure the border router with a given external route prefix False: fail to configure the border router with a given external route prefix """ - print ('%s call configExternalRouter' % self.port) - print (P_Prefix) + print('%s call configExternalRouter' % self.port) + print(P_Prefix) stable = '' prefix = self.__convertIp6PrefixStringToIp6Address(str(P_Prefix)) try: @@ -1774,7 +1774,7 @@ class OpenThread(IThci): cmd = 'route add %s/64 %s %s' % (prefix, stable, prf) else: cmd = 'route add %s/64 %s' % (prefix, prf) - print (cmd) + print(cmd) if self.__sendCommand(cmd)[-1] == 'Done': # send server data ntf to leader @@ -1790,15 +1790,15 @@ class OpenThread(IThci): Returns: neighboring routers' extended address """ - print ('%s call getNeighbouringRouters' % self.port) + print('%s call getNeighbouringRouters' % self.port) try: routerInfo = [] routerList = [] routerList = self.__sendCommand('router list')[0].split() - print (routerList) + print(routerList) if 'Done' in routerList: - print ('no neighbouring routers') + print('no neighbouring routers') return None for index in routerList: @@ -1821,7 +1821,7 @@ class OpenThread(IThci): else: pass - print (routerInfo) + print(routerInfo) return routerInfo except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -1834,15 +1834,15 @@ class OpenThread(IThci): Returns: children's extended address """ - print ('%s call getChildrenInfo' % self.port) + print('%s call getChildrenInfo' % self.port) try: childrenInfoAll = [] childrenInfo = {'EUI': 0, 'Rloc16': 0, 'MLEID': ''} childrenList = self.__sendCommand('child list')[0].split() - print (childrenList) + print(childrenList) if 'Done' in childrenList: - print ('no children') + print('no children') return None for index in childrenList: @@ -1871,7 +1871,7 @@ class OpenThread(IThci): childrenInfoAll.append(childrenInfo['EUI']) # childrenInfoAll.append(childrenInfo) - print (childrenInfoAll) + print(childrenInfoAll) return childrenInfoAll except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -1889,8 +1889,8 @@ class OpenThread(IThci): False: fail to set the extended PAN ID """ xpanid = '' - print ('%s call setXpanId' % self.port) - print (xPanId) + print('%s call setXpanId' % self.port) + print(xPanId) try: if not isinstance(xPanId, str): xpanid = self.__convertLongToString(xPanId) @@ -1898,7 +1898,7 @@ class OpenThread(IThci): # prepend '0' at the beginning if len(xpanid) < 16: xpanid = xpanid.zfill(16) - print (xpanid) + print(xpanid) cmd = 'extpanid %s' % xpanid datasetCmd = 'dataset extpanid %s' % xpanid else: @@ -1923,7 +1923,7 @@ class OpenThread(IThci): A list including extended address of neighboring routers, parent as well as children """ - print ('%s call getNeighbouringDevices' % self.port) + print('%s call getNeighbouringDevices' % self.port) neighbourList = [] # get parent info @@ -1943,7 +1943,7 @@ class OpenThread(IThci): for entry in routerNeighbours: neighbourList.append(entry) - print (neighbourList) + print(neighbourList) return neighbourList def setPartationId(self, partationId): @@ -1956,11 +1956,11 @@ class OpenThread(IThci): True: successful to set the Partition ID False: fail to set the Partition ID """ - print ('%s call setPartationId' % self.port) - print (partationId) + print('%s call setPartationId' % self.port) + print(partationId) cmd = 'leaderpartitionid %s' % (str(hex(partationId)).rstrip('L')) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' def getGUA(self, filterByPrefix=None): @@ -1975,8 +1975,8 @@ class OpenThread(IThci): Returns: a global IPv6 address """ - print ('%s call getGUA' % self.port) - print (filterByPrefix) + print('%s call getGUA' % self.port) + print(filterByPrefix) globalAddrs = [] try: # get global addrs set if multiple @@ -1987,26 +1987,26 @@ class OpenThread(IThci): else: for fullIp in globalAddrs: if fullIp.startswith(filterByPrefix): - print ('target global %s' % fullIp) + print('target global %s' % fullIp) return fullIp - print ('no global address matched') + print('no global address matched') return str(globalAddrs[0]) except Exception as e: ModuleHelper.WriteIntoDebugLogger('getGUA() Error: ' + str(e)) def getShortAddress(self): """get Rloc16 short address of Thread device""" - print ('%s call getShortAddress' % self.port) + print('%s call getShortAddress' % self.port) return self.getRloc16() def getULA64(self): """get mesh local EID of Thread device""" - print ('%s call getULA64' % self.port) + print('%s call getULA64' % self.port) return self.__sendCommand('ipaddr mleid')[0] def setMLPrefix(self, sMeshLocalPrefix): """set mesh local prefix""" - print ('%s call setMLPrefix' % self.port) + print('%s call setMLPrefix' % self.port) try: cmd = 'dataset meshlocalprefix %s' % sMeshLocalPrefix self.hasActiveDatasetToCommit = True @@ -2016,7 +2016,7 @@ class OpenThread(IThci): def getML16(self): """get mesh local 16 unicast address (Rloc)""" - print ('%s call getML16' % self.port) + print('%s call getML16' % self.port) return self.getRloc() def downgradeToDevice(self): @@ -2035,11 +2035,11 @@ class OpenThread(IThci): True: successful to set slaac address to Thread interface False: fail to set slaac address to Thread interface """ - print ('%s call forceSetSlaac' % self.port) - print (slaacAddress) + print('%s call forceSetSlaac' % self.port) + print(slaacAddress) try: cmd = 'ipaddr add %s' % str(slaacAddress) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -2051,12 +2051,12 @@ class OpenThread(IThci): def enableAutoDUTObjectFlag(self): """set AutoDUTenable flag""" - print ('%s call enableAutoDUTObjectFlag' % self.port) + print('%s call enableAutoDUTObjectFlag' % self.port) self.AutoDUTEnable = True def getChildTimeoutValue(self): """get child timeout""" - print ('%s call getChildTimeoutValue' % self.port) + print('%s call getChildTimeoutValue' % self.port) childTimeout = self.__sendCommand('childtimeout')[0] return int(childTimeout) @@ -2071,7 +2071,7 @@ class OpenThread(IThci): strDestinationAddr, ' '.join([str(tlv) for tlv in listTLV_ids]), ) - print (cmd) + print(cmd) return self._sendline(cmd) @@ -2086,7 +2086,7 @@ class OpenThread(IThci): strDestinationAddr, ' '.join([str(tlv) for tlv in listTLV_ids]), ) - print (cmd) + print(cmd) return self.__sendCommand(cmd) @@ -2097,10 +2097,10 @@ class OpenThread(IThci): # TODO: Support the whole Native Commissioner functionality # Currently it only aims to trigger a Discovery Request message to pass # Certification test 5.8.4 - print ('%s call startNativeCommissioner' % self.port) + print('%s call startNativeCommissioner' % self.port) self.__sendCommand('ifconfig up') cmd = 'joiner start %s' % (strPSKc) - print (cmd) + print(cmd) if self.__sendCommand(cmd)[-1] == 'Done': return True else: @@ -2113,11 +2113,11 @@ class OpenThread(IThci): True: successful to start Commissioner False: fail to start Commissioner """ - print ('%s call startCollapsedCommissioner' % self.port) + print('%s call startCollapsedCommissioner' % self.port) if self.__startOpenThread(): time.sleep(20) cmd = 'commissioner start' - print (cmd) + print(cmd) if self.__sendCommand(cmd)[-1] == 'Done': self.isActiveCommissioner = True time.sleep(20) # time for petition process @@ -2138,7 +2138,7 @@ class OpenThread(IThci): True: successful to add Joiner's steering data False: fail to add Joiner's steering data """ - print ('%s call scanJoiner' % self.port) + print('%s call scanJoiner' % self.port) # long timeout value to avoid automatic joiner removal (in seconds) timeout = 500 @@ -2149,7 +2149,7 @@ class OpenThread(IThci): # prepend 0 at the beginning if len(eui64) < 16: eui64 = eui64.zfill(16) - print (eui64) + print(eui64) else: eui64 = xEUI @@ -2158,7 +2158,7 @@ class OpenThread(IThci): strPSKd, str(timeout), ) - print (cmd) + print(cmd) if self.__sendCommand(cmd)[-1] == 'Done': if self.logThreadStatus == self.logStatus['stop']: self.logThread = ThreadRunner.run( @@ -2178,7 +2178,7 @@ class OpenThread(IThci): True: successful to set provisioning Url False: fail to set provisioning Url """ - print ('%s call setProvisioningUrl' % self.port) + print('%s call setProvisioningUrl' % self.port) self.provisioningUrl = strURL if self.deviceRole == Thread_Device_Role.Commissioner: cmd = 'commissioner provisioningurl %s' % (strURL) @@ -2192,10 +2192,10 @@ class OpenThread(IThci): True: successful to start commissioner candidate petition process False: fail to start commissioner candidate petition process """ - print ('%s call allowCommission' % self.port) + print('%s call allowCommission' % self.port) try: cmd = 'commissioner start' - print (cmd) + print(cmd) if self.__sendCommand(cmd)[-1] == 'Done': self.isActiveCommissioner = True # time for petition process and at least one keep alive @@ -2218,10 +2218,10 @@ class OpenThread(IThci): True: successful to start joiner False: fail to start joiner """ - print ('%s call joinCommissioned' % self.port) + print('%s call joinCommissioned' % self.port) self.__sendCommand('ifconfig up') cmd = 'joiner start %s %s' % (strPSKd, self.provisioningUrl) - print (cmd) + print(cmd) if self.__sendCommand(cmd)[-1] == 'Done': maxDuration = 150 # seconds self.joinCommissionedStatus = self.joinStatus['ongoing'] @@ -2257,14 +2257,14 @@ class OpenThread(IThci): payload = [] while not rawLogs.empty(): rawLogEach = rawLogs.get() - print (rawLogEach) + print(rawLogEach) if '[THCI]' not in rawLogEach: continue EncryptedPacket = PlatformDiagnosticPacket() infoList = rawLogEach.split('[THCI]')[1].split(']')[0].split('|') for eachInfo in infoList: - print (eachInfo) + print(eachInfo) info = eachInfo.split('=') infoType = info[0].strip() infoValue = info[1].strip() @@ -2337,7 +2337,7 @@ class OpenThread(IThci): True: successful to send MGMT_ED_SCAN message. False: fail to send MGMT_ED_SCAN message """ - print ('%s call MGMT_ED_SCAN' % self.port) + print('%s call MGMT_ED_SCAN' % self.port) channelMask = '' channelMask = '0x' + self.__convertLongToString( self.__convertChannelMask(listChannelMask) @@ -2350,7 +2350,7 @@ class OpenThread(IThci): xScanDuration, sAddr, ) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.writeintodebuglogger( @@ -2369,7 +2369,7 @@ class OpenThread(IThci): True: successful to send MGMT_PANID_QUERY message. False: fail to send MGMT_PANID_QUERY message. """ - print ('%s call MGMT_PANID_QUERY' % self.port) + print('%s call MGMT_PANID_QUERY' % self.port) panid = '' channelMask = '' channelMask = '0x' + self.__convertLongToString( @@ -2381,7 +2381,7 @@ class OpenThread(IThci): try: cmd = 'commissioner panid %s %s %s' % (panid, channelMask, sAddr) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.writeintodebuglogger( @@ -2397,7 +2397,7 @@ class OpenThread(IThci): True: successful to send MGMT_ANNOUNCE_BEGIN message. False: fail to send MGMT_ANNOUNCE_BEGIN message. """ - print ('%s call MGMT_ANNOUNCE_BEGIN' % self.port) + print('%s call MGMT_ANNOUNCE_BEGIN' % self.port) channelMask = '' channelMask = '0x' + self.__convertLongToString( self.__convertChannelMask(listChannelMask) @@ -2409,7 +2409,7 @@ class OpenThread(IThci): xPeriod, sAddr, ) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' except Exception as e: ModuleHelper.writeintodebuglogger( @@ -2423,7 +2423,7 @@ class OpenThread(IThci): True: successful to send MGMT_ACTIVE_GET False: fail to send MGMT_ACTIVE_GET """ - print ('%s call MGMT_ACTIVE_GET' % self.port) + print('%s call MGMT_ACTIVE_GET' % self.port) try: cmd = 'dataset mgmtgetcommand active' @@ -2436,7 +2436,7 @@ class OpenThread(IThci): cmd += ' binary ' cmd += tlvs - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' @@ -2471,7 +2471,7 @@ class OpenThread(IThci): True: successful to send MGMT_ACTIVE_SET False: fail to send MGMT_ACTIVE_SET """ - print ('%s call MGMT_ACTIVE_SET' % self.port) + print('%s call MGMT_ACTIVE_SET' % self.port) try: cmd = 'dataset mgmtsetcommand active' @@ -2608,7 +2608,7 @@ class OpenThread(IThci): if BogusTLV is not None: cmd += '8202aa55' - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' @@ -2624,7 +2624,7 @@ class OpenThread(IThci): True: successful to send MGMT_PENDING_GET False: fail to send MGMT_PENDING_GET """ - print ('%s call MGMT_PENDING_GET' % self.port) + print('%s call MGMT_PENDING_GET' % self.port) try: cmd = 'dataset mgmtgetcommand pending' @@ -2637,7 +2637,7 @@ class OpenThread(IThci): cmd += ' binary ' cmd += tlvs - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' @@ -2665,7 +2665,7 @@ class OpenThread(IThci): True: successful to send MGMT_PENDING_SET False: fail to send MGMT_PENDING_SET """ - print ('%s call MGMT_PENDING_SET' % self.port) + print('%s call MGMT_PENDING_SET' % self.port) try: cmd = 'dataset mgmtsetcommand pending' @@ -2717,7 +2717,7 @@ class OpenThread(IThci): cmd += sessionid - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' @@ -2733,7 +2733,7 @@ class OpenThread(IThci): True: successful to send MGMT_COMM_GET False: fail to send MGMT_COMM_GET """ - print ('%s call MGMT_COMM_GET' % self.port) + print('%s call MGMT_COMM_GET' % self.port) try: cmd = 'commissioner mgmtget' @@ -2742,7 +2742,7 @@ class OpenThread(IThci): cmd += ' binary ' cmd += tlvs - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' @@ -2766,7 +2766,7 @@ class OpenThread(IThci): True: successful to send MGMT_COMM_SET False: fail to send MGMT_COMM_SET """ - print ('%s call MGMT_COMM_SET' % self.port) + print('%s call MGMT_COMM_SET' % self.port) try: cmd = 'commissioner mgmtset' @@ -2794,7 +2794,7 @@ class OpenThread(IThci): cmd += ' binary ' cmd += '000300' + hex(xChannelTlv).lstrip('0x').zfill(4) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' @@ -2804,13 +2804,13 @@ class OpenThread(IThci): ) def setActiveDataset(self, listActiveDataset=[]): - print ('%s call setActiveDataset' % self.port) + print('%s call setActiveDataset' % self.port) def setCommisionerMode(self): - print ('%s call setCommissionerMode' % self.port) + print('%s call setCommissionerMode' % self.port) def setPSKc(self, strPSKc): - print ('%s call setPSKc' % self.port) + print('%s call setPSKc' % self.port) try: cmd = 'dataset pskc %s' % strPSKc self.hasActiveDatasetToCommit = True @@ -2819,7 +2819,7 @@ class OpenThread(IThci): ModuleHelper.WriteIntoDebugLogger('setPSKc() Error: ' + str(e)) def setActiveTimestamp(self, xActiveTimestamp): - print ('%s call setActiveTimestamp' % self.port) + print('%s call setActiveTimestamp' % self.port) try: self.activetimestamp = xActiveTimestamp cmd = 'dataset activetimestamp %s' % str(xActiveTimestamp) @@ -2840,9 +2840,9 @@ class OpenThread(IThci): True: successful to set Joiner UDP Port False: fail to set Joiner UDP Port """ - print ('%s call setUdpJoinerPort' % self.port) + print('%s call setUdpJoinerPort' % self.port) cmd = 'joinerport %d' % portNumber - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' def commissionerUnregister(self): @@ -2852,21 +2852,21 @@ class OpenThread(IThci): True: successful to stop commissioner False: fail to stop commissioner """ - print ('%s call commissionerUnregister' % self.port) + print('%s call commissionerUnregister' % self.port) cmd = 'commissioner stop' - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' def sendBeacons( self, sAddr, xCommissionerSessionId, listChannelMask, xPanId ): - print ('%s call sendBeacons' % self.port) + print('%s call sendBeacons' % self.port) self._sendline('scan') return True def updateRouterStatus(self): """force update to router as if there is child id request""" - print ('%s call updateRouterStatus' % self.port) + print('%s call updateRouterStatus' % self.port) cmd = 'state' while True: state = self.__sendCommand(cmd)[0] @@ -2881,18 +2881,18 @@ class OpenThread(IThci): return self.__sendCommand(cmd)[-1] == 'Done' def setRouterThresholdValues(self, upgradeThreshold, downgradeThreshold): - print ('%s call setRouterThresholdValues' % self.port) + print('%s call setRouterThresholdValues' % self.port) self.__setRouterUpgradeThreshold(upgradeThreshold) self.__setRouterDowngradeThreshold(downgradeThreshold) def setMinDelayTimer(self, iSeconds): - print ('%s call setMinDelayTimer' % self.port) + print('%s call setMinDelayTimer' % self.port) cmd = 'delaytimermin %s' % iSeconds - print (cmd) + print(cmd) return self.__sendCommand(cmd)[-1] == 'Done' def ValidateDeviceFirmware(self): - print ('%s call ValidateDeviceFirmware' % self.port) + print('%s call ValidateDeviceFirmware' % self.port) if 'OPENTHREAD' in self.UIStatusMsg: return True else: diff --git a/tools/harness-thci/OpenThread_WpanCtl.py b/tools/harness-thci/OpenThread_WpanCtl.py index 9ac200038..2e1e6f6d8 100644 --- a/tools/harness-thci/OpenThread_WpanCtl.py +++ b/tools/harness-thci/OpenThread_WpanCtl.py @@ -125,15 +125,15 @@ class OpenThread_WpanCtl(IThci): expected str: the expected string times int: number of trials """ - print ('[%s] Expecting [%s]' % (self.port, expected)) + print('[%s] Expecting [%s]' % (self.port, expected)) retry_times = 10 while times > 0 and retry_times > 0: line = self._readline() - print ('[%s] Got line [%s]' % (self.port, line)) + print('[%s] Got line [%s]' % (self.port, line)) if line == expected: - print ('[%s] Expected [%s]' % (self.port, expected)) + print('[%s] Expected [%s]' % (self.port, expected)) return if not line: @@ -196,7 +196,7 @@ class OpenThread_WpanCtl(IThci): except socket.error: logging.debug('%s: Nothing cleared', self.port) - print ('sending [%s]' % line) + print('sending [%s]' % line) self._write(line + '\r\n') self._lines = [] # wait for write to complete @@ -233,8 +233,7 @@ class OpenThread_WpanCtl(IThci): try: if self._is_net: ssh_stdin, ssh_stdout, ssh_stderr = self.handle.exec_command( - cmd - ) + cmd) else: self._sendline(cmd) self._expect(cmd) @@ -265,9 +264,9 @@ class OpenThread_WpanCtl(IThci): stderr_line.strip(), re.M | re.I, ): - print ('Command failed: %s' % stderr_line) + print('Command failed: %s' % stderr_line) return 'Fail' - print ('Got line: %s' % stderr_line) + print('Got line: %s' % stderr_line) logging.info( '%s: the read line is[%s]', self.port, stderr_line ) @@ -282,9 +281,9 @@ class OpenThread_WpanCtl(IThci): stdout_line.strip(), re.M | re.I, ): - print ('Command failed') + print('Command failed') return 'Fail' - print ('Got line: ' + stdout_line) + print('Got line: ' + stdout_line) logging.info( '%s: send command[%s] done!', self.port, cmd ) @@ -294,7 +293,7 @@ class OpenThread_WpanCtl(IThci): else: while retry_times > 0: line = self._readline() - print ('read line: %s' % line) + print('read line: %s' % line) logging.info('%s: the read line is[%s]', self.port, line) if line: response.append(line) @@ -305,7 +304,7 @@ class OpenThread_WpanCtl(IThci): line, re.M | re.I, ): - print ('Command failed') + print('Command failed') return 'Fail' retry_times -= 1 @@ -350,7 +349,7 @@ class OpenThread_WpanCtl(IThci): segments = ( segments[:empty] + ['0000'] * (8 - len(segments) + 1) - + segments[empty + 1 :] + + segments[empty + 1:] ) return ':'.join(segments) @@ -369,7 +368,7 @@ class OpenThread_WpanCtl(IThci): True: successful to set the device mode False: fail to set the device mode """ - print ('call __setDeviceMode') + print('call __setDeviceMode') try: cmd = WPANCTL_CMD + 'setprop Thread:DeviceMode %d' % mode @@ -390,7 +389,7 @@ class OpenThread_WpanCtl(IThci): True: successful to set the ROUTER_UPGRADE_THRESHOLD False: fail to set ROUTER_UPGRADE_THRESHOLD """ - print ('call __setRouterUpgradeThreshold') + print('call __setRouterUpgradeThreshold') try: cmd = ( WPANCTL_CMD @@ -414,7 +413,7 @@ class OpenThread_WpanCtl(IThci): True: successful to set the ROUTER_DOWNGRADE_THRESHOLD False: fail to set ROUTER_DOWNGRADE_THRESHOLD """ - print ('call __setRouterDowngradeThreshold') + print('call __setRouterDowngradeThreshold') try: cmd = ( WPANCTL_CMD @@ -437,7 +436,7 @@ class OpenThread_WpanCtl(IThci): True: successful to set the ROUTER_SELECTION_JITTER False: fail to set ROUTER_SELECTION_JITTER """ - print ('call _setRouterSelectionJitter') + print('call _setRouterSelectionJitter') try: cmd = ( WPANCTL_CMD @@ -457,14 +456,14 @@ class OpenThread_WpanCtl(IThci): True: successful to set address filter mode. False: fail to set address filter mode. """ - print ('call setAddressFilterMode() %s' % mode) + print('call setAddressFilterMode() %s' % mode) try: if re.match('list', mode, re.M | re.I): cmd = WPANCTL_CMD + 'setprop MAC:' + mode + ':Enabled 1' elif mode == 'disabled': cmd = WPANCTL_CMD + 'setprop MAC:' + mode + ':Enabled 0' else: - print ('no such option') + print('no such option') return False if self.__sendCommand(cmd)[0] != 'Fail': return True @@ -481,7 +480,7 @@ class OpenThread_WpanCtl(IThci): True: successful to start OpenThreadWpan up False: fail to start OpenThreadWpan """ - print ('call startOpenThreadWpan') + print('call startOpenThreadWpan') try: # restore whitelist/blacklist address filter mode if rejoin after @@ -570,7 +569,7 @@ class OpenThread_WpanCtl(IThci): True: successfully stop OpenThreadWpan False: failed to stop OpenThreadWpan """ - print ('call stopOpenThreadWpan') + print('call stopOpenThreadWpan') try: if ( self.__sendCommand(WPANCTL_CMD + 'leave')[0] != 'Fail' @@ -592,17 +591,17 @@ class OpenThread_WpanCtl(IThci): True: OpenThreadWpan is running False: OpenThreadWpan is not running """ - print ('call __isOpenThreadWpanRunning') + print('call __isOpenThreadWpanRunning') if ( self.__stripValue( self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:State')[0] ) == 'associated' ): - print ('*****OpenThreadWpan is running') + print('*****OpenThreadWpan is running') return True else: - print ('*****Wrong OpenThreadWpan state') + print('*****Wrong OpenThreadWpan state') return False # rloc16 might be hex string or integer, need to return actual allocated @@ -620,8 +619,8 @@ class OpenThread_WpanCtl(IThci): routerList = self.__sendCommand( WPANCTL_CMD + 'getprop -v Thread:RouterTable' ) - print (routerList) - print (xRloc16) + print(routerList) + print(xRloc16) for line in routerList: if re.match(r'\[|\]', line): @@ -724,14 +723,14 @@ class OpenThread_WpanCtl(IThci): if len(channelList): chan_mask_range = ','.join(str(chan) for chan in channelList) else: - print ('empty list') + print('empty list') else: - print ('not a valid channel list: %s' % channelList) + print('not a valid channel list: %s' % channelList) return chan_mask_range def __setChannelMask(self, channelMask): - print ('call _setChannelMask') + print('call _setChannelMask') try: cmd = WPANCTL_CMD + 'setprop NCP:ChannelMask %s' % channelMask datasetCmd = ( @@ -749,7 +748,7 @@ class OpenThread_WpanCtl(IThci): ) def __setSecurityPolicy(self, securityPolicySecs, securityPolicyFlags): - print ('call _setSecurityPolicy') + print('call _setSecurityPolicy') try: cmd1 = ( WPANCTL_CMD @@ -759,7 +758,7 @@ class OpenThread_WpanCtl(IThci): if securityPolicyFlags == 'onrcb': cmd2 = WPANCTL_CMD + 'setprop Dataset:SecPolicy:Flags 0xff' else: - print ('unknown policy flag :' + securityPolicyFlags) + print('unknown policy flag :' + securityPolicyFlags) return False self.hasActiveDatasetToCommit = True return ( @@ -781,8 +780,8 @@ class OpenThread_WpanCtl(IThci): True: successful to set key switch guard time False: fail to set key switch guard time """ - print ('%s call setKeySwitchGuardTime' % self.port) - print (iKeySwitchGuardTime) + print('%s call setKeySwitchGuardTime' % self.port) + print(iKeySwitchGuardTime) try: cmd = WPANCTL_CMD + 'setprop Network:KeySwitchGuardTime %s' % str( iKeySwitchGuardTime @@ -799,7 +798,7 @@ class OpenThread_WpanCtl(IThci): def __getCommissionerSessionId(self): """ get the commissioner session id allocated from Leader """ - print ('%s call getCommissionerSessionId' % self.port) + print('%s call getCommissionerSessionId' % self.port) return self.__sendCommand( WPANCTL_CMD + 'getprop -v Commissioner:SessionId' )[0] @@ -823,7 +822,7 @@ class OpenThread_WpanCtl(IThci): def _connect(self): if self.connectType == 'usb': - print ('My port is %s' % self.port) + print('My port is %s' % self.port) try: self.handle = serial.Serial(self.port, 115200, timeout=0.2) except Exception as e: @@ -838,7 +837,7 @@ class OpenThread_WpanCtl(IThci): while attempts < 10 or pwd_prompted: time.sleep(0.5) attempts = attempts + 1 - print ('attempts...%d' % attempts) + print('attempts...%d' % attempts) input_data = self.handle.read(self.handle.inWaiting()) @@ -851,17 +850,17 @@ class OpenThread_WpanCtl(IThci): if 'login' in input_data: self.handle.write(WPAN_CARRIER_USER + '\n') time.sleep(0.3) - print ('user prompted') + print('user prompted') user_prompted = True elif 'Password' in input_data: - print ('password prompted') + print('password prompted') time.sleep(0.3) self.handle.write(WPAN_CARRIER_PASSWD + '\n') pwd_prompted = True elif WPAN_CARRIER_PROMPT in input_data: - print ('login success (serial)') + print('login success (serial)') time.sleep(0.3) self.deviceConnected = True self.handle.write('stty cols 256\n') @@ -877,7 +876,7 @@ class OpenThread_WpanCtl(IThci): ) elif self.connectType == 'ip': - print ('My IP: %s Port: %s' % (self.dutIpv4, self.dutPort)) + print('My IP: %s Port: %s' % (self.dutIpv4, self.dutPort)) try: import paramiko @@ -891,7 +890,7 @@ class OpenThread_WpanCtl(IThci): username=WPAN_CARRIER_USER, password=WPAN_CARRIER_PASSWD, ) - print ('login success (ssh)') + print('login success (ssh)') self.deviceConnected = True self.handle.exec_command('stty cols 256\n') time.sleep(1) @@ -905,7 +904,7 @@ class OpenThread_WpanCtl(IThci): def closeConnection(self): """close current serial port connection""" - print ('%s call closeConnection' % self.port) + print('%s call closeConnection' % self.port) try: if self.handle: self.handle.close() @@ -917,7 +916,7 @@ class OpenThread_WpanCtl(IThci): def intialize(self): """initialize the serial port with baudrate, timeout parameters""" - print ('%s call intialize' % self.port) + print('%s call intialize' % self.port) try: # init serial port self.deviceConnected = False @@ -954,7 +953,7 @@ class OpenThread_WpanCtl(IThci): True: successful to set the Thread Networkname False: fail to set the Thread Networkname """ - print ('%s call setNetworkName' % self.port) + print('%s call setNetworkName' % self.port) try: cmd = WPANCTL_CMD + 'setprop -s Network:Name %s' % networkName @@ -973,7 +972,7 @@ class OpenThread_WpanCtl(IThci): def getNetworkName(self): """get Thread Network name""" - print ('%s call getNetworkname' % self.port) + print('%s call getNetworkname' % self.port) networkName = self.__sendCommand( WPANCTL_CMD + 'getprop -v Network:Name' )[0] @@ -992,7 +991,7 @@ class OpenThread_WpanCtl(IThci): True: successful to set the channel False: fail to set the channel """ - print ('%s call setChannel' % self.port) + print('%s call setChannel' % self.port) try: cmd = WPANCTL_CMD + 'setprop NCP:Channel %s' % channel @@ -1007,7 +1006,7 @@ class OpenThread_WpanCtl(IThci): def getChannel(self): """get current channel""" - print ('%s call getChannel' % self.port) + print('%s call getChannel' % self.port) return self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:Channel')[0] def setMAC(self, xEUI): @@ -1020,7 +1019,7 @@ class OpenThread_WpanCtl(IThci): True: successful to set the extended address False: fail to set the extended address """ - print ('%s call setMAC' % self.port) + print('%s call setMAC' % self.port) address64 = '' try: @@ -1033,7 +1032,7 @@ class OpenThread_WpanCtl(IThci): # prepend 0 at the beginning if len(address64) < 16: address64 = address64.zfill(16) - print (address64) + print(address64) else: address64 = xEUI @@ -1057,7 +1056,7 @@ class OpenThread_WpanCtl(IThci): Returns: specific type of MAC address """ - print ('%s call getMAC' % self.port) + print('%s call getMAC' % self.port) # if power down happens, return extended address assigned previously if self.isPowerDown: @@ -1086,7 +1085,7 @@ class OpenThread_WpanCtl(IThci): def getLL64(self): """get link local unicast IPv6 address""" - print ('%s call getLL64' % self.port) + print('%s call getLL64' % self.port) return self.__stripValue( self.__sendCommand( WPANCTL_CMD + 'getprop -v IPv6:LinkLocalAddress' @@ -1095,7 +1094,7 @@ class OpenThread_WpanCtl(IThci): def getMLEID(self): """get mesh local endpoint identifier address""" - print ('%s call getMLEID' % self.port) + print('%s call getMLEID' % self.port) return self.__stripValue( self.__sendCommand( WPANCTL_CMD + 'getprop -v IPv6:MeshLocalAddress' @@ -1104,7 +1103,7 @@ class OpenThread_WpanCtl(IThci): def getRloc16(self): """get rloc16 short address""" - print ('%s call getRloc16' % self.port) + print('%s call getRloc16' % self.port) rloc16 = self.__sendCommand(WPANCTL_CMD + 'getprop -v Thread:RLOC16')[ 0 ] @@ -1112,7 +1111,7 @@ class OpenThread_WpanCtl(IThci): def getRloc(self): """get router locator unicast IPv6 address""" - print ('%s call getRloc' % self.port) + print('%s call getRloc' % self.port) prefix = self.__stripValue( self.__sendCommand( WPANCTL_CMD + 'getprop -v IPv6:MeshLocalPrefix' @@ -1122,19 +1121,19 @@ class OpenThread_WpanCtl(IThci): rloc16 = self.__sendCommand(WPANCTL_CMD + 'getprop -v Thread:RLOC16')[ 0 ].lstrip('0x') - print ('prefix: %s' % prefix) - print ('mlprefix: %s ' % mlprefix) - print ('rloc16: %s' % rloc16) + print('prefix: %s' % prefix) + print('mlprefix: %s ' % mlprefix) + print('rloc16: %s' % rloc16) rloc = self.__padIp6Addr(mlprefix + '00ff:fe00:' + rloc16) - print ('rloc: %s' % rloc) + print('rloc: %s' % rloc) return rloc def getGlobal(self): """get global unicast IPv6 address set if configuring multiple entries """ - print ('%s call getGlobal' % self.port) + print('%s call getGlobal' % self.port) globalAddrs = [] mleid = self.__stripValue( @@ -1161,7 +1160,7 @@ class OpenThread_WpanCtl(IThci): fullIp = ModuleHelper.GetFullIpv6Address(ip6Addr).lower() - print ('fullip %s' % fullIp) + print('fullip %s' % fullIp) if fullIp.startswith('fe80'): continue @@ -1169,7 +1168,7 @@ class OpenThread_WpanCtl(IThci): if fullIp.startswith(mleid[0:19]): continue - print ('global') + print('global') globalAddrs.append(fullIp) return globalAddrs @@ -1185,7 +1184,7 @@ class OpenThread_WpanCtl(IThci): False: fail to set the Thread Network master key """ masterKey = '' - print ('%s call setNetworkKey' % self.port) + print('%s call setNetworkKey' % self.port) try: if not isinstance(key, str): @@ -1219,7 +1218,7 @@ class OpenThread_WpanCtl(IThci): def getNetworkKey(self): """get the current Thread Network master key""" - print ('%s call getNetwokKey' % self.port) + print('%s call getNetwokKey' % self.port) return self.networkKey def addBlockedMAC(self, xEUI): @@ -1232,8 +1231,8 @@ class OpenThread_WpanCtl(IThci): True: successful to add a given extended address to the blacklist entry False: fail to add a given extended address to the blacklist entry """ - print ('%s call addBlockedMAC' % self.port) - print (xEUI) + print('%s call addBlockedMAC' % self.port) + print(xEUI) if isinstance(xEUI, str): macAddr = xEUI else: @@ -1242,7 +1241,7 @@ class OpenThread_WpanCtl(IThci): try: # if blocked device is itself if macAddr == self.mac: - print ('block device itself') + print('block device itself') return True if self._addressfilterMode != 'blacklist': @@ -1253,9 +1252,9 @@ class OpenThread_WpanCtl(IThci): ret = self.__sendCommand(cmd)[0] != 'Fail' self._addressfilterSet.add(macAddr) - print ('current blacklist entries:') + print('current blacklist entries:') for addr in self._addressfilterSet: - print (addr) + print(addr) return ret except Exception as e: @@ -1273,8 +1272,8 @@ class OpenThread_WpanCtl(IThci): True: successful to add a given extended address to the whitelist entry False: fail to add a given extended address to the whitelist entry """ - print ('%s call addAllowMAC' % self.port) - print (xEUI) + print('%s call addAllowMAC' % self.port) + print(xEUI) if isinstance(xEUI, str): macAddr = xEUI else: @@ -1289,9 +1288,9 @@ class OpenThread_WpanCtl(IThci): ret = self.__sendCommand(cmd)[0] != 'Fail' self._addressfilterSet.add(macAddr) - print ('current whitelist entries:') + print('current whitelist entries:') for addr in self._addressfilterSet: - print (addr) + print(addr) return ret except Exception as e: @@ -1304,13 +1303,13 @@ class OpenThread_WpanCtl(IThci): True: successful to clear the blacklist False: fail to clear the blacklist """ - print ('%s call clearBlockList' % self.port) + print('%s call clearBlockList' % self.port) # remove all entries in blacklist try: - print ('clearing blacklist entries:') + print('clearing blacklist entries:') for addr in self._addressfilterSet: - print (addr) + print(addr) # disable blacklist if self.__setAddressfilterMode('disable'): @@ -1333,13 +1332,13 @@ class OpenThread_WpanCtl(IThci): True: successful to clear the whitelist False: fail to clear the whitelist """ - print ('%s call clearAllowList' % self.port) + print('%s call clearAllowList' % self.port) # remove all entries in whitelist try: - print ('clearing whitelist entries:') + print('clearing whitelist entries:') for addr in self._addressfilterSet: - print (addr) + print(addr) # disable whitelist if self.__setAddressfilterMode('disable'): @@ -1357,7 +1356,7 @@ class OpenThread_WpanCtl(IThci): def getDeviceRole(self): """get current device role in Thread Network""" - print ('%s call getDeviceRole' % self.port) + print('%s call getDeviceRole' % self.port) return self.__stripValue( self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:NodeType')[0] ) @@ -1371,8 +1370,8 @@ class OpenThread_WpanCtl(IThci): Returns: True: ready to set Thread Network parameter for joining desired Network """ - print ('%s call joinNetwork' % self.port) - print (eRoleId) + print('%s call joinNetwork' % self.port) + print(eRoleId) self.deviceRole = eRoleId mode = 15 @@ -1383,43 +1382,43 @@ class OpenThread_WpanCtl(IThci): # FIXME: when Harness call setNetworkDataRequirement()? # only sleep end device requires stable networkdata now if eRoleId == Thread_Device_Role.Leader: - print ('join as leader') + print('join as leader') # rsdn mode = 15 if self.AutoDUTEnable is False: # set ROUTER_DOWNGRADE_THRESHOLD self.__setRouterDowngradeThreshold(33) elif eRoleId == Thread_Device_Role.Router: - print ('join as router') + print('join as router') # rsdn mode = 15 if self.AutoDUTEnable is False: # set ROUTER_DOWNGRADE_THRESHOLD self.__setRouterDowngradeThreshold(33) elif eRoleId == Thread_Device_Role.SED: - print ('join as sleepy end device') + print('join as sleepy end device') # s mode = 4 self.__setPollPeriod(self.__sedPollPeriod) elif eRoleId == Thread_Device_Role.EndDevice: - print ('join as end device') + print('join as end device') # rsn mode = 13 elif eRoleId == Thread_Device_Role.REED: - print ('join as REED') + print('join as REED') # rsdn mode = 15 # set ROUTER_UPGRADE_THRESHOLD self.__setRouterUpgradeThreshold(0) elif eRoleId == Thread_Device_Role.EndDevice_FED: # always remain an ED, never request to be a router - print ('join as FED') + print('join as FED') # rsdn mode = 15 # set ROUTER_UPGRADE_THRESHOLD self.__setRouterUpgradeThreshold(0) elif eRoleId == Thread_Device_Role.EndDevice_MED: - print ('join as MED') + print('join as MED') # rsn mode = 13 else: @@ -1442,9 +1441,9 @@ class OpenThread_WpanCtl(IThci): Returns: The Thread network Partition Id """ - print ('%s call getNetworkFragmentID' % self.port) + print('%s call getNetworkFragmentID' % self.port) if not self.____isOpenThreadWpanRunning(): - print ('OpenThreadWpan is not running') + print('OpenThreadWpan is not running') return None return self.__sendCommand( @@ -1457,7 +1456,7 @@ class OpenThread_WpanCtl(IThci): Returns: The extended address of parent in hex format """ - print ('%s call getParentAddress' % self.port) + print('%s call getParentAddress' % self.port) parentInfo = [] parentInfo = self.__stripValue( self.__sendCommand(WPANCTL_CMD + 'getprop -v Thread:Parent') @@ -1467,7 +1466,7 @@ class OpenThread_WpanCtl(IThci): def powerDown(self): """power down the OpenThreadWpan""" - print ('%s call powerDown' % self.port) + print('%s call powerDown' % self.port) if ( self.__sendCommand( WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset false' @@ -1485,7 +1484,7 @@ class OpenThread_WpanCtl(IThci): def powerUp(self): """power up the Thread device""" - print ('%s call powerUp' % self.port) + print('%s call powerUp' % self.port) if not self.handle: self._connect() @@ -1509,7 +1508,7 @@ class OpenThread_WpanCtl(IThci): ) != 'associated' ): - print ('powerUp failed') + print('powerUp failed') return False else: return True @@ -1521,7 +1520,7 @@ class OpenThread_WpanCtl(IThci): True: successful to reset and rejoin the Thread Network False: fail to reset and rejoin the Thread Network """ - print ('%s call reboot' % self.port) + print('%s call reboot' % self.port) try: self._sendline(WPANCTL_CMD + 'reset') self.isPowerDown = True @@ -1530,7 +1529,7 @@ class OpenThread_WpanCtl(IThci): self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:State')[0] != 'associated' ): - print ('[FAIL] reboot') + print('[FAIL] reboot') return False else: return True @@ -1545,8 +1544,8 @@ class OpenThread_WpanCtl(IThci): destination: the unicast destination address of ICMPv6 echo request length: the size of ICMPv6 echo request payload """ - print ('%s call ping' % self.port) - print ('destination: %s' % destination) + print('%s call ping' % self.port) + print('destination: %s' % destination) try: cmd = 'ping %s -c 1 -s %s -I %s' % ( destination, @@ -1573,8 +1572,8 @@ class OpenThread_WpanCtl(IThci): destination: the multicast destination address of ICMPv6 echo request length: the size of ICMPv6 echo request payload """ - print ('%s call multicast_Ping' % self.port) - print ('destination: %s' % destination) + print('%s call multicast_Ping' % self.port) + print('destination: %s' % destination) try: cmd = 'ping %s -c 1 -s %s -I %s' % ( destination, @@ -1597,7 +1596,7 @@ class OpenThread_WpanCtl(IThci): def getVersionNumber(self): """get OpenThreadWpan stack firmware version number""" - print ('%s call getVersionNumber' % self.port) + print('%s call getVersionNumber' % self.port) versionStr = self.__sendCommand( WPANCTL_CMD + 'getprop -v NCP:Version' )[0] @@ -1614,13 +1613,13 @@ class OpenThread_WpanCtl(IThci): True: successful to set the Thread Network PAN ID False: fail to set the Thread Network PAN ID """ - print ('%s call setPANID' % self.port) - print (xPAN) + print('%s call setPANID' % self.port) + print(xPAN) panid = '' try: if not isinstance(xPAN, str): panid = str(hex(xPAN)) - print (panid) + print(panid) cmd = WPANCTL_CMD + 'setprop -s Network:PANID %s' % panid datasetCmd = WPANCTL_CMD + 'setprop Dataset:PanId %s' % panid @@ -1634,12 +1633,12 @@ class OpenThread_WpanCtl(IThci): def getPANID(self): """get current Thread Network PAN ID""" - print ('%s call getPANID' % self.port) + print('%s call getPANID' % self.port) return self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:PANID')[0] def reset(self): """factory reset""" - print ('%s call reset' % self.port) + print('%s call reset' % self.port) try: if self._is_net: self.__sendCommand(WPANCTL_CMD + 'leave') @@ -1663,14 +1662,14 @@ class OpenThread_WpanCtl(IThci): True: successful to remove the router from the Thread Network False: fail to remove the router from the Thread Network """ - print ('%s call removeRouter' % self.port) - print (xRouterId) + print('%s call removeRouter' % self.port) + print(xRouterId) routerId = '' routerId = self.__convertRlocToRouterId(xRouterId) - print (routerId) + print(routerId) if routerId is None: - print ('no matched xRouterId') + print('no matched xRouterId') return False try: @@ -1683,7 +1682,7 @@ class OpenThread_WpanCtl(IThci): def setDefaultValues(self): """set default mandatory Thread Network parameter value""" - print ('%s call setDefaultValues' % self.port) + print('%s call setDefaultValues' % self.port) # initialize variables self.networkName = ModuleHelper.Default_NwkName @@ -1738,14 +1737,14 @@ class OpenThread_WpanCtl(IThci): def getDeviceConncetionStatus(self): """check if serial port connection is ready or not""" - print ('%s call getDeviceConnectionStatus' % self.port) + print('%s call getDeviceConnectionStatus' % self.port) return self.deviceConnected def getPollingRate(self): """get data polling rate for sleepy end device (in milliseconds) note: not used for now """ - print ('%s call getPollingRate' % self.port) + print('%s call getPollingRate' % self.port) return self.__sendCommand( WPANCTL_CMD + 'getprop -v NCP:SleepyPollInterval' )[0] @@ -1760,10 +1759,10 @@ class OpenThread_WpanCtl(IThci): True: successful to set the data polling rate for sleepy end device False: fail to set the data polling rate for sleepy end device """ - print ('%s call setPollingRate' % self.port) + print('%s call setPollingRate' % self.port) iPollingRate = int(iPollingRate * 1000) - print (iPollingRate) + print(iPollingRate) if self.__sedPollPeriod != iPollingRate: self.__sedPollPeriod = iPollingRate @@ -1788,7 +1787,7 @@ class OpenThread_WpanCtl(IThci): cmd = WPANCTL_CMD + 'setprop NCP:SleepyPollInterval %s' % str( iPollPeriod ) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[0] != 'Fail' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -1813,7 +1812,6 @@ class OpenThread_WpanCtl(IThci): @todo: required if as reference device """ - pass def setOutBoundLinkQuality(self, LinkQuality): """set custom LinkQualityIn for all receiving messages from the any address @@ -1832,7 +1830,6 @@ class OpenThread_WpanCtl(IThci): @todo: required if as reference device """ - pass def removeRouterPrefix(self, prefixEntry): """remove the configured prefix on a border router @@ -1846,7 +1843,6 @@ class OpenThread_WpanCtl(IThci): @todo: required if as reference device """ - pass def resetAndRejoin(self, timeout): """reset and join back Thread Network with a given timeout delay @@ -1858,8 +1854,8 @@ class OpenThread_WpanCtl(IThci): True: successful to reset and rejoin Thread Network False: fail to reset and rejoin the Thread Network """ - print ('%s call resetAndRejoin' % self.port) - print (timeout) + print('%s call resetAndRejoin' % self.port) + print(timeout) try: if ( self.__sendCommand( @@ -1899,7 +1895,7 @@ class OpenThread_WpanCtl(IThci): ) != 'associated' ): - print ('[FAIL] reset and rejoin') + print('[FAIL] reset and rejoin') return False return True except Exception as e: @@ -1934,9 +1930,9 @@ class OpenThread_WpanCtl(IThci): True: successful to configure the border router with a given prefix entry False: fail to configure the border router with a given prefix entry """ - print ('%s call configBorderRouter' % self.port) + print('%s call configBorderRouter' % self.port) prefix = self.__convertIp6PrefixStringToIp6Address(str(P_Prefix)) - print (prefix) + print(prefix) try: parameter = '' @@ -1960,8 +1956,8 @@ class OpenThread_WpanCtl(IThci): parameter, P_preference, ) - print (parameter) - print (cmd) + print(parameter) + print(cmd) if self.__sendCommand(cmd)[0] != 'Fail': return True else: @@ -1983,7 +1979,6 @@ class OpenThread_WpanCtl(IThci): @todo: required if as reference device """ - pass def setKeepAliveTimeOut(self, iTimeOut): """set keep alive timeout for device @@ -1996,13 +1991,13 @@ class OpenThread_WpanCtl(IThci): True: successful to set the data poll period for SED False: fail to set the data poll period for SED """ - print ('%s call setKeepAliveTimeOut' % self.port) - print (iTimeOut) + print('%s call setKeepAliveTimeOut' % self.port) + print(iTimeOut) try: cmd = WPANCTL_CMD + 'setprop NCP:SleepyPollInterval %s' % str( iTimeOut * 1000 ) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[0] != 'Fail' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -2019,8 +2014,8 @@ class OpenThread_WpanCtl(IThci): True: successful to set the key sequence False: fail to set the key sequence """ - print ('%s call setKeySequenceCounter' % self.port) - print (iKeySequenceValue) + print('%s call setKeySequenceCounter' % self.port) + print(iKeySequenceValue) try: cmd = WPANCTL_CMD + 'setprop Network:KeyIndex %s' % str( iKeySequenceValue @@ -2037,7 +2032,7 @@ class OpenThread_WpanCtl(IThci): def getKeySequenceCounter(self): """get current Thread Network key sequence""" - print ('%s call getKeySequenceCounter' % self.port) + print('%s call getKeySequenceCounter' % self.port) keySequence = '' keySequence = self.__sendCommand( WPANCTL_CMD + 'getprop -v Network:KeyIndex' @@ -2054,13 +2049,13 @@ class OpenThread_WpanCtl(IThci): True: successful to increment the key sequence with a given value False: fail to increment the key sequence with a given value """ - print ('%s call incrementKeySequenceCounter' % self.port) - print (iIncrementValue) + print('%s call incrementKeySequenceCounter' % self.port) + print(iIncrementValue) currentKeySeq = '' try: currentKeySeq = self.getKeySequenceCounter() keySequence = int(currentKeySeq, 10) + iIncrementValue - print (keySequence) + print(keySequence) return self.setKeySequenceCounter(keySequence) except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -2077,8 +2072,8 @@ class OpenThread_WpanCtl(IThci): Returns: True: successful to set the network requirement """ - print ('%s call setNetworkDataRequirement' % self.port) - print (eDataRequirement) + print('%s call setNetworkDataRequirement' % self.port) + print(eDataRequirement) if eDataRequirement == Device_Data_Requirement.ALL_DATA: self.networkDataRequirement = 'n' @@ -2099,8 +2094,8 @@ class OpenThread_WpanCtl(IThci): True: successful to configure the border router with a given external route prefix False: fail to configure the border router with a given external route prefix """ - print ('%s call configExternalRouter' % self.port) - print (P_Prefix) + print('%s call configExternalRouter' % self.port) + print(P_Prefix) prefix = self.__convertIp6PrefixStringToIp6Address(str(P_Prefix)) try: if P_stable: @@ -2113,7 +2108,7 @@ class OpenThread_WpanCtl(IThci): prefix, R_Preference, ) - print (cmd) + print(cmd) if self.__sendCommand(cmd)[0] != 'Fail': return True @@ -2132,7 +2127,6 @@ class OpenThread_WpanCtl(IThci): @todo: required if as reference device """ - pass def getChildrenInfo(self): """get all children information @@ -2142,7 +2136,6 @@ class OpenThread_WpanCtl(IThci): @todo: required if as reference device """ - pass def setXpanId(self, xPanId): """set extended PAN ID of Thread Network @@ -2155,8 +2148,8 @@ class OpenThread_WpanCtl(IThci): False: fail to set the extended PAN ID """ xpanid = '' - print ('%s call setXpanId' % self.port) - print (xPanId) + print('%s call setXpanId' % self.port) + print(xPanId) try: if not isinstance(xPanId, str): xpanid = self.__convertLongToString(xPanId) @@ -2164,7 +2157,7 @@ class OpenThread_WpanCtl(IThci): # prepend '0' at the beginning if len(xpanid) < 16: xpanid = xpanid.zfill(16) - print (xpanid) + print(xpanid) cmd = WPANCTL_CMD + 'setprop Network:XPANID %s' % xpanid datasetCmd = ( WPANCTL_CMD @@ -2194,7 +2187,7 @@ class OpenThread_WpanCtl(IThci): A list including extended address of neighboring routers, parent as well as children """ - print ('%s call getNeighbouringDevices' % self.port) + print('%s call getNeighbouringDevices' % self.port) neighbourList = [] # get parent info @@ -2214,7 +2207,7 @@ class OpenThread_WpanCtl(IThci): for entry in routerNeighbours: neighbourList.append(entry) - print (neighbourList) + print(neighbourList) return neighbourList def setPartationId(self, partationId): @@ -2227,13 +2220,13 @@ class OpenThread_WpanCtl(IThci): True: successful to set the Partition ID False: fail to set the Partition ID """ - print ('%s call setPartationId' % self.port) - print (partationId) + print('%s call setPartationId' % self.port) + print(partationId) cmd = WPANCTL_CMD + 'setprop Network:PartitionId %s' % ( str(hex(partationId)).rstrip('L') ) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[0] != 'Fail' def getGUA(self, filterByPrefix=None): @@ -2248,8 +2241,8 @@ class OpenThread_WpanCtl(IThci): Returns: a global IPv6 address """ - print ('%s call getGUA' % self.port) - print (filterByPrefix) + print('%s call getGUA' % self.port) + print(filterByPrefix) globalAddrs = [] try: # get global addrs set if multiple @@ -2260,9 +2253,9 @@ class OpenThread_WpanCtl(IThci): else: for fullIp in globalAddrs: if fullIp.startswith(filterByPrefix): - print ('target global %s' % fullIp) + print('target global %s' % fullIp) return fullIp - print ('no global address matched') + print('no global address matched') return str(globalAddrs[0]) except Exception as e: ModuleHelper.WriteIntoDebugLogger('getGUA() Error: ' + str(e)) @@ -2270,17 +2263,17 @@ class OpenThread_WpanCtl(IThci): def getShortAddress(self): """get Rloc16 short address of Thread device""" - print ('%s call getShortAddress' % self.port) + print('%s call getShortAddress' % self.port) return self.getRloc16() def getULA64(self): """get mesh local EID of Thread device""" - print ('%s call getULA64' % self.port) + print('%s call getULA64' % self.port) return self.getMLEID() def setMLPrefix(self, sMeshLocalPrefix): """set mesh local prefix""" - print ('%s call setMLPrefix' % self.port) + print('%s call setMLPrefix' % self.port) try: cmd = ( WPANCTL_CMD @@ -2300,7 +2293,7 @@ class OpenThread_WpanCtl(IThci): def getML16(self): """get mesh local 16 unicast address (Rloc)""" - print ('%s call getML16' % self.port) + print('%s call getML16' % self.port) return self.getRloc() def downgradeToDevice(self): @@ -2311,19 +2304,18 @@ class OpenThread_WpanCtl(IThci): def forceSetSlaac(self, slaacAddress): """@todo : required if as reference device""" - pass def setSleepyNodePollTime(self): pass def enableAutoDUTObjectFlag(self): """set AutoDUTenable flag""" - print ('%s call enableAutoDUTObjectFlag' % self.port) + print('%s call enableAutoDUTObjectFlag' % self.port) self.AutoDUTEnable = True def getChildTimeoutValue(self): """get child timeout""" - print ('%s call getChildTimeoutValue' % self.port) + print('%s call getChildTimeoutValue' % self.port) childTimeout = self.__sendCommand( WPANCTL_CMD + 'getprop -v Thread:ChildTimeout' )[0] @@ -2331,7 +2323,6 @@ class OpenThread_WpanCtl(IThci): def diagnosticGet(self, strDestinationAddr, listTLV_ids=[]): """@todo : required if as reference device""" - pass def diagnosticQuery(self, strDestinationAddr, listTLV_ids=[]): """@todo : required if as reference device""" @@ -2339,14 +2330,14 @@ class OpenThread_WpanCtl(IThci): def diagnosticReset(self, strDestinationAddr, listTLV_ids=[]): """@todo : required if as reference device""" - pass def startNativeCommissioner(self, strPSKc='GRLpassWord'): # TODO: Support the whole Native Commissioner functionality - # Currently it only aims to trigger a Discovery Request message to pass Certification test 5.8.4 - print ('%s call startNativeCommissioner' % self.port) + # Currently it only aims to trigger a Discovery Request message to pass + # Certification test 5.8.4 + print('%s call startNativeCommissioner' % self.port) cmd = WPANCTL_CMD + 'joiner --start %s' % (strPSKc) - print (cmd) + print(cmd) if self.__sendCommand(cmd)[0] != 'Fail': return True else: @@ -2359,7 +2350,7 @@ class OpenThread_WpanCtl(IThci): True: successful to start Commissioner False: fail to start Commissioner """ - print ('%s call startCollapsedCommissioner' % self.port) + print('%s call startCollapsedCommissioner' % self.port) startCmd = WPANCTL_CMD + 'form %s -c %s -T router' % ( self.networkName, str(self.channel), @@ -2367,7 +2358,7 @@ class OpenThread_WpanCtl(IThci): if self.__sendCommand(startCmd) != 'Fail': time.sleep(2) cmd = WPANCTL_CMD + 'commissioner start' - print (cmd) + print(cmd) if self.__sendCommand(cmd)[0] != 'Fail': self.isActiveCommissioner = True time.sleep(20) # time for petition process @@ -2388,14 +2379,14 @@ class OpenThread_WpanCtl(IThci): True: successful to add Joiner's steering data False: fail to add Joiner's steering data """ - print ('%s call scanJoiner' % self.port) + print('%s call scanJoiner' % self.port) if not isinstance(xEUI, str): eui64 = self.__convertLongToString(xEUI) # prepend 0 at the beginning if len(eui64) < 16: eui64 = eui64.zfill(16) - print (eui64) + print(eui64) else: eui64 = xEUI @@ -2407,7 +2398,7 @@ class OpenThread_WpanCtl(IThci): str(timeout), strPSKd, ) - print (cmd) + print(cmd) if not self.isActiveCommissioner: self.startCollapsedCommissioner() if self.__sendCommand(cmd)[0] != 'Fail': @@ -2425,13 +2416,13 @@ class OpenThread_WpanCtl(IThci): True: successful to set provisioning Url False: fail to set provisioning Url """ - print ('%s call setProvisioningUrl' % self.port) + print('%s call setProvisioningUrl' % self.port) self.provisioningUrl = strURL if self.deviceRole == Thread_Device_Role.Commissioner: cmd = WPANCTL_CMD + 'setprop Commissioner:ProvisioningUrl %s' % ( strURL ) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[0] != 'Fail' return True @@ -2442,10 +2433,10 @@ class OpenThread_WpanCtl(IThci): True: successful to start commissioner candidate petition process False: fail to start commissioner candidate petition process """ - print ('%s call allowCommission' % self.port) + print('%s call allowCommission' % self.port) try: cmd = WPANCTL_CMD + 'commissioner start' - print (cmd) + print(cmd) if self.isActiveCommissioner: return True if self.__sendCommand(cmd)[0] != 'Fail': @@ -2471,12 +2462,12 @@ class OpenThread_WpanCtl(IThci): True: successful to start joiner False: fail to start joiner """ - print ('%s call joinCommissioned' % self.port) + print('%s call joinCommissioned' % self.port) cmd = WPANCTL_CMD + 'joiner --start %s %s' % ( strPSKd, self.provisioningUrl, ) - print (cmd) + print(cmd) if self.__sendCommand(cmd)[0] != 'Fail': if self.__getJoinerState(): self.__sendCommand(WPANCTL_CMD + 'joiner --attach') @@ -2498,14 +2489,14 @@ class OpenThread_WpanCtl(IThci): payload = [] while not rawLogs.empty(): rawLogEach = rawLogs.get() - print (rawLogEach) + print(rawLogEach) if '[THCI]' not in rawLogEach: continue EncryptedPacket = PlatformDiagnosticPacket() infoList = rawLogEach.split('[THCI]')[1].split(']')[0].split('|') for eachInfo in infoList: - print (eachInfo) + print(eachInfo) info = eachInfo.split('=') infoType = info[0].strip() infoValue = info[1].strip() @@ -2578,7 +2569,7 @@ class OpenThread_WpanCtl(IThci): True: successful to send MGMT_ED_SCAN message. False: fail to send MGMT_ED_SCAN message """ - print ('%s call MGMT_ED_SCAN' % self.port) + print('%s call MGMT_ED_SCAN' % self.port) channelMask = '' channelMask = self.__ChannelMaskListToStr(listChannelMask) try: @@ -2589,7 +2580,7 @@ class OpenThread_WpanCtl(IThci): xScanDuration, sAddr, ) - print (cmd) + print(cmd) return self.__sendCommand(cmd) != 'Fail' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -2608,7 +2599,7 @@ class OpenThread_WpanCtl(IThci): True: successful to send MGMT_PANID_QUERY message. False: fail to send MGMT_PANID_QUERY message. """ - print ('%s call MGMT_PANID_QUERY' % self.port) + print('%s call MGMT_PANID_QUERY' % self.port) panid = '' channelMask = '' channelMask = self.__ChannelMaskListToStr(listChannelMask) @@ -2622,7 +2613,7 @@ class OpenThread_WpanCtl(IThci): channelMask, sAddr, ) - print (cmd) + print(cmd) return self.__sendCommand(cmd) != 'Fail' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -2638,7 +2629,7 @@ class OpenThread_WpanCtl(IThci): True: successful to send MGMT_ANNOUNCE_BEGIN message. False: fail to send MGMT_ANNOUNCE_BEGIN message. """ - print ('%s call MGMT_ANNOUNCE_BEGIN' % self.port) + print('%s call MGMT_ANNOUNCE_BEGIN' % self.port) channelMask = '' channelMask = self.__ChannelMaskListToStr(listChannelMask) try: @@ -2648,7 +2639,7 @@ class OpenThread_WpanCtl(IThci): xPeriod, sAddr, ) - print (cmd) + print(cmd) return self.__sendCommand(cmd) != 'Fail' except Exception as e: ModuleHelper.WriteIntoDebugLogger( @@ -2662,7 +2653,7 @@ class OpenThread_WpanCtl(IThci): True: successful to send MGMT_ACTIVE_GET False: fail to send MGMT_ACTIVE_GET """ - print ('%s call MGMT_ACTIVE_GET' % self.port) + print('%s call MGMT_ACTIVE_GET' % self.port) try: cmd = WPANCTL_CMD + 'dataset mgmt-get-active' @@ -2686,7 +2677,7 @@ class OpenThread_WpanCtl(IThci): if self.__sendCommand(setAddressCmd)[0] == 'Fail': return False - print (cmd) + print(cmd) return self.__sendCommand(cmd)[0] != 'Fail' @@ -2721,7 +2712,7 @@ class OpenThread_WpanCtl(IThci): True: successful to send MGMT_ACTIVE_SET False: fail to send MGMT_ACTIVE_SET """ - print ('%s call MGMT_ACTIVE_SET' % self.port) + print('%s call MGMT_ACTIVE_SET' % self.port) try: cmd = WPANCTL_CMD + 'dataset mgmt-set-active' @@ -2837,7 +2828,8 @@ class OpenThread_WpanCtl(IThci): rotationTime = 0 policyBits = 0 - # previous passing way listSecurityPolicy=[True, True, 3600, False, False, True] + # previous passing way listSecurityPolicy=[True, True, 3600, + # False, False, True] if len(listSecurityPolicy) == 6: rotationTime = listSecurityPolicy[2] @@ -2894,8 +2886,8 @@ class OpenThread_WpanCtl(IThci): if BogusTLV is not None: setRawTLVCmd += '8202aa55' - print (setRawTLVCmd) - print (cmd) + print(setRawTLVCmd) + print(cmd) if self.__sendCommand(setRawTLVCmd)[0] == 'Fail': return False @@ -2914,7 +2906,7 @@ class OpenThread_WpanCtl(IThci): True: successful to send MGMT_PENDING_GET False: fail to send MGMT_PENDING_GET """ - print ('%s call MGMT_PENDING_GET' % self.port) + print('%s call MGMT_PENDING_GET' % self.port) try: cmd = WPANCTL_CMD + 'dataset mgmt-get-pending' @@ -2937,7 +2929,7 @@ class OpenThread_WpanCtl(IThci): if self.__sendCommand(setAddressCmd)[0] == 'Fail': return False - print (cmd) + print(cmd) return self.__sendCommand(cmd)[0] != 'Fail' @@ -2965,7 +2957,7 @@ class OpenThread_WpanCtl(IThci): True: successful to send MGMT_PENDING_SET False: fail to send MGMT_PENDING_SET """ - print ('%s call MGMT_PENDING_SET' % self.port) + print('%s call MGMT_PENDING_SET' % self.port) try: cmd = WPANCTL_CMD + 'dataset mgmt-set-pending' if self.__sendCommand(WPANCTL_CMD + 'dataset erase')[0] == 'Fail': @@ -3047,9 +3039,9 @@ class OpenThread_WpanCtl(IThci): return False if xCommissionerSessionId is not None: - print ('not handle xCommissionerSessionId') + print('not handle xCommissionerSessionId') - print (cmd) + print(cmd) return self.__sendCommand(cmd)[0] != 'Fail' @@ -3065,17 +3057,17 @@ class OpenThread_WpanCtl(IThci): True: successful to send MGMT_COMM_GET False: fail to send MGMT_COMM_GET """ - print ('%s call MGMT_COMM_GET' % self.port) + print('%s call MGMT_COMM_GET' % self.port) try: cmd = WPANCTL_CMD + 'commissioner mgmt-get ' - print ('TLVs:') - print (TLVs) + print('TLVs:') + print(TLVs) if len(TLVs) != 0: tlvs = ''.join(hex(tlv).lstrip('0x').zfill(2) for tlv in TLVs) cmd += tlvs - print (cmd) + print(cmd) return self.__sendCommand(cmd)[0] != 'Fail' @@ -3099,17 +3091,17 @@ class OpenThread_WpanCtl(IThci): True: successful to send MGMT_COMM_SET False: fail to send MGMT_COMM_SET """ - print ('%s call MGMT_COMM_SET' % self.port) + print('%s call MGMT_COMM_SET' % self.port) try: cmd = WPANCTL_CMD + 'commissioner mgmt-set ' - print ('-------------------------------') - print (xCommissionerSessionID) - print (xSteeringData) - print (str(xSteeringData) + ' ' + str(hex(xSteeringData)[2:])) - print (xBorderRouterLocator) - print (xChannelTlv) - print (ExceedMaxPayload) - print ('-------------------------------') + print('-------------------------------') + print(xCommissionerSessionID) + print(xSteeringData) + print(str(xSteeringData) + ' ' + str(hex(xSteeringData)[2:])) + print(xBorderRouterLocator) + print(xChannelTlv) + print(ExceedMaxPayload) + print('-------------------------------') if xCommissionerSessionID is not None: # use assigned session id @@ -3136,7 +3128,7 @@ class OpenThread_WpanCtl(IThci): if xChannelTlv is not None: cmd += '000300' + hex(xChannelTlv).lstrip('0x').zfill(4) - print (cmd) + print(cmd) return self.__sendCommand(cmd)[0] != 'Fail' @@ -3146,13 +3138,13 @@ class OpenThread_WpanCtl(IThci): ) def setActiveDataset(self, listActiveDataset=[]): - print ('%s call setActiveDataset' % self.port) + print('%s call setActiveDataset' % self.port) def setCommisionerMode(self): - print ('%s call setCommissionerMode' % self.port) + print('%s call setCommissionerMode' % self.port) def setPSKc(self, strPSKc): - print ('%s call setPSKc' % self.port) + print('%s call setPSKc' % self.port) try: cmd = WPANCTL_CMD + 'setprop Network:PSKc %s' % strPSKc datasetCmd = WPANCTL_CMD + 'setprop Dataset:PSKc %s' % strPSKc @@ -3165,7 +3157,7 @@ class OpenThread_WpanCtl(IThci): ModuleHelper.WriteIntoDebugLogger('setPSKc() Error: ' + str(e)) def setActiveTimestamp(self, xActiveTimestamp): - print ('%s call setActiveTimestamp' % self.port) + print('%s call setActiveTimestamp' % self.port) try: sActiveTimestamp = str(xActiveTimestamp) if len(sActiveTimestamp) < 16: @@ -3194,7 +3186,6 @@ class OpenThread_WpanCtl(IThci): @todo : required if as reference device """ - pass def commissionerUnregister(self): """stop commissioner @@ -3203,9 +3194,9 @@ class OpenThread_WpanCtl(IThci): True: successful to stop commissioner False: fail to stop commissioner """ - print ('%s call commissionerUnregister' % self.port) + print('%s call commissionerUnregister' % self.port) cmd = WPANCTL_CMD + 'commissioner stop' - print (cmd) + print(cmd) if self.__sendCommand(cmd)[0] != 'Fail': self.isActiveCommissioner = False return True @@ -3215,7 +3206,7 @@ class OpenThread_WpanCtl(IThci): def sendBeacons( self, sAddr, xCommissionerSessionId, listChannelMask, xPanId ): - print ('%s call sendBeacons' % self.port) + print('%s call sendBeacons' % self.port) self._sendline(WPANCTL_CMD + 'scan') return True @@ -3223,10 +3214,9 @@ class OpenThread_WpanCtl(IThci): """force update to router as if there is child id request @todo : required if as reference device """ - pass def setRouterThresholdValues(self, upgradeThreshold, downgradeThreshold): - print ('%s call setRouterThresholdValues' % self.port) + print('%s call setRouterThresholdValues' % self.port) self.__setRouterUpgradeThreshold(upgradeThreshold) self.__setRouterDowngradeThreshold(downgradeThreshold) @@ -3234,7 +3224,7 @@ class OpenThread_WpanCtl(IThci): pass def ValidateDeviceFirmware(self): - print ('%s call ValidateDeviceFirmware' % self.port) + print('%s call ValidateDeviceFirmware' % self.port) if 'OPENTHREAD' in self.UIStatusMsg: return True else: