Best Python code snippet using ATX
usbDevice.https.any.js
Source:usbDevice.https.any.js  
1// META: timeout=long2// META: script=/webusb/resources/fake-devices.js3// META: script=/webusb/resources/usb-helpers.js4'use strict';5function assertRejectsWithNotFoundError(promise) {6  return assertRejectsWithError(promise, 'NotFoundError');7}8function assertRejectsWithTypeError(promise) {9  return assertRejectsWithError(promise, 'TypeError');10}11function assertRejectsWithNotOpenError(promise) {12  return assertRejectsWithError(13      promise, 'InvalidStateError', 'The device must be opened first.');14}15function assertRejectsWithNotConfiguredError(promise) {16  return assertRejectsWithError(17      promise, 'InvalidStateError',18      'The device must have a configuration selected.');19}20function assertRejectsWithDeviceStateChangeInProgressError(promise) {21  return assertRejectsWithError(22    promise, 'InvalidStateError',23    'An operation that changes the device state is in progress.');24}25function assertRejectsWithInterfaceStateChangeInProgressError(promise) {26  return assertRejectsWithError(27    promise, 'InvalidStateError',28    'An operation that changes interface state is in progress.');29}30usb_test(() => {31  return getFakeDevice().then(({ device, fakeDevice }) => {32    return waitForDisconnect(fakeDevice)33      .then(() => assertRejectsWithNotFoundError(device.open()));34  });35}, 'open rejects when called on a disconnected device');36usb_test(() => {37  return getFakeDevice().then(({ device, fakeDevice }) => {38    return device.open()39      .then(() => waitForDisconnect(fakeDevice))40      .then(() => {41        assert_false(device.opened);42      });43  });44}, 'disconnection closes the device');45usb_test(() => {46  return getFakeDevice().then(({ device }) => {47    assert_false(device.opened);48    return device.open().then(() => {49      assert_true(device.opened);50      return device.close().then(() => {51        assert_false(device.opened);52      });53    });54  });55}, 'a device can be opened and closed');56usb_test(() => {57  return getFakeDevice().then(({ device }) => {58    return device.open()59      .then(() => device.open())60      .then(() => device.open())61      .then(() => device.open())62      .then(() => device.close())63      .then(() => device.close())64      .then(() => device.close())65      .then(() => device.close());66  });67}, 'open and close can be called multiple times');68usb_test(async () => {69  let { device } = await getFakeDevice();70  await Promise.all([71    device.open(),72    assertRejectsWithDeviceStateChangeInProgressError(device.open()),73    assertRejectsWithDeviceStateChangeInProgressError(device.close()),74  ]);75  await Promise.all([76    device.close(),77    assertRejectsWithDeviceStateChangeInProgressError(device.open()),78    assertRejectsWithDeviceStateChangeInProgressError(device.close()),79  ]);80}, 'open and close cannot be called again while open or close are in progress');81usb_test(async () => {82  let { device } = await getFakeDevice();83  await device.open();84  return Promise.all([85    device.selectConfiguration(1),86    assertRejectsWithDeviceStateChangeInProgressError(87        device.claimInterface(0)),88    assertRejectsWithDeviceStateChangeInProgressError(89        device.releaseInterface(0)),90    assertRejectsWithDeviceStateChangeInProgressError(device.open()),91    assertRejectsWithDeviceStateChangeInProgressError(92        device.selectConfiguration(1)),93    assertRejectsWithDeviceStateChangeInProgressError(device.reset()),94    assertRejectsWithDeviceStateChangeInProgressError(95        device.selectAlternateInterface(0, 0)),96    assertRejectsWithDeviceStateChangeInProgressError(97        device.controlTransferOut({98          requestType: 'standard',99          recipient: 'interface',100          request: 0x42,101          value: 0x1234,102          index: 0x0000,103        })),104    assertRejectsWithDeviceStateChangeInProgressError(105        device.controlTransferOut({106          requestType: 'standard',107          recipient: 'interface',108          request: 0x42,109          value: 0x1234,110          index: 0x0000,111        }, new Uint8Array([1, 2, 3]))),112    assertRejectsWithDeviceStateChangeInProgressError(113        device.controlTransferIn({114          requestType: 'standard',115          recipient: 'interface',116          request: 0x42,117          value: 0x1234,118          index: 0x0000119        }, 0)),120    assertRejectsWithDeviceStateChangeInProgressError(device.close()),121  ]);122}, 'device operations reject if an device state change is in progress');123usb_test(() => {124  return getFakeDevice().then(({ device, fakeDevice }) => {125    return device.open()126      .then(() => waitForDisconnect(fakeDevice))127      .then(() => assertRejectsWithNotFoundError(device.close()));128  });129}, 'close rejects when called on a disconnected device');130usb_test(() => {131  return getFakeDevice().then(({ device, fakeDevice }) => {132    return device.open()133      .then(() => waitForDisconnect(fakeDevice))134      .then(() => assertRejectsWithNotFoundError(device.selectConfiguration(1)));135  });136}, 'selectConfiguration rejects when called on a disconnected device');137usb_test(() => {138  return getFakeDevice().then(({ device }) => Promise.all([139      assertRejectsWithNotOpenError(device.selectConfiguration(1)),140      assertRejectsWithNotOpenError(device.claimInterface(0)),141      assertRejectsWithNotOpenError(device.releaseInterface(0)),142      assertRejectsWithNotOpenError(device.selectAlternateInterface(0, 1)),143      assertRejectsWithNotOpenError(device.controlTransferIn({144          requestType: 'vendor',145          recipient: 'device',146          request: 0x42,147          value: 0x1234,148          index: 0x5678149      }, 7)),150      assertRejectsWithNotOpenError(device.controlTransferOut({151          requestType: 'vendor',152          recipient: 'device',153          request: 0x42,154          value: 0x1234,155          index: 0x5678156      }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))),157      assertRejectsWithNotOpenError(device.clearHalt('in', 1)),158      assertRejectsWithNotOpenError(device.transferIn(1, 8)),159      assertRejectsWithNotOpenError(160          device.transferOut(1, new ArrayBuffer(8))),161      assertRejectsWithNotOpenError(device.isochronousTransferIn(1, [8])),162      assertRejectsWithNotOpenError(163          device.isochronousTransferOut(1, new ArrayBuffer(8), [8])),164      assertRejectsWithNotOpenError(device.reset())165  ]));166}, 'methods requiring it reject when the device is not open');167usb_test(() => {168  return getFakeDevice().then(({ device }) => {169    assert_equals(device.configuration, null);170    return device.open()171      .then(() => {172        assert_equals(device.configuration, null);173        return device.selectConfiguration(1);174      })175      .then(() => {176        assertDeviceInfoEquals(177            device.configuration, fakeDeviceInit.configurations[0]);178      })179      .then(() => device.close());180  });181}, 'device configuration can be set and queried');182usb_test(async () => {183  let { device } = await getFakeDevice();184  assert_equals(device.configuration, null);185  await device.open();186  assert_equals(device.configuration, null);187  await device.selectConfiguration(1);188  await device.selectConfiguration(1);189  assertDeviceInfoEquals(190      device.configuration, fakeDeviceInit.configurations[0]);191  await device.selectConfiguration(2);192  assertDeviceInfoEquals(193      device.configuration, fakeDeviceInit.configurations[1]);194  await device.close();195}, 'a device configuration value can be set again');196usb_test(() => {197  return getFakeDevice().then(({ device }) => {198    assert_equals(device.configuration, null);199    return device.open()200      .then(() => assertRejectsWithError(201            device.selectConfiguration(3), 'NotFoundError',202            'The configuration value provided is not supported by the device.'))203      .then(() => device.close());204  });205}, 'selectConfiguration rejects on invalid configurations');206usb_test(() => {207  return getFakeDevice().then(({ device }) => {208    assert_equals(device.configuration, null);209    return device.open().then(() => Promise.all([210        assertRejectsWithNotConfiguredError(device.claimInterface(0)),211        assertRejectsWithNotConfiguredError(device.releaseInterface(0)),212        assertRejectsWithNotConfiguredError(device.selectAlternateInterface(0, 1)),213        assertRejectsWithNotConfiguredError(device.controlTransferIn({214            requestType: 'vendor',215            recipient: 'device',216            request: 0x42,217            value: 0x1234,218            index: 0x5678219        }, 7)),220        assertRejectsWithNotConfiguredError(device.controlTransferOut({221            requestType: 'vendor',222            recipient: 'device',223            request: 0x42,224            value: 0x1234,225            index: 0x5678226        }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))),227        assertRejectsWithNotConfiguredError(device.clearHalt('in', 1)),228        assertRejectsWithNotConfiguredError(device.transferIn(1, 8)),229        assertRejectsWithNotConfiguredError(230            device.transferOut(1, new ArrayBuffer(8))),231        assertRejectsWithNotConfiguredError(232            device.isochronousTransferIn(1, [8])),233        assertRejectsWithNotConfiguredError(234            device.isochronousTransferOut(1, new ArrayBuffer(8), [8])),235    ])).then(() => device.close());236  });237}, 'methods requiring it reject when the device is unconfigured');238usb_test(() => {239  return getFakeDevice().then(({ device }) => {240    return device.open()241      .then(() => device.selectConfiguration(1))242      .then(() => device.claimInterface(0))243      .then(() => {244        assert_true(device.configuration.interfaces[0].claimed);245        return device.releaseInterface(0);246      })247      .then(() => {248        assert_false(device.configuration.interfaces[0].claimed);249        return device.close();250      });251  });252}, 'an interface can be claimed and released');253usb_test(async () => {254  let { device } = await getFakeDevice()255  await device.open();256  await device.selectConfiguration(1);257  await device.claimInterface(0);258  assert_true(device.configuration.interfaces[0].claimed);259  await device.claimInterface(0);260  assert_true(device.configuration.interfaces[0].claimed);261  await device.close();262}, 'an interface can be claimed multiple times');263usb_test(async () => {264  let { device } = await getFakeDevice();265  await device.open();266  await device.selectConfiguration(1);267  await device.claimInterface(0);268  assert_true(device.configuration.interfaces[0].claimed);269  await device.releaseInterface(0);270  assert_false(device.configuration.interfaces[0].claimed);271  await device.releaseInterface(0);272  assert_false(device.configuration.interfaces[0].claimed);273  await device.close();274}, 'an interface can be released multiple times');275usb_test(async () => {276  let { device } = await getFakeDevice();277  await device.open();278  await device.selectConfiguration(1);279  return Promise.all([280    device.claimInterface(0),281    assertRejectsWithInterfaceStateChangeInProgressError(282        device.claimInterface(0)),283    assertRejectsWithInterfaceStateChangeInProgressError(284        device.releaseInterface(0)),285    assertRejectsWithInterfaceStateChangeInProgressError(device.open()),286    assertRejectsWithInterfaceStateChangeInProgressError(287        device.selectConfiguration(1)),288    assertRejectsWithInterfaceStateChangeInProgressError(device.reset()),289    assertRejectsWithInterfaceStateChangeInProgressError(290        device.selectAlternateInterface(0, 0)),291    assertRejectsWithInterfaceStateChangeInProgressError(292        device.controlTransferOut({293          requestType: 'standard',294          recipient: 'interface',295          request: 0x42,296          value: 0x1234,297          index: 0x0000,298        })),299    assertRejectsWithInterfaceStateChangeInProgressError(300        device.controlTransferOut({301          requestType: 'standard',302          recipient: 'interface',303          request: 0x42,304          value: 0x1234,305          index: 0x0000,306        }, new Uint8Array([1, 2, 3]))),307    assertRejectsWithInterfaceStateChangeInProgressError(308        device.controlTransferIn({309          requestType: 'standard',310          recipient: 'interface',311          request: 0x42,312          value: 0x1234,313          index: 0x0000314        }, 0)),315    assertRejectsWithInterfaceStateChangeInProgressError(device.close()),316  ]);317}, 'device operations reject if an interface state change is in progress');318usb_test(async () => {319  let { device } = await getFakeDevice();320  await device.open();321  await device.selectConfiguration(1);322  await device.claimInterface(0);323  assert_true(device.configuration.interfaces[0].claimed);324  await device.close(0);325  assert_false(device.configuration.interfaces[0].claimed);326}, 'interfaces are released on close');327usb_test(() => {328  return getFakeDevice().then(({ device }) => {329    const message = 'The interface number provided is not supported by the ' +330                    'device in its current configuration.';331    return device.open()332      .then(() => device.selectConfiguration(1))333      .then(() => Promise.all([334          assertRejectsWithError(335              device.claimInterface(2), 'NotFoundError', message),336          assertRejectsWithError(337              device.releaseInterface(2), 'NotFoundError', message),338      ]))339      .then(() => device.close());340  });341}, 'a non-existent interface cannot be claimed or released');342usb_test(() => {343  return getFakeDevice().then(({ device, fakeDevice }) => {344    return device.open()345      .then(() => device.selectConfiguration(1))346      .then(() => waitForDisconnect(fakeDevice))347      .then(() => assertRejectsWithNotFoundError(device.claimInterface(0)));348  });349}, 'claimInterface rejects when called on a disconnected device');350usb_test(() => {351  return getFakeDevice().then(({ device, fakeDevice }) => {352    return device.open()353      .then(() => device.selectConfiguration(1))354      .then(() => device.claimInterface(0))355      .then(() => waitForDisconnect(fakeDevice))356      .then(() => assertRejectsWithNotFoundError(device.releaseInterface(0)));357  });358}, 'releaseInterface rejects when called on a disconnected device');359usb_test(() => {360  return getFakeDevice().then(({ device }) => {361    return device.open()362      .then(() => device.selectConfiguration(2))363      .then(() => device.claimInterface(0))364      .then(() => device.selectAlternateInterface(0, 1))365      .then(() => device.close());366  });367}, 'can select an alternate interface');368usb_test(() => {369  return getFakeDevice().then(({ device }) => {370    return device.open()371      .then(() => device.selectConfiguration(2))372      .then(() => device.claimInterface(0))373      .then(() => assertRejectsWithError(374          device.selectAlternateInterface(0, 2), 'NotFoundError',375          'The alternate setting provided is not supported by the device in ' +376          'its current configuration.'))377      .then(() => device.close());378  });379}, 'cannot select a non-existent alternate interface');380usb_test(() => {381  return getFakeDevice().then(({ device, fakeDevice }) => {382    return device.open()383      .then(() => device.selectConfiguration(2))384      .then(() => device.claimInterface(0))385      .then(() => waitForDisconnect(fakeDevice))386      .then(() => assertRejectsWithNotFoundError(device.selectAlternateInterface(0, 1)));387  });388}, 'selectAlternateInterface rejects when called on a disconnected device');389usb_test(async () => {390  let { device } = await getFakeDevice();391  let usbRequestTypes = ['standard', 'class', 'vendor'];392  let usbRecipients = ['device', 'interface', 'endpoint', 'other'];393  await device.open();394  await device.selectConfiguration(1);395  await device.claimInterface(0);396  await device.selectAlternateInterface(0, 0);397  for (const requestType of usbRequestTypes) {398    for (const recipient of usbRecipients) {399      let index = recipient === 'interface' ? 0x5600 : 0x5681;400      let result = await device.controlTransferIn({401        requestType: requestType,402        recipient: recipient,403        request: 0x42,404        value: 0x1234,405        index: index406      }, 7);407      assert_true(result instanceof USBInTransferResult);408      assert_equals(result.status, 'ok');409      assert_equals(result.data.byteLength, 7);410      assert_equals(result.data.getUint16(0), 0x07);411      assert_equals(result.data.getUint8(2), 0x42);412      assert_equals(result.data.getUint16(3), 0x1234);413      assert_equals(result.data.getUint16(5), index);414    }415  }416  await device.close();417}, 'can issue all types of IN control transfers');418usb_test(() => {419  return getFakeDevice().then(({ device, fakeDevice }) => {420    return device.open()421      .then(() => device.selectConfiguration(1))422      .then(() => waitForDisconnect(fakeDevice))423      .then(() => assertRejectsWithNotFoundError(device.controlTransferIn({424          requestType: 'vendor',425          recipient: 'device',426          request: 0x42,427          value: 0x1234,428          index: 0x5678429        }, 7)));430  });431}, 'controlTransferIn rejects when called on a disconnected device');432usb_test(async () => {433  let { device } = await getFakeDevice();434  let usbRequestTypes = ['standard', 'class', 'vendor'];435  let usbRecipients = ['device', 'interface', 'endpoint', 'other'];436  let dataArray = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);437  let dataTypes = [dataArray, dataArray.buffer];438  await device.open();439  await device.selectConfiguration(1);440  await device.claimInterface(0);441  await device.selectAlternateInterface(0, 0);442  for (const requestType of usbRequestTypes) {443    for (const recipient of usbRecipients) {444      let index = recipient === 'interface' ? 0x5600 : 0x5681;445      let transferParams = {446        requestType: requestType,447        recipient: recipient,448        request: 0x42,449        value: 0x1234,450        index: index451      };452      for (const data of dataTypes) {453        let result = await device.controlTransferOut(transferParams, data);454        assert_true(result instanceof USBOutTransferResult);455        assert_equals(result.status, 'ok');456        assert_equals(result.bytesWritten, 8);457      }458      let result = await device.controlTransferOut(transferParams);459      assert_true(result instanceof USBOutTransferResult);460      assert_equals(result.status, 'ok');461    }462  }463  await device.close();464}, 'can issue all types of OUT control transfers');465usb_test(() => {466  return getFakeDevice().then(({ device, fakeDevice }) => {467    return device.open()468      .then(() => device.selectConfiguration(1))469      .then(() => waitForDisconnect(fakeDevice))470      .then(() => assertRejectsWithNotFoundError(device.controlTransferOut({471          requestType: 'vendor',472          recipient: 'device',473          request: 0x42,474          value: 0x1234,475          index: 0x5678476        }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))));477  });478}, 'controlTransferOut rejects when called on a disconnected device');479usb_test(async () => {480  let { device } = await getFakeDevice();481  await device.open();482  await device.selectConfiguration(1);483  await device.claimInterface(0);484  assertRejectsWithTypeError(device.controlTransferOut({485    requestType: 'invalid',486    recipient: 'device',487    request: 0x42,488    value: 0x1234,489    index: 0x5678490  }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])));491  assertRejectsWithTypeError(device.controlTransferIn({492    requestType: 'invalid',493    recipient: 'device',494    request: 0x42,495    value: 0x1234,496    index: 0x5678497  }, 0));498  await device.close();499}, 'control transfers with a invalid request type reject');500usb_test(async () => {501  let { device } = await getFakeDevice();502  await device.open();503  await device.selectConfiguration(1);504  await device.claimInterface(0);505  assertRejectsWithTypeError(device.controlTransferOut({506    requestType: 'vendor',507    recipient: 'invalid',508    request: 0x42,509    value: 0x1234,510    index: 0x5678511  }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])));512  assertRejectsWithTypeError(device.controlTransferIn({513    requestType: 'vendor',514    recipient: 'invalid',515    request: 0x42,516    value: 0x1234,517    index: 0x5678518  }, 0));519}, 'control transfers with a invalid recipient type reject');520usb_test(async () => {521  let { device } = await getFakeDevice();522  await device.open();523  await device.selectConfiguration(1);524  await device.claimInterface(0);525  assertRejectsWithNotFoundError(device.controlTransferOut({526    requestType: 'vendor',527    recipient: 'interface',528    request: 0x42,529    value: 0x1234,530    index: 0x0002  // Last byte of index is interface number.531  }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])));532  assertRejectsWithNotFoundError(device.controlTransferIn({533    requestType: 'vendor',534    recipient: 'interface',535    request: 0x42,536    value: 0x1234,537    index: 0x0002  // Last byte of index is interface number.538  }, 0));539}, 'control transfers to a non-existant interface reject');540usb_test(() => {541  return getFakeDevice().then(({ device }) => {542    let interfaceRequest = {543        requestType: 'vendor',544        recipient: 'interface',545        request: 0x42,546        value: 0x1234,547        index: 0x5600  // Last byte of index is interface number.548    };549    let endpointRequest = {550        requestType: 'vendor',551        recipient: 'endpoint',552        request: 0x42,553        value: 0x1234,554        index: 0x5681  // Last byte of index is endpoint address.555    };556    let data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);557    return device.open()558      .then(() => device.selectConfiguration(1))559      .then(() => Promise.all([560          assertRejectsWithError(561              device.controlTransferIn(interfaceRequest, 7),562              'InvalidStateError'),563          assertRejectsWithError(564              device.controlTransferIn(endpointRequest, 7),565              'NotFoundError'),566          assertRejectsWithError(567              device.controlTransferOut(interfaceRequest, data),568              'InvalidStateError'),569          assertRejectsWithError(570              device.controlTransferOut(endpointRequest, data),571              'NotFoundError'),572      ]))573      .then(() => device.claimInterface(0))574      .then(() => Promise.all([575          device.controlTransferIn(interfaceRequest, 7).then(result => {576            assert_true(result instanceof USBInTransferResult);577            assert_equals(result.status, 'ok');578            assert_equals(result.data.byteLength, 7);579            assert_equals(result.data.getUint16(0), 0x07);580            assert_equals(result.data.getUint8(2), 0x42);581            assert_equals(result.data.getUint16(3), 0x1234);582            assert_equals(result.data.getUint16(5), 0x5600);583          }),584          device.controlTransferIn(endpointRequest, 7).then(result => {585            assert_true(result instanceof USBInTransferResult);586            assert_equals(result.status, 'ok');587            assert_equals(result.data.byteLength, 7);588            assert_equals(result.data.getUint16(0), 0x07);589            assert_equals(result.data.getUint8(2), 0x42);590            assert_equals(result.data.getUint16(3), 0x1234);591            assert_equals(result.data.getUint16(5), 0x5681);592          }),593          device.controlTransferOut(interfaceRequest, data),594          device.controlTransferOut(endpointRequest, data),595      ]))596      .then(() => device.close());597  });598}, 'requests to interfaces and endpoint require an interface claim');599usb_test(() => {600  return getFakeDevice().then(({ device }) => {601    return device.open()602      .then(() => device.selectConfiguration(1))603      .then(() => device.claimInterface(0))604      .then(() => device.clearHalt('in', 1))605      .then(() => device.close());606  });607}, 'can clear a halt condition');608usb_test(() => {609  return getFakeDevice().then(({ device, fakeDevice }) => {610    return device.open()611      .then(() => device.selectConfiguration(1))612      .then(() => device.claimInterface(0))613      .then(() => waitForDisconnect(fakeDevice))614      .then(() => assertRejectsWithNotFoundError(device.clearHalt('in', 1)));615  });616}, 'clearHalt rejects when called on a disconnected device');617usb_test(() => {618  return getFakeDevice().then(({ device }) => {619    let data = new DataView(new ArrayBuffer(1024));620    for (let i = 0; i < 1024; ++i)621      data.setUint8(i, i & 0xff);622    const notFoundMessage = 'The specified endpoint is not part of a claimed ' +623                            'and selected alternate interface.';624    const rangeError = 'The specified endpoint number is out of range.';625    return device.open()626      .then(() => device.selectConfiguration(1))627      .then(() => device.claimInterface(0))628      .then(() => Promise.all([629          assertRejectsWithError(device.transferIn(2, 8),630                                 'NotFoundError', notFoundMessage), // Unclaimed631          assertRejectsWithError(device.transferIn(3, 8), 'NotFoundError',632                                 notFoundMessage), // Non-existent633          assertRejectsWithError(634              device.transferIn(16, 8), 'IndexSizeError', rangeError),635          assertRejectsWithError(device.transferOut(2, data),636                                 'NotFoundError', notFoundMessage), // Unclaimed637          assertRejectsWithError(device.transferOut(3, data), 'NotFoundError',638                                 notFoundMessage), // Non-existent639          assertRejectsWithError(640              device.transferOut(16, data), 'IndexSizeError', rangeError),641      ]));642  });643}, 'transfers to unavailable endpoints are rejected');644usb_test(() => {645  return getFakeDevice().then(({ device }) => {646    return device.open()647      .then(() => device.selectConfiguration(1))648      .then(() => device.claimInterface(0))649      .then(() => device.transferIn(1, 8))650      .then(result => {651        assert_true(result instanceof USBInTransferResult);652        assert_equals(result.status, 'ok');653        assert_equals(result.data.byteLength, 8);654        for (let i = 0; i < 8; ++i)655          assert_equals(result.data.getUint8(i), i, 'mismatch at byte ' + i);656        return device.close();657      });658  });659}, 'can issue IN interrupt transfer');660usb_test(() => {661  return getFakeDevice().then(({ device }) => {662    return device.open()663      .then(() => device.selectConfiguration(1))664      .then(() => device.claimInterface(1))665      .then(() => device.transferIn(2, 1024))666      .then(result => {667        assert_true(result instanceof USBInTransferResult);668        assert_equals(result.status, 'ok');669        assert_equals(result.data.byteLength, 1024);670        for (let i = 0; i < 1024; ++i)671          assert_equals(result.data.getUint8(i), i & 0xff,672                        'mismatch at byte ' + i);673        return device.close();674      });675  });676}, 'can issue IN bulk transfer');677usb_test(() => {678  return getFakeDevice().then(({ device, fakeDevice }) => {679    return device.open()680      .then(() => device.selectConfiguration(1))681      .then(() => device.claimInterface(1))682      .then(() => waitForDisconnect(fakeDevice))683      .then(() => assertRejectsWithNotFoundError(device.transferIn(2, 1024)));684  });685}, 'transferIn rejects if called on a disconnected device');686usb_test(() => {687  return getFakeDevice().then(({ device }) => {688    return device.open()689      .then(() => device.selectConfiguration(1))690      .then(() => device.claimInterface(1))691      .then(() => {692        let data = new DataView(new ArrayBuffer(1024));693        for (let i = 0; i < 1024; ++i)694          data.setUint8(i, i & 0xff);695        return device.transferOut(2, data);696      })697      .then(result => {698        assert_true(result instanceof USBOutTransferResult);699        assert_equals(result.status, 'ok');700        assert_equals(result.bytesWritten, 1024);701        return device.close();702      });703  });704}, 'can issue OUT bulk transfer');705usb_test(() => {706  return getFakeDevice().then(({ device, fakeDevice }) => {707    return device.open()708      .then(() => device.selectConfiguration(1))709      .then(() => device.claimInterface(1))710      .then(() => {711        let data = new DataView(new ArrayBuffer(1024));712        for (let i = 0; i < 1024; ++i)713          data.setUint8(i, i & 0xff);714        return waitForDisconnect(fakeDevice)715          .then(() => assertRejectsWithNotFoundError(device.transferOut(2, data)));716      });717  });718}, 'transferOut rejects if called on a disconnected device');719usb_test(() => {720  return getFakeDevice().then(({ device }) => {721    return device.open()722      .then(() => device.selectConfiguration(2))723      .then(() => device.claimInterface(0))724      .then(() => device.selectAlternateInterface(0, 1))725      .then(() => device.isochronousTransferIn(726          1, [64, 64, 64, 64, 64, 64, 64, 64]))727      .then(result => {728        assert_true(result instanceof USBIsochronousInTransferResult);729        assert_equals(result.data.byteLength, 64 * 8, 'buffer size');730        assert_equals(result.packets.length, 8, 'number of packets');731        let byteOffset = 0;732        for (let i = 0; i < result.packets.length; ++i) {733          assert_true(734              result.packets[i] instanceof USBIsochronousInTransferPacket);735          assert_equals(result.packets[i].status, 'ok');736          assert_equals(result.packets[i].data.byteLength, 64);737          assert_equals(result.packets[i].data.buffer, result.data.buffer);738          assert_equals(result.packets[i].data.byteOffset, byteOffset);739          for (let j = 0; j < 64; ++j)740            assert_equals(result.packets[i].data.getUint8(j), j & 0xff,741                          'mismatch at byte ' + j + ' of packet ' + i);742          byteOffset += result.packets[i].data.byteLength;743        }744        return device.close();745      });746  });747}, 'can issue IN isochronous transfer');748usb_test(() => {749  return getFakeDevice().then(({ device, fakeDevice }) => {750    return device.open()751      .then(() => device.selectConfiguration(2))752      .then(() => device.claimInterface(0))753      .then(() => device.selectAlternateInterface(0, 1))754      .then(() => waitForDisconnect(fakeDevice))755      .then(() => assertRejectsWithNotFoundError(device.isochronousTransferIn(756          1, [64, 64, 64, 64, 64, 64, 64, 64])));757  });758}, 'isochronousTransferIn rejects when called on a disconnected device');759usb_test(() => {760  return getFakeDevice().then(({ device }) => {761    return device.open()762      .then(() => device.selectConfiguration(2))763      .then(() => device.claimInterface(0))764      .then(() => device.selectAlternateInterface(0, 1))765      .then(() => {766        let data = new DataView(new ArrayBuffer(64 * 8));767        for (let i = 0; i < 8; ++i) {768          for (let j = 0; j < 64; ++j)769            data.setUint8(i * j, j & 0xff);770        }771        return device.isochronousTransferOut(772            1, data, [64, 64, 64, 64, 64, 64, 64, 64]);773      })774      .then(result => {775        assert_true(result instanceof USBIsochronousOutTransferResult);776        assert_equals(result.packets.length, 8, 'number of packets');777        let byteOffset = 0;778        for (let i = 0; i < result.packets.length; ++i) {779          assert_true(780              result.packets[i] instanceof USBIsochronousOutTransferPacket);781          assert_equals(result.packets[i].status, 'ok');782          assert_equals(result.packets[i].bytesWritten, 64);783        }784        return device.close();785      });786  });787}, 'can issue OUT isochronous transfer');788usb_test(() => {789  return getFakeDevice().then(({ device, fakeDevice }) => {790    return device.open()791      .then(() => device.selectConfiguration(2))792      .then(() => device.claimInterface(0))793      .then(() => device.selectAlternateInterface(0, 1))794      .then(() => {795        let data = new DataView(new ArrayBuffer(64 * 8));796        for (let i = 0; i < 8; ++i) {797          for (let j = 0; j < 64; ++j)798            data.setUint8(i * j, j & 0xff);799        }800        return waitForDisconnect(fakeDevice)801          .then(() => assertRejectsWithNotFoundError(device.isochronousTransferOut(802              1, data, [64, 64, 64, 64, 64, 64, 64, 64])));803      });804  });805}, 'isochronousTransferOut rejects when called on a disconnected device');806usb_test(() => {807  return getFakeDevice().then(({ device }) => {808    return device.open().then(() => device.reset()).then(() => device.close());809  });810}, 'can reset the device');811usb_test(() => {812  return getFakeDevice().then(({ device, fakeDevice }) => {813    return device.open()814      .then(() => waitForDisconnect(fakeDevice))815      .then(() => assertRejectsWithNotFoundError(device.reset()));816  });...device.py
Source:device.py  
...56        self.device_id = device_id57        return self.device_id58    def query_download_filename(self, file_id=None):59        pass60    def ping_device(self):61        pass62    def check_device(self):63        pass64    def cleanup_device(self, reboot=False):65        pass66    def reboot_device(self):67        pass68    def query_device_root(self):69        pass70    def wait_for_device(self, interval=60, max_attempts=20):71        pass72    def install_app(self, file_path):73        pass74# ADBDeviceHandler {{{175class ADBDeviceHandler(BaseDeviceHandler):76    def __init__(self, **kwargs):77        super(ADBDeviceHandler, self).__init__(**kwargs)78        self.default_port = 555579    def query_device_exe(self, exe_name):80        return self.query_exe(exe_name, exe_dict="device_exes")81    def _query_config_device_id(self):82        return BaseDeviceHandler.query_device_id(self)83    def query_device_id(self, auto_connect=True):84        if self.device_id:85            return self.device_id86        device_id = self._query_config_device_id()87        if device_id:88            if auto_connect:89                self.ping_device(auto_connect=True)90        else:91            self.info("Trying to find device...")92            devices = self._query_attached_devices()93            if not devices:94                self.add_device_flag(DEVICE_NOT_CONNECTED)95                self.fatal("No device connected via adb!\nUse 'adb connect' or specify a device_id or device_ip in config!")96            elif len(devices) > 1:97                self.warning("""More than one device detected; specify 'device_id' or\n'device_ip' to target a specific device!""")98            device_id = devices[0]99            self.info("Found %s." % device_id)100        self.device_id = device_id101        return self.device_id102    # maintenance {{{2103    def ping_device(self, auto_connect=False, silent=False):104        if auto_connect and not self._query_attached_devices():105            self.connect_device()106        if not silent:107            self.info("Determining device connectivity over adb...")108        device_id = self.query_device_id()109        adb = self.query_exe('adb')110        uptime = self.query_device_exe('uptime')111        output = self.get_output_from_command([adb, "-s", device_id,112                                               "shell", uptime],113                                              silent=silent)114        if str(output).startswith("up time:"):115            if not silent:116                self.info("Found %s." % device_id)117            return True118        elif auto_connect:119            # TODO retry?120            self.connect_device()121            return self.ping_device()122        else:123            if not silent:124                self.error("Can't find a device.")125            return False126    def _query_attached_devices(self):127        devices = []128        adb = self.query_exe('adb')129        output = self.get_output_from_command([adb, "devices"])130        starting_list = False131        if output is None:132            self.add_device_flag(DEVICE_HOST_ERROR)133            self.fatal("Can't get output from 'adb devices'; install the Android SDK!")134        for line in output:135            if 'adb: command not found' in line:136                self.add_device_flag(DEVICE_HOST_ERROR)137                self.fatal("Can't find adb; install the Android SDK!")138            if line.startswith("* daemon"):139                continue140            if line.startswith("List of devices"):141                starting_list = True142                continue143            # TODO somehow otherwise determine whether this is an actual144            # device?145            if starting_list:146                devices.append(re.split('\s+', line)[0])147        return devices148    def connect_device(self):149        self.info("Connecting device...")150        adb = self.query_exe('adb')151        cmd = [adb, "connect"]152        device_id = self._query_config_device_id()153        if device_id:154            devices = self._query_attached_devices()155            if device_id in devices:156                # TODO is this the right behavior?157                self.disconnect_device()158            cmd.append(device_id)159        # TODO error check160        self.run_command(cmd, error_list=ADBErrorList)161    def disconnect_device(self):162        self.info("Disconnecting device...")163        device_id = self.query_device_id()164        if device_id:165            adb = self.query_exe('adb')166            # TODO error check167            self.run_command([adb, "-s", device_id,168                              "disconnect"],169                             error_list=ADBErrorList)170        else:171            self.info("No device found.")172    def check_device(self):173        if not self.ping_device(auto_connect=True):174            self.add_device_flag(DEVICE_NOT_CONNECTED)175            self.fatal("Can't find device!")176        if self.query_device_root() is None:177            self.add_device_flag(DEVICE_NOT_CONNECTED)178            self.fatal("Can't connect to device!")179    def reboot_device(self):180        if not self.ping_device(auto_connect=True):181            self.add_device_flag(DEVICE_NOT_REBOOTED)182            self.error("Can't reboot disconnected device!")183            return False184        device_id = self.query_device_id()185        self.info("Rebooting device...")186        adb = self.query_exe('adb')187        cmd = [adb, "-s", device_id, "reboot"]188        self.info("Running command (in the background): %s" % cmd)189        # This won't exit until much later, but we don't need to wait.190        # However, some error checking would be good.191        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,192                             stderr=subprocess.STDOUT)193        time.sleep(10)194        self.disconnect_device()195        status = False196        try:197            self.wait_for_device()198            status = True199        except DeviceException:200            self.error("Can't reconnect to device!")201        if p.poll() is None:202            p.kill()203        p.wait()204        return status205    def cleanup_device(self, reboot=False):206        self.info("Cleaning up device.")207        c = self.config208        device_id = self.query_device_id()209        status = self.remove_device_root()210        if not status:211            self.add_device_flag(DEVICE_CANT_REMOVE_DEVROOT)212            self.fatal("Can't remove device root!")213        if c.get("enable_automation"):214            self.remove_etc_hosts()215        if c.get("device_package_name"):216            adb = self.query_exe('adb')217            killall = self.query_device_exe('killall')218            self.run_command([adb, "-s", device_id, "shell",219                              killall, c["device_package_name"]],220                             error_list=ADBErrorList)221            self.uninstall_app(c['device_package_name'])222        if reboot:223            self.reboot_device()224    # device calls {{{2225    def query_device_root(self, silent=False):226        if self.device_root:227            return self.device_root228        device_root = None229        device_id = self.query_device_id()230        adb = self.query_exe('adb')231        output = self.get_output_from_command("%s -s %s shell df" % (adb, device_id),232                                              silent=silent)233        # TODO this assumes we're connected; error checking?234        if output is None or ' not found' in str(output):235            self.error("Can't get output from 'adb shell df'!\n%s" % output)236            return None237        if "/mnt/sdcard" in output:238            device_root = "/mnt/sdcard/tests"239        else:240            device_root = "/data/local/tmp/tests"241        if not silent:242            self.info("Device root is %s" % str(device_root))243        self.device_root = device_root244        return self.device_root245    # TODO from here on down needs to be copied to Base+SUT246    def wait_for_device(self, interval=60, max_attempts=20):247        self.info("Waiting for device to come back...")248        time.sleep(interval)249        tries = 0250        while tries <= max_attempts:251            tries += 1252            self.info("Try %d" % tries)253            if self.ping_device(auto_connect=True, silent=True):254                return self.ping_device()255            time.sleep(interval)256        raise DeviceException("Remote Device Error: waiting for device timed out.")257    def query_device_time(self):258        device_id = self.query_device_id()259        adb = self.query_exe('adb')260        # adb shell 'date' will give a date string261        date_string = self.get_output_from_command([adb, "-s", device_id,262                                                    "shell", "date"])263        # TODO what to do when we error?264        return date_string265    def set_device_time(self, device_time=None, error_level='error'):266        # adb shell date -s YYYYMMDD.hhmmss will set date267        device_id = self.query_device_id()268        if device_time is None:269            device_time = time.strftime("%Y%m%d.%H%M%S")270        self.info(self.query_device_time())271        adb = self.query_exe('adb')272        status = self.run_command([adb, "-s", device_id,  "shell", "date", "-s",273                                   str(device_time)],274                                  error_list=ADBErrorList)275        self.info(self.query_device_time())276        return status277    def query_device_file_exists(self, file_name):278        device_id = self.query_device_id()279        adb = self.query_exe('adb')280        output = self.get_output_from_command([adb, "-s", device_id,281                                               "shell", "ls", "-d", file_name])282        if str(output).rstrip() == file_name:283            return True284        return False285    def remove_device_root(self, error_level='error'):286        device_root = self.query_device_root()287        device_id = self.query_device_id()288        if device_root is None:289            self.add_device_flag(DEVICE_UNREACHABLE)290            self.fatal("Can't connect to device!")291        adb = self.query_exe('adb')292        if self.query_device_file_exists(device_root):293            self.info("Removing device root %s." % device_root)294            self.run_command([adb, "-s", device_id, "shell", "rm",295                              "-r", device_root], error_list=ADBErrorList)296            if self.query_device_file_exists(device_root):297                self.add_device_flag(DEVICE_CANT_REMOVE_DEVROOT)298                self.log("Unable to remove device root!", level=error_level)299                return False300        return True301    def install_app(self, file_path):302        c = self.config303        device_id = self.query_device_id()304        adb = self.query_exe('adb')305        if self._log_level_at_least(DEBUG):306            self.run_command([adb, "-s", device_id, "shell", "ps"],307                             error_list=ADBErrorList)308            uptime = self.query_device_exe('uptime')309            self.run_command([adb, "-s", "shell", uptime],310                             error_list=ADBErrorList)311        if not c['enable_automation']:312            # -s to install on sdcard? Needs to be config driven313            self.run_command([adb, "-s", device_id, "install", '-r',314                              file_path],315                             error_list=ADBErrorList)316        else:317            # A slow-booting device may not allow installs, temporarily.318            # Wait up to a few minutes if not immediately successful.319            # Note that "adb install" typically writes status messages320            # to stderr and the adb return code may not differentiate321            # successful installations from failures; instead we check322            # the command output.323            install_complete = False324            retries = 0325            while retries < 6:326                output = self.get_output_from_command([adb, "-s", device_id,327                                                       "install", '-r',328                                                       file_path],329                                                       ignore_errors=True)330                if output and output.lower().find("success") >= 0:331                    install_complete = True332                    break333                self.warning("Failed to install %s" % file_path)334                time.sleep(30)335                retries = retries + 1336            if not install_complete:337                self.fatal("Failed to install %s!" % file_path)338    def uninstall_app(self, package_name, package_root="/data/data",339                      error_level="error"):340        c = self.config341        device_id = self.query_device_id()342        self.info("Uninstalling %s..." % package_name)343        if self.query_device_file_exists('%s/%s' % (package_root, package_name)):344            adb = self.query_exe('adb')345            cmd = [adb, "-s", device_id, "uninstall"]346            if not c.get('enable_automation'):347                cmd.append("-k")348            cmd.append(package_name)349            status = self.run_command(cmd, error_list=ADBErrorList)350            # TODO is this the right error check?351            if status:352                self.log("Failed to uninstall %s!" % package_name,353                         level=error_level)354    # Device-type-specific. {{{2355    def remove_etc_hosts(self, hosts_file="/system/etc/hosts"):356        c = self.config357        if c['device_type'] not in ("tegra250",):358            self.debug("No need to remove /etc/hosts on a non-Tegra250.")359            return360        device_id = self.query_device_id()361        if self.query_device_file_exists(hosts_file):362            self.info("Removing %s file." % hosts_file)363            adb = self.query_exe('adb')364            self.run_command([adb, "-s", device_id, "shell",365                              "mount", "-o", "remount,rw", "-t", "yaffs2",366                              "/dev/block/mtdblock3", "/system"],367                             error_list=ADBErrorList)368            self.run_command([adb, "-s", device_id, "shell", "rm",369                              hosts_file])370            if self.query_device_file_exists(hosts_file):371                self.add_device_flag(DEVICE_CANT_REMOVE_ETC_HOSTS)372                self.fatal("Unable to remove %s!" % hosts_file)373        else:374            self.debug("%s file doesn't exist; skipping." % hosts_file)375# SUTDeviceHandler {{{1376class SUTDeviceHandler(BaseDeviceHandler):377    def __init__(self, **kwargs):378        super(SUTDeviceHandler, self).__init__(**kwargs)379        self.devicemanager = None380        self.default_port = 20701381        self.default_heartbeat_port = 20700382        self.DMError = None383    def query_devicemanager(self):384        if self.devicemanager:385            return self.devicemanager386        c = self.config387        site_packages_path = self.script_obj.query_python_site_packages_path()388        dm_path = os.path.join(site_packages_path, 'mozdevice')389        sys.path.append(dm_path)390        try:391            from devicemanagerSUT import DeviceManagerSUT392            from devicemanagerSUT import DMError393            self.DMError = DMError394            self.devicemanager = DeviceManagerSUT(c['device_ip'])395            # TODO configurable?396            self.devicemanager.debug = c.get('devicemanager_debug_level', 0)397        except ImportError, e:398            self.fatal("Can't import DeviceManagerSUT! %s\nDid you check out talos?" % str(e))399        return self.devicemanager400    # maintenance {{{2401    def ping_device(self):402        #TODO writeme403        pass404    def check_device(self):405        self.info("Checking for device root to verify the device is alive.")406        dev_root = self.query_device_root(strict=True)407        if not dev_root:408            self.add_device_flag(DEVICE_UNREACHABLE)409            self.fatal("Can't get dev_root from devicemanager; is the device up?")410        self.info("Found a dev_root of %s." % str(dev_root))411    def wait_for_device(self, interval=60, max_attempts=20):412        self.info("Waiting for device to come back...")413        time.sleep(interval)414        success = False415        attempts = 0416        while attempts <= max_attempts:417            attempts += 1418            self.info("Try %d" % attempts)419            if self.query_device_root() is not None:420                success = True421                break422            time.sleep(interval)423        if not success:424            self.add_device_flag(DEVICE_UNREACHABLE)425            self.fatal("Waiting for tegra timed out.")426        else:427            self.info("Device came back.")428    def cleanup_device(self, reboot=False):429        c = self.config430        dev_root = self.query_device_root()431        dm = self.query_devicemanager()432        if dm.dirExists(dev_root):433            self.info("Removing dev_root %s..." % dev_root)434            try:435                dm.removeDir(dev_root)436            except self.DMError:437                self.add_device_flag(DEVICE_CANT_REMOVE_DEVROOT)438                self.fatal("Can't remove dev_root!")439        if c.get("enable_automation"):440            self.remove_etc_hosts()441        # TODO I need to abstract this uninstall as we'll need to clean442        # multiple packages off devices.443        if c.get("device_package_name"):444            if dm.dirExists('/data/data/%s' % c['device_package_name']):445                self.info("Uninstalling %s..." % c['device_package_name'])446                dm.uninstallAppAndReboot(c['device_package_name'])447                self.wait_for_device()448            elif reboot:449                self.reboot_device()450    # device calls {{{2451    def query_device_root(self, strict=False):452        c = self.config453        dm = self.query_devicemanager()454        dev_root = dm.getDeviceRoot()455        if strict and c.get('enable_automation'):456            if not str(dev_root).startswith("/mnt/sdcard"):457                self.add_device_flag(DEVICE_MISSING_SDCARD)458                self.fatal("dev_root from devicemanager [%s] is not correct!" %459                           str(dev_root))460        if not dev_root or dev_root == "/tests":461            return None462        return dev_root463    def query_device_time(self):464        dm = self.query_devicemanager()465        timestamp = int(dm.getCurrentTime())  # epoch time in milliseconds466        dt = datetime.datetime.utcfromtimestamp(timestamp / 1000)467        self.info("Current device time is %s" % dt.strftime('%Y/%m/%d %H:%M:%S'))468        return dt469    def set_device_time(self):470        dm = self.query_devicemanager()471        s = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')472        self.info("Setting device time to %s" % s)473        try:474            dm.sendCMD(['settime %s' % s])475            return True476        except self.DMError, e:477            self.add_device_flag(DEVICE_CANT_SET_TIME)478            self.fatal("Exception while setting device time: %s" % str(e))479    def install_app(self, file_path):480        dev_root = self.query_device_root(strict=True)481        if not dev_root:482            self.add_device_flag(DEVICE_UNREACHABLE)483            # TODO wait_for_device?484            self.fatal("dev_root %s not correct!" % str(dev_root))485        dm = self.query_devicemanager()486        c = self.config487        if c.get('enable_automation'):488            self.query_device_time()489            self.set_device_time()490            self.query_device_time()491            dm.getInfo('process')492            dm.getInfo('memory')493            dm.getInfo('uptime')494        # This target needs to not use os.path.join due to differences with win495        # Paths vs. unix paths.496        target = "/".join([dev_root, os.path.basename(file_path)])497        self.info("Installing %s on device..." % file_path)498        dm.pushFile(file_path, target)499        # TODO screen resolution500        # TODO do something with status?501        try:502            dm.installApp(target)503            self.info('-' * 42)504            self.info("Sleeping for 90 seconds...")505            time.sleep(90)506            self.info('installApp(%s) done - gathering debug info' % target)507            try:508                self.info(repr(dm.getInfo('process')))509                self.info(repr(dm.getInfo('memory')))510                self.info(repr(dm.getInfo('uptime')))511                self.info(repr(dm.sendCMD(['exec su -c "logcat -d -v time *:W"'])))512            except Exception, e:513                self.info("Exception hit while trying to run logcat: %s" % str(e))514                self.fatal("Remote Device Error: can't run logcat")515        except self.DMError:516            self.fatal("Remote Device Error: installApp() call failed - exiting")517    def reboot_device(self):518        dm = self.query_devicemanager()519        # logcat?520        self.info("Rebooting device...")521        try:522            dm.reboot()523        except self.DMError:524            self.add_device_flag(DEVICE_NOT_REBOOTED)525            self.fatal("Can't reboot device!")526        self.wait_for_device()527        dm.getInfo('uptime')528    # device type specific {{{2529    def remove_etc_hosts(self, hosts_file="/system/etc/hosts"):530        c = self.config531        # TODO figure this out532        if c['device_type'] not in ("tegra250",) or True:533            self.debug("No need to remove /etc/hosts on a non-Tegra250.")534            return535        dm = self.query_devicemanager()536        if dm.fileExists(hosts_file):537            self.info("Removing %s file." % hosts_file)538            try:539                dm.sendCMD(['exec mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system'])540                dm.sendCMD(['exec rm %s' % hosts_file])541            except self.DMError:542                self.add_device_flag(DEVICE_CANT_REMOVE_ETC_HOSTS)543                self.fatal("Unable to remove %s!" % hosts_file)544            if dm.fileExists(hosts_file):545                self.add_device_flag(DEVICE_CANT_REMOVE_ETC_HOSTS)546                self.fatal("Unable to remove %s!" % hosts_file)547        else:548            self.debug("%s file doesn't exist; skipping." % hosts_file)549# SUTDeviceMozdeviceMixin {{{1550class SUTDeviceMozdeviceMixin(SUTDeviceHandler):551    '''552    This SUT device manager class makes calls through mozdevice (from mozbase) [1]553    directly rather than calling SUT tools.554    [1] https://github.com/mozilla/mozbase/blob/master/mozdevice/mozdevice/devicemanagerSUT.py555    '''556    dm = None557    def query_devicemanager(self):558        if self.dm:559            return self.dm560        sys.path.append(self.query_python_site_packages_path())561        from mozdevice.devicemanagerSUT import DeviceManagerSUT562        self.info("Connecting to: %s" % self.mozpool_device)563        self.dm = DeviceManagerSUT(self.mozpool_device)564        # No need for 300 second SUT socket timeouts here565        self.dm.default_timeout = 30566        return self.dm567    def query_file(self, filename):568        dm = self.query_devicemanager()569        if not dm.fileExists(filename):570            raise Exception("Expected file (%s) not found" % filename)571        file_contents = dm.pullFile(filename)572        if file_contents is None:573            raise Exception("Unable to read file (%s)" % filename)574        return file_contents575    def set_device_epoch_time(self, timestamp=int(time.time())):576        dm = self.query_devicemanager()577        dm._runCmds([{'cmd': 'setutime %s' % timestamp}])578        return dm._runCmds([{'cmd': 'clok'}])579    def get_logcat(self):580        dm = self.query_devicemanager()581        return dm.getLogcat()582# DeviceMixin {{{1583DEVICE_PROTOCOL_DICT = {584    'adb': ADBDeviceHandler,585    'sut': SUTDeviceHandler,586}587device_config_options = [[588    ["--device-ip"],589    {"action": "store",590     "dest": "device_ip",591     "help": "Specify the IP address of the device."592     }593], [594    ["--device-port"],595    {"action": "store",596     "dest": "device_port",597     "help": "Specify the IP port of the device."598     }599], [600    ["--device-heartbeat-port"],601    {"action": "store",602     "dest": "device_heartbeat_port",603     "help": "Specify the heartbeat port of the SUT device."604     }605], [606    ["--device-protocol"],607    {"action": "store",608     "type": "choice",609     "dest": "device_protocol",610     "choices": DEVICE_PROTOCOL_DICT.keys(),611     "help": "Specify the device communication protocol."612     }613], [614    ["--device-type"],615    # A bit useless atm, but we can add new device types as we add support616    # for them.617    {"action": "store",618     "type": "choice",619     "choices": ["non-tegra", "tegra250"],620     "default": "non-tegra",621     "dest": "device_type",622     "help": "Specify the device type."623     }624], [625    ["--devicemanager-path"],626    {"action": "store",627     "dest": "devicemanager_path",628     "help": "Specify the parent dir of devicemanagerSUT.py."629     }630]]631class DeviceMixin(object):632    '''BaseScript mixin, designed to interface with the device.633    '''634    device_handler = None635    device_root = None636    def query_device_handler(self):637        if self.device_handler:638            return self.device_handler639        c = self.config640        device_protocol = c.get('device_protocol')641        device_class = DEVICE_PROTOCOL_DICT.get(device_protocol)642        if not device_class:643            self.fatal("Unknown device_protocol %s; set via --device-protocol!" % str(device_protocol))644        self.device_handler = device_class(645            log_obj=self.log_obj,646            config=self.config,647            script_obj=self,648        )649        return self.device_handler650    def check_device(self):651        dh = self.query_device_handler()652        return dh.check_device()653    def cleanup_device(self, **kwargs):654        dh = self.query_device_handler()655        return dh.cleanup_device(**kwargs)656    def install_app(self):657        dh = self.query_device_handler()658        return dh.install_app(file_path=self.installer_path)659    def reboot_device(self):660        dh = self.query_device_handler()...test_accounts_device_registration.js
Source:test_accounts_device_registration.js  
...100    },101    DEVICE_REGISTRATION_VERSION102  });103}104add_task(function* test_updateDeviceRegistration_with_new_device() {105  const deviceName = "foo";106  const deviceType = "bar";107  const credentials = getTestUser("baz");108  delete credentials.deviceId;109  const fxa = new MockFxAccounts({ name: deviceName });110  yield fxa.internal.setSignedInUser(credentials);111  const spy = {112    registerDevice: { count: 0, args: [] },113    updateDevice: { count: 0, args: [] },114    getDeviceList: { count: 0, args: [] }115  };116  const client = fxa.internal.fxAccountsClient;117  client.registerDevice = function () {118    spy.registerDevice.count += 1;119    spy.registerDevice.args.push(arguments);120    return Promise.resolve({121      id: "newly-generated device id",122      createdAt: Date.now(),123      name: deviceName,124      type: deviceType125    });126  };127  client.updateDevice = function () {128    spy.updateDevice.count += 1;129    spy.updateDevice.args.push(arguments);130    return Promise.resolve({});131  };132  client.getDeviceList = function () {133    spy.getDeviceList.count += 1;134    spy.getDeviceList.args.push(arguments);135    return Promise.resolve([]);136  };137  const result = yield fxa.updateDeviceRegistration();138  do_check_eq(result, "newly-generated device id");139  do_check_eq(spy.updateDevice.count, 0);140  do_check_eq(spy.getDeviceList.count, 0);141  do_check_eq(spy.registerDevice.count, 1);142  do_check_eq(spy.registerDevice.args[0].length, 4);143  do_check_eq(spy.registerDevice.args[0][0], credentials.sessionToken);144  do_check_eq(spy.registerDevice.args[0][1], deviceName);145  do_check_eq(spy.registerDevice.args[0][2], "desktop");146  do_check_eq(spy.registerDevice.args[0][3].pushCallback, "http://mochi.test:8888");147  do_check_eq(spy.registerDevice.args[0][3].pushPublicKey, BOGUS_PUBLICKEY);148  do_check_eq(spy.registerDevice.args[0][3].pushAuthKey, BOGUS_AUTHKEY);149  const state = fxa.internal.currentAccountState;150  const data = yield state.getUserAccountData();151  do_check_eq(data.deviceId, "newly-generated device id");152  do_check_eq(data.deviceRegistrationVersion, DEVICE_REGISTRATION_VERSION);153});154add_task(function* test_updateDeviceRegistration_with_existing_device() {155  const deviceName = "phil's device";156  const deviceType = "desktop";157  const credentials = getTestUser("pb");158  const fxa = new MockFxAccounts({ name: deviceName });159  yield fxa.internal.setSignedInUser(credentials);160  const spy = {161    registerDevice: { count: 0, args: [] },162    updateDevice: { count: 0, args: [] },163    getDeviceList: { count: 0, args: [] }164  };165  const client = fxa.internal.fxAccountsClient;166  client.registerDevice = function () {167    spy.registerDevice.count += 1;168    spy.registerDevice.args.push(arguments);...device.test.js
Source:device.test.js  
1/* eslint-env mocha */2const assert = require('assert');3const Device = require('../src/device');4const FileInfo = require('../src/file-info');5describe('Device', () => {6  it('scanimage-a1.txt', () => {7    const file = FileInfo.create('test/resource/scanimage-a1.txt');8    const device = Device.from(file.toText());9    assert.strictEqual(device.id, 'plustek:libusb:001:008');10    assert.deepStrictEqual(device.features['--mode'].options, ['Lineart', 'Gray', 'Color']);11    assert.strictEqual(device.features['--mode'].default, 'Color');12    assert.strictEqual(device.features['--source'], undefined);13    assert.deepStrictEqual(device.features['--resolution'].options, [50, 75, 150, 300, 600, 1200]);14    assert.strictEqual(device.features['--resolution'].default, 50);15    assert.strictEqual(device.features['-l'].limits[0], 0);16    assert.strictEqual(device.features['-l'].limits[1], 215);17    assert.strictEqual(device.features['-l'].default, 0);18    assert.strictEqual(device.features['-t'].limits[0], 0);19    assert.strictEqual(device.features['-t'].limits[1], 297);20    assert.strictEqual(device.features['-t'].default, 0);21    assert.strictEqual(device.features['-x'].limits[0], 0);22    assert.strictEqual(device.features['-x'].limits[1], 215);23    assert.strictEqual(device.features['-x'].default, 103);24    assert.strictEqual(device.features['-y'].limits[0], 0);25    assert.strictEqual(device.features['-y'].limits[1], 297);26    assert.strictEqual(device.features['-y'].default, 76.2);27    assert.strictEqual(device.features['--brightness'].limits[0], -100);28    assert.strictEqual(device.features['--brightness'].limits[1], 100);29    assert.strictEqual(device.features['--brightness'].interval, 1);30    assert.strictEqual(device.features['--brightness'].default, 0);31    assert.strictEqual(device.features['--contrast'].limits[0], -100);32    assert.strictEqual(device.features['--contrast'].limits[1], 100);33    assert.strictEqual(device.features['--contrast'].interval, 1);34    assert.strictEqual(device.features['--contrast'].default, 0);35  });36  it('scanimage-a2.txt', () => {37    const file = FileInfo.create('test/resource/scanimage-a2.txt');38    const device = Device.from(file.toText());39    assert.strictEqual(device.id, 'epson2:libusb:001:029');40    assert.deepStrictEqual(device.features['--mode'].options, ['Lineart', 'Gray', 'Color']);41    assert.strictEqual(device.features['--mode'].default, 'Lineart');42    assert.strictEqual(device.features['--source'], undefined);43    assert.deepStrictEqual(device.features['--resolution'].options, [75, 300, 600, 1200]);44    assert.strictEqual(device.features['--resolution'].default, 75);45    assert.strictEqual(device.features['-l'].limits[0], 0);46    assert.strictEqual(device.features['-l'].limits[1], 215.9);47    assert.strictEqual(device.features['-l'].default, 0);48    assert.strictEqual(device.features['-t'].limits[0], 0);49    assert.strictEqual(device.features['-t'].limits[1], 297.1);50    assert.strictEqual(device.features['-t'].default, 0);51    assert.strictEqual(device.features['-x'].limits[0], 0);52    assert.strictEqual(device.features['-x'].limits[1], 215.9);53    assert.strictEqual(device.features['-x'].default, 215.9);54    assert.strictEqual(device.features['-y'].limits[0], 0);55    assert.strictEqual(device.features['-y'].limits[1], 297.1);56    assert.strictEqual(device.features['-y'].default, 297.1);57    assert.strictEqual(device.features['--brightness'], undefined);58    assert.strictEqual(device.features['--contrast'], undefined);59  });60  it('scanimage-a3.txt', () => {61    const file = FileInfo.create('test/resource/scanimage-a3.txt');62    const device = Device.from(file.toText());63    assert.strictEqual(device.id, 'magic');64    assert.deepStrictEqual(device.features['--mode'].options, ['Lineart', 'Gray', '24bitColor']);65    assert.strictEqual(device.features['--mode'].default, '24bitColor');66    assert.strictEqual(device.features['--source'], undefined);67    assert.deepStrictEqual(device.features['--resolution'].options, [75, 300, 600, 1200]);68    assert.strictEqual(device.features['--resolution'].default, 75);69    assert.strictEqual(device.features['-l'].limits[0], 0);70    assert.strictEqual(device.features['-l'].limits[1], 215.9);71    assert.strictEqual(device.features['-t'].limits[0], 0);72    assert.strictEqual(device.features['-t'].limits[1], 297.1);73    assert.strictEqual(device.features['-x'].limits[0], 0);74    assert.strictEqual(device.features['-x'].limits[1], 215.9);75    assert.strictEqual(device.features['-y'].limits[0], 0);76    assert.strictEqual(device.features['-y'].limits[1], 297.1);77    assert.strictEqual(device.features['--brightness'].limits[0], -50);78    assert.strictEqual(device.features['--brightness'].limits[1], 50);79    assert.strictEqual(device.features['--brightness'].interval, 1);80    assert.strictEqual(device.features['--brightness'].default, 0);81    assert.strictEqual(device.features['--contrast'].limits[0], -50);82    assert.strictEqual(device.features['--contrast'].limits[1], 50);83    assert.strictEqual(device.features['--contrast'].interval, 10);84    assert.strictEqual(device.features['--contrast'].default, 0);85  });86  it('scanimage-a4.txt', () => {87    const file = FileInfo.create('test/resource/scanimage-a4.txt');88    const device = Device.from(file.toText());89    assert.strictEqual(device.id, 'net:192.168.1.4:xerox_mfp:libusb:001:003');90    assert.deepStrictEqual(device.features['--mode'].options, ['Lineart', 'Halftone', 'Gray', 'Color']);91    assert.strictEqual(device.features['--mode'].default, 'Color');92    assert.deepStrictEqual(device.features['--source'].options, ['Flatbed', 'ADF', 'Auto']);93    assert.strictEqual(device.features['--source'].default, 'Flatbed');94    assert.deepStrictEqual(device.features['--resolution'].options, [75, 100, 150, 200, 300, 600, 1200]);95    assert.strictEqual(device.features['--resolution'].default, 150);96    assert.strictEqual(device.features['-l'].limits[0], 0);97    assert.strictEqual(device.features['-l'].limits[1], 215.9);98    assert.strictEqual(device.features['-t'].limits[0], 0);99    assert.strictEqual(device.features['-t'].limits[1], 297.1);100    assert.strictEqual(device.features['-x'].limits[0], 0);101    assert.strictEqual(device.features['-x'].limits[1], 215.9);102    assert.strictEqual(device.features['-y'].limits[0], 0);103    assert.strictEqual(device.features['-y'].limits[1], 297.1);104    assert.strictEqual(device.features['--brightness'], undefined);105    assert.strictEqual(device.features['--contrast'], undefined);106  });107  it('scanimage-a5.txt', () => {108    const file = FileInfo.create('test/resource/scanimage-a5.txt');109    const device = Device.from(file.toText());110    assert.strictEqual(device.id, 'pixma:04A91766_004AE4');111    assert.deepStrictEqual(device.features['--mode'].options, ['Color', 'Gray', 'Lineart']);112    assert.strictEqual(device.features['--mode'].default, 'Color');113    assert.deepStrictEqual(device.features['--source'].options, ['Flatbed', 'Automatic Document Feeder']);114    assert.strictEqual(device.features['--source'].default, 'Flatbed');115    assert.deepStrictEqual(device.features['--resolution'].options, [75, 150, 300, 600, 1200]);116    assert.strictEqual(device.features['--resolution'].default, 75);117    assert.strictEqual(device.features['-l'].limits[0], 0);118    assert.strictEqual(device.features['-l'].limits[1], 216);119    assert.strictEqual(device.features['-t'].limits[0], 0);120    assert.strictEqual(device.features['-t'].limits[1], 355.6);121    assert.strictEqual(device.features['-x'].limits[0], 0);122    assert.strictEqual(device.features['-x'].limits[1], 216);123    assert.strictEqual(device.features['-y'].limits[0], 0);124    assert.strictEqual(device.features['-y'].limits[1], 355.6);125    assert.strictEqual(device.features['--brightness'], undefined);126    assert.strictEqual(device.features['--contrast'], undefined);127  });128  it('scanimage-a6.txt', () => {129    const file = FileInfo.create('test/resource/scanimage-a6.txt');130    const device = Device.from(file.toText());131    assert.strictEqual(device.id, 'brother4:bus9;dev1');132    assert.deepStrictEqual(device.features['--mode'].options, ['Black & White', 'Gray[Error Diffusion]', 'True Gray', '24bit Color[Fast]']);133    assert.strictEqual(device.features['--mode'].default, '24bit Color[Fast]');134    assert.deepStrictEqual(device.features['--source'].options, ['FlatBed', 'Automatic Document Feeder(left aligned)', 'Automatic Document Feeder(left aligned,Duplex)', 'Automatic Document Feeder(centrally aligned)', 'Automatic Document Feeder(centrally aligned,Duplex)']);135    assert.strictEqual(device.features['--source'].default, 'Automatic Document Feeder(left aligned)');136    assert.deepStrictEqual(device.features['--resolution'].options, [100, 150, 200, 300, 400, 600, 1200, 2400, 4800, 9600]);137    assert.strictEqual(device.features['--resolution'].default, 200);138    assert.strictEqual(device.features['-l'].limits[0], 0);139    assert.strictEqual(device.features['-l'].limits[1], 215.9);140    assert.strictEqual(device.features['-t'].limits[0], 0);141    assert.strictEqual(device.features['-t'].limits[1], 355.6);142    assert.strictEqual(device.features['-x'].limits[0], 0);143    assert.strictEqual(device.features['-x'].limits[1], 215.9);144    assert.strictEqual(device.features['-y'].limits[0], 0);145    assert.strictEqual(device.features['-y'].limits[1], 355.6);146    assert.strictEqual(device.features['--brightness'], undefined);147    assert.strictEqual(device.features['--contrast'], undefined);148  });149  it('scanimage-a8.txt', () => {150    const file = FileInfo.create('test/resource/scanimage-a8.txt');151    const device = Device.from(file.toText());152    assert.strictEqual(device.id, 'umax1220u:libusb:001:004');153    assert.deepStrictEqual(device.features['--resolution'].options, [75, 150, 300, 600]);154    assert.strictEqual(device.features['--resolution'].default, 75);155    assert.strictEqual(device.features['-l'].limits[0], 0);156    assert.strictEqual(device.features['-l'].limits[1], 228.6);157    assert.strictEqual(device.features['-l'].default, 0);158    assert.strictEqual(device.features['-t'].limits[0], 0);159    assert.strictEqual(device.features['-t'].limits[1], 298);160    assert.strictEqual(device.features['-t'].default, 0);161    assert.strictEqual(device.features['-x'].limits[0], 0);162    assert.strictEqual(device.features['-x'].limits[1], 228.6);163    assert.strictEqual(device.features['-x'].default, 228.6);164    assert.strictEqual(device.features['-y'].limits[0], 0);165    assert.strictEqual(device.features['-y'].limits[1], 298);166    assert.strictEqual(device.features['-y'].default, 298);167  });168  it('scanimage-a9.txt', () => {169    const file = FileInfo.create('test/resource/scanimage-a9.txt');170    const device = Device.from(file.toText());171    assert.strictEqual(device.id, 'utsushi:esci:usb:/sys/devices/platform/soc/20980000.usb/usb1/1-1/1-1.2/1-1.2:1.0');172    assert.deepStrictEqual(device.features['--mode'].options, ['Monochrome', 'Grayscale', 'Color']);173    assert.strictEqual(device.features['--mode'].default, 'Color');174    assert.strictEqual(device.features['--source'], undefined);175    assert.deepStrictEqual(device.features['--resolution'].options, [50, 75, 150, 300, 600, 1200]);176    assert.strictEqual(device.features['--resolution'].default, 75);177    assert.strictEqual(device.features['-l'].limits[0], 0);178    assert.strictEqual(device.features['-l'].limits[1], 215.9);179    assert.strictEqual(device.features['-l'].default, 0);180    assert.strictEqual(device.features['-t'].limits[0], 0);181    assert.strictEqual(device.features['-t'].limits[1], 297.1);182    assert.strictEqual(device.features['-t'].default, 0);183    assert.strictEqual(device.features['-x'].limits[0], 0);184    assert.strictEqual(device.features['-x'].limits[1], 215.9);185    assert.strictEqual(device.features['-x'].default, 215.9);186    assert.strictEqual(device.features['-y'].limits[0], 0);187    assert.strictEqual(device.features['-y'].limits[1], 297.1);188    assert.strictEqual(device.features['-y'].default, 297.1);189  });...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
