def test_hardware_manager(mock_bable): """Test if the device adapter works correctly with the HardwareManager.""" # Test using a wrong controller id with pytest.raises(ExternalError): hw = HardwareManager(port='ble:0') # Test without giving the controller id hw = HardwareManager(port='ble') hw.close()
def test_initialisation(): with HardwareManager(port='virtual:./engine_vibration_device.py') as hw: hw.connect('1') con = hw.controller() assert con.manage_min_value('get') == 20 assert con.manage_max_value('get') == 100 vibration_test(20, 100, con)
def simple_hw(): if sys.version_info < (3, 5): pytest.skip('requires iotile-emulate on python 3.5+') simple_file = """{{ "device": {{ "iotile_id": "{0}", "trace": [ [0.001, "hello "], [0.001, "goodbye "] ], "simulate_time": true }} }} """ for i in [1, 3, 4, 6]: fname = "dev" + str(i) + ".json" with open(fname, 'w') as tf: tf.write(simple_file.format(str(i))) with HardwareManager( 'virtual:[email protected];[email protected];[email protected];[email protected]' ) as hw: yield hw
def stream_vibrations(min_value, max_value): """ Stream vibration data every second, all between min_value and max_value. """ with HardwareManager(port='virtual:./vibration_device.py') as hw: hw.connect('1') con = hw.controller() con.set_min_and_max(min_value, max_value) hw.enable_streaming() """ hw.iter_reports() will run forever until we kill the program with a control-c. """ try: for report in hw.iter_reports(blocking=True): # Verify that the device is sending realtime data as we expect. assert isinstance(report, IndividualReadingReport) assert len(report.visible_readings) == 1 reading = report.visible_readings[0] assert isinstance(reading, IOTileReading) # We just need the value here, use reading.stream and # reading.reading_time to respectively get the stream # and reading time. Print reading to get them all. print(reading.value) except KeyboardInterrupt: pass
def per_test_device(port, device_id, direct, record, request): """Return a HardwareManager instance connected to an IOTile Device This fixture creates and tears down the connection for each test """ if record is not None: record = _build_record_string(record, request, module=False) with HardwareManager(port=port, record=record) as hw: max_attempts = 3 i = 0 for i in range(0, max_attempts): try: if direct: hw.connect_direct(direct) else: hw.connect(device_id) break except HardwareError: time.sleep(1) if i == max_attempts - 1: pytest.fail( "Could not connect to device after %d attempts, failing" % max_attempts) return hw.enable_streaming() yield hw hw.disconnect()
def device(port, device_id, direct, record, request): """Return a HardwareManager instance connected to an IOTile Device This fixture shares the same device among all tests in the same module """ if record is not None: record = _build_record_string(record, request, module=True) with HardwareManager(port=port, record=record) as hw: # Sometimes in congested wireless environments we can miss the # device advertisement, so attempt the connection several times # before giving up to improve test robustness. max_attempts = 3 i = 0 for i in range(0, max_attempts): try: if direct: hw.connect_direct(direct) else: hw.connect(device_id) break except HardwareError: time.sleep(1) if i == max_attempts - 1: pytest.fail( "Could not connect to device after %d attempts, failing" % max_attempts) return hw.enable_streaming() yield hw hw.disconnect()
def simple_hw(): simple_file = """{{ "device": {{ "iotile_id": "{0}", "trace": [ [0.001, "hello "], [0.001, "goodbye "] ] }} }} """ for i in [1, 3, 4, 6]: fname = "dev" + str(i) + ".json" with open(fname, 'w') as tf: tf.write(simple_file.format(str(i))) hw = HardwareManager( 'virtual:[email protected];[email protected];[email protected];[email protected]' ) yield hw hw.disconnect()
def con(): hw = HardwareManager(port='virtual:./radiation_device.py') hw.connect_direct(1) con = hw.controller() yield con hw.disconnect()
def setUp(self): self.vdev = subprocess.Popen( ['virtual_device', 'bled112', 'report_test']) bleds = BLED112Adapter.find_bled112_devices() print(bleds) self.hw = HardwareManager(port='bled112:{}'.format(bleds[1]))
def hw(): hw = HardwareManager(port='virtual:{}'.format(path)) hw.connect_direct(1) yield hw hw.disconnect() hw.close()
def test_set_correct_max_value(): with HardwareManager(port='virtual:./engine_vibration_device.py') as hw: hw.connect('1') con = hw.controller() assert con.manage_max_value('set=21') == 21 vibration_test(20, 21, con) assert con.manage_max_value('set=1234567890') == 1234567890 vibration_test(20, 1234567890, con)
def test_set_correct_min_value(): with HardwareManager(port='virtual:./engine_vibration_device.py') as hw: hw.connect('1') con = hw.controller() assert con.manage_min_value('set=99') == 99 vibration_test(99, 100, con) assert con.manage_min_value('set=0') == 0 vibration_test(0, 100, con)
def hw(virtual_interface): port, _ = virtual_interface hw = HardwareManager(port="ws2:127.0.0.1:{}".format(port)) yield hw hw.close()
def test_find_virtual_script_withjson(): """Make sure we can find a script with a json """ path = os.path.join(os.path.dirname(__file__), 'virtual_device.py') jsonpath = os.path.join(os.path.dirname(__file__), 'report_test_config_signed.json') hw = HardwareManager(port="virtual:%s@%s" % (path, jsonpath))
def hw(server): path, _ = server logger.info("Creating HardwareManager at with socket path %s", path) hw = HardwareManager(port="unix:{}".format(path)) yield hw hw.close()
def hw(server): port, _ = server logger.info("Creating HardwareManager at port %d", port) hw = HardwareManager(port="ws:127.0.0.1:{}".format(port)) yield hw hw.close()
def tile_based(): conf_file = os.path.join(os.path.dirname(__file__), 'tile_config.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') hw = HardwareManager('virtual:tile_based@%s' % conf_file) yield hw hw.disconnect()
def test_find_virtual_script_unknownjson(): """Make sure we can find a script with a json """ path = os.path.join(os.path.dirname(__file__), 'virtual_device.py') jsonpath = os.path.join(os.path.dirname(__file__), 'unknown_json_config.json') with pytest.raises(ArgumentError): hw = HardwareManager(port="virtual:%s@%s" % (path, jsonpath))
def conf2_report_hw(): conf_file = os.path.join(os.path.dirname(__file__), 'report_test_config_signed.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') hw = HardwareManager('virtual:report_test@%s' % conf_file) yield hw hw.disconnect()
def test_set_incorrect_min_value(): with HardwareManager(port='virtual:./engine_vibration_device.py') as hw: hw.connect('1') con = hw.controller() assert con.manage_min_value('set=100') == 20 # initial value assert con.manage_min_value('set=zhrbjvk') == None with pytest.raises(APIError): con.manage_min_value('set=-1') with pytest.raises(APIError): # since min_value is converted in long before being compared to max_value this kind of error can appear con.manage_min_value('set=10000000000000000000000000000000000000')
def tracer_hw(): conf_file = os.path.join(os.path.dirname(__file__), 'fast_realtime_trace.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') hw = HardwareManager('virtual:realtime_test@%s' % conf_file) yield hw hw.disconnect()
def linked_tile(rpc_agent, tmpdir): """Create a connected HardwareManager instance with a proxy pointed at an RPCDispatcher.""" visor, _client1, _client2 = rpc_agent # Create a config file that we can use to initialize a virtual device that will point at our # BasicRPCDispatch via a running IOTileSupervisor. Currently, HardwareManager can only # load configurations for virtual devices from actual files, so we need to save this to a # temp file. config = { "device": { "iotile_id": 1, "tiles": [{ "name": "service_delegate", "address": 11, "args": { "url": "ws://127.0.0.1:%d/services" % visor. port, # This has to match the port of the supervisor instance that we want to connect to "service": "service_1", # This has to match the service name that the RPCDispatcher is registered as an agent for "name": "bsctst" # This is the 6 character string that must match the ModuleName() of the proxy and is used to find the right proxy } }] } } # This is a special py.path.local object from pytest # https://docs.pytest.org/en/latest/tmpdir.html config_path_obj = tmpdir.join('config.json') config_path_obj.write(json.dumps(config)) config_path = str(config_path_obj) reg = ComponentRegistry() reg.register_extension('iotile.proxy', 'test_proxy', BasicRPCDispatcherProxy) # This will create a HardwareManager pointed at a virtual tile based device # where the tiles that are added to the virtual device are found using the config # file specified after the @ symbol. hw = HardwareManager(port="virtual:tile_based@%s" % config_path) # pylint:disable=invalid-name; We use hw throughout CoreTools to denote a HardwareManager instance # We specified that the virtual device should be at uuid 1 (using iotile_id above) # so we know how to connect to it. We also know that we specified a single tile # at address 11 inside that virtual device so we will be able to get its proxy # object by calling hw.get(11) once we are connected. hw.connect(1) yield hw hw.disconnect() reg.clear_extensions('iotile.proxy')
def test_recording_rpcs(tmpdir): """Make sure we can record RPCs.""" record_path = tmpdir.join('recording.csv') conf_file = os.path.join(os.path.dirname(__file__), 'tile_config.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') reg = ComponentRegistry() reg.register_extension('iotile.proxy', 'virtual_tile', 'test/test_hw/virtual_tile.py') try: with HardwareManager('virtual:tile_based@%s' % conf_file, record=str(record_path)) as hw: hw.connect(1) con = hw.get(9) tile1 = hw.get(11) con.count() tile1.add(3, 5) tile1.count() finally: reg.clear_extensions() assert record_path.exists() rpcs = record_path.readlines(cr=False) assert len(rpcs) == 12 assert rpcs[:3] == ['# IOTile RPC Recording', '# Format: 1.0', ''] # Patch out the timestamps and run times for better comparison rpc_lines = [x.split(',') for x in rpcs[4:-1]] for rpc in rpc_lines: assert len(rpc) == 9 rpc[1] = "" rpc[5] = "" rpc_lines = [",".join(x) for x in rpc_lines] print(rpc_lines[4]) assert rpc_lines == [ '1,, 9,0x0004,0xc0,, ,ffff74657374303101000003 ,', '1,, 9,0x0004,0xc0,, ,ffff74657374303101000003 ,', '1,,11,0x0004,0xc0,, ,ffff74657374303101000003 ,', '1,,11,0x0004,0xc0,, ,ffff74657374303101000003 ,', '1,, 9,0x8001,0xc0,, ,00000000 ,', '1,,11,0x8000,0xc0,,0300000005000000 ,08000000 ,', '1,,11,0x8001,0xc0,, ,00000000 ,' ]
def conf_ascii_tracing(): conf_file = os.path.join(os.path.dirname(__file__), 'tracing_ascii_config.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') hw = HardwareManager('virtual:tracing_test@%s' % conf_file) hw.connect_direct('1') yield hw hw.disconnect()
def test_invalid_length_combo(): """Make sure invalid length combinations throw an exception """ conf_file = os.path.join(os.path.dirname(__file__), 'report_length_invalid.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') with pytest.raises(ArgumentError): hw = HardwareManager('virtual:report_test@%s' % conf_file)
def hw_man(gateway, local_broker): """Create a HardwareManager that can talk to our gateway over the local broker.""" reg = ComponentRegistry() reg.set_config('awsiot-endpoint', '') reg.set_config('awsiot-rootcert', '') reg.set_config('awsiot-iamkey', '') reg.set_config('awsiot-iamtoken', '') hw_dev = HardwareManager(port="awsiot:devices/d--0000-0000-0000-0002") yield hw_dev hw_dev.close()
def test_set_incorrect_max_value(): with HardwareManager(port='virtual:./engine_vibration_device.py') as hw: hw.connect('1') con = hw.controller() assert con.manage_max_value('set=20') == 100 # initial value assert con.manage_max_value('set=0') == 100 assert con.manage_max_value('set=zhrbjvk') == None with pytest.raises(APIError): con.manage_max_value('set=-1') with pytest.raises(APIError): con.manage_max_value('set=1000000000000000000000000') with pytest.raises(APIError): # message="APIError: (\"'L' format requires 0 <= number <= 4294967295\",)" con.manage_max_value('set=12345678900')
def test_crossed_changes(): with HardwareManager(port='virtual:./engine_vibration_device.py') as hw: hw.connect('1') con = hw.controller() assert con.manage_min_value('set=55') == 55 vibration_test(55, 100, con) assert con.manage_max_value('set=20') == 100 # initial value vibration_test(55, 100, con) assert con.manage_min_value('set=550') == 55 vibration_test(55, 100, con) assert con.manage_max_value('set=20000') == 20000 # initial value vibration_test(55, 20000, con) assert con.manage_max_value('set=zhrbjvk') == None vibration_test(55, 20000, con)
def tile_based(): conf_file = os.path.join(os.path.dirname(__file__), 'tile_config.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') reg = ComponentRegistry() reg.register_extension('iotile.proxy', 'vitual_tile', 'test/test_hw/virtual_tile.py') hw = HardwareManager('virtual:tile_based@%s' % conf_file) yield hw reg.clear_extensions() hw.disconnect()
def proxy_variants_4(): conf_file = os.path.join(os.path.dirname(__file__), 'proxy_match_tile_config.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') reg = ComponentRegistry() # None, None reg.register_extension('iotile.proxy', 'proxy_match_tile', ProxyMatchTest1) reg.register_extension('iotile.proxy', 'proxy_match_tile', ProxyMatchTest2) hw = HardwareManager('virtual:tile_based@%s' % conf_file) yield hw reg.clear_extensions() hw.close()