Best JavaScript code snippet using wpt
webusb-test.js
Source:webusb-test.js
...10 webUsbServiceInterceptor: null,11 messagePort: null,12};13let mojom = {};14async function loadMojomDefinitions() {15 const deviceMojom =16 await import('/gen/services/device/public/mojom/usb_device.mojom.m.js');17 const serviceMojom = await import(18 '/gen/third_party/blink/public/mojom/usb/web_usb_service.mojom.m.js');19 return {20 ...deviceMojom,21 ...serviceMojom,22 };23}24function getMessagePort(target) {25 return new Promise(resolve => {26 target.addEventListener('message', messageEvent => {27 if (messageEvent.data.type === 'ReadyForAttachment') {28 if (internal.messagePort === null) {29 internal.messagePort = messageEvent.data.port;30 }31 resolve();32 }33 }, {once: true});34 });35}36// Converts an ECMAScript String object to an instance of37// mojo_base.mojom.String16.38function mojoString16ToString(string16) {39 return String.fromCharCode.apply(null, string16.data);40}41// Converts an instance of mojo_base.mojom.String16 to an ECMAScript String.42function stringToMojoString16(string) {43 let array = new Array(string.length);44 for (var i = 0; i < string.length; ++i) {45 array[i] = string.charCodeAt(i);46 }47 return { data: array }48}49function fakeDeviceInitToDeviceInfo(guid, init) {50 let deviceInfo = {51 guid: guid + "",52 usbVersionMajor: init.usbVersionMajor,53 usbVersionMinor: init.usbVersionMinor,54 usbVersionSubminor: init.usbVersionSubminor,55 classCode: init.deviceClass,56 subclassCode: init.deviceSubclass,57 protocolCode: init.deviceProtocol,58 vendorId: init.vendorId,59 productId: init.productId,60 deviceVersionMajor: init.deviceVersionMajor,61 deviceVersionMinor: init.deviceVersionMinor,62 deviceVersionSubminor: init.deviceVersionSubminor,63 manufacturerName: stringToMojoString16(init.manufacturerName),64 productName: stringToMojoString16(init.productName),65 serialNumber: stringToMojoString16(init.serialNumber),66 activeConfiguration: init.activeConfigurationValue,67 configurations: []68 };69 init.configurations.forEach(config => {70 var configInfo = {71 configurationValue: config.configurationValue,72 configurationName: stringToMojoString16(config.configurationName),73 selfPowered: false,74 remoteWakeup: false,75 maximumPower: 0,76 interfaces: [],77 extraData: new Uint8Array()78 };79 config.interfaces.forEach(iface => {80 var interfaceInfo = {81 interfaceNumber: iface.interfaceNumber,82 alternates: []83 };84 iface.alternates.forEach(alternate => {85 var alternateInfo = {86 alternateSetting: alternate.alternateSetting,87 classCode: alternate.interfaceClass,88 subclassCode: alternate.interfaceSubclass,89 protocolCode: alternate.interfaceProtocol,90 interfaceName: stringToMojoString16(alternate.interfaceName),91 endpoints: [],92 extraData: new Uint8Array()93 };94 alternate.endpoints.forEach(endpoint => {95 var endpointInfo = {96 endpointNumber: endpoint.endpointNumber,97 packetSize: endpoint.packetSize,98 synchronizationType: mojom.UsbSynchronizationType.NONE,99 usageType: mojom.UsbUsageType.DATA,100 pollingInterval: 0,101 extraData: new Uint8Array()102 };103 switch (endpoint.direction) {104 case "in":105 endpointInfo.direction = mojom.UsbTransferDirection.INBOUND;106 break;107 case "out":108 endpointInfo.direction = mojom.UsbTransferDirection.OUTBOUND;109 break;110 }111 switch (endpoint.type) {112 case "bulk":113 endpointInfo.type = mojom.UsbTransferType.BULK;114 break;115 case "interrupt":116 endpointInfo.type = mojom.UsbTransferType.INTERRUPT;117 break;118 case "isochronous":119 endpointInfo.type = mojom.UsbTransferType.ISOCHRONOUS;120 break;121 }122 alternateInfo.endpoints.push(endpointInfo);123 });124 interfaceInfo.alternates.push(alternateInfo);125 });126 configInfo.interfaces.push(interfaceInfo);127 });128 deviceInfo.configurations.push(configInfo);129 });130 return deviceInfo;131}132function convertMojoDeviceFilters(input) {133 let output = [];134 input.forEach(filter => {135 output.push(convertMojoDeviceFilter(filter));136 });137 return output;138}139function convertMojoDeviceFilter(input) {140 let output = {};141 if (input.hasVendorId)142 output.vendorId = input.vendorId;143 if (input.hasProductId)144 output.productId = input.productId;145 if (input.hasClassCode)146 output.classCode = input.classCode;147 if (input.hasSubclassCode)148 output.subclassCode = input.subclassCode;149 if (input.hasProtocolCode)150 output.protocolCode = input.protocolCode;151 if (input.serialNumber)152 output.serialNumber = mojoString16ToString(input.serialNumber);153 return output;154}155class FakeDevice {156 constructor(deviceInit) {157 this.info_ = deviceInit;158 this.opened_ = false;159 this.currentConfiguration_ = null;160 this.claimedInterfaces_ = new Map();161 }162 getConfiguration() {163 if (this.currentConfiguration_) {164 return Promise.resolve({165 value: this.currentConfiguration_.configurationValue });166 } else {167 return Promise.resolve({ value: 0 });168 }169 }170 open() {171 assert_false(this.opened_);172 this.opened_ = true;173 return Promise.resolve({error: mojom.UsbOpenDeviceError.OK});174 }175 close() {176 assert_true(this.opened_);177 this.opened_ = false;178 return Promise.resolve();179 }180 setConfiguration(value) {181 assert_true(this.opened_);182 let selectedConfiguration = this.info_.configurations.find(183 configuration => configuration.configurationValue == value);184 // Blink should never request an invalid configuration.185 assert_not_equals(selectedConfiguration, undefined);186 this.currentConfiguration_ = selectedConfiguration;187 return Promise.resolve({ success: true });188 }189 claimInterface(interfaceNumber) {190 assert_true(this.opened_);191 assert_false(this.currentConfiguration_ == null, 'device configured');192 assert_false(this.claimedInterfaces_.has(interfaceNumber),193 'interface already claimed');194 // Blink should never request an invalid interface.195 assert_true(this.currentConfiguration_.interfaces.some(196 iface => iface.interfaceNumber == interfaceNumber));197 this.claimedInterfaces_.set(interfaceNumber, 0);198 return Promise.resolve({ success: true });199 }200 releaseInterface(interfaceNumber) {201 assert_true(this.opened_);202 assert_false(this.currentConfiguration_ == null, 'device configured');203 assert_true(this.claimedInterfaces_.has(interfaceNumber));204 this.claimedInterfaces_.delete(interfaceNumber);205 return Promise.resolve({ success: true });206 }207 setInterfaceAlternateSetting(interfaceNumber, alternateSetting) {208 assert_true(this.opened_);209 assert_false(this.currentConfiguration_ == null, 'device configured');210 assert_true(this.claimedInterfaces_.has(interfaceNumber));211 let iface = this.currentConfiguration_.interfaces.find(212 iface => iface.interfaceNumber == interfaceNumber);213 // Blink should never request an invalid interface or alternate.214 assert_false(iface == undefined);215 assert_true(iface.alternates.some(216 x => x.alternateSetting == alternateSetting));217 this.claimedInterfaces_.set(interfaceNumber, alternateSetting);218 return Promise.resolve({ success: true });219 }220 reset() {221 assert_true(this.opened_);222 return Promise.resolve({ success: true });223 }224 clearHalt(endpoint) {225 assert_true(this.opened_);226 assert_false(this.currentConfiguration_ == null, 'device configured');227 // TODO(reillyg): Assert that endpoint is valid.228 return Promise.resolve({ success: true });229 }230 async controlTransferIn(params, length, timeout) {231 assert_true(this.opened_);232 if ((params.recipient == mojom.UsbControlTransferRecipient.INTERFACE ||233 params.recipient == mojom.UsbControlTransferRecipient.ENDPOINT) &&234 this.currentConfiguration_ == null) {235 return {236 status: mojom.UsbTransferStatus.PERMISSION_DENIED,237 };238 }239 return {240 status: mojom.UsbTransferStatus.OK,241 data: [242 length >> 8, length & 0xff, params.request, params.value >> 8,243 params.value & 0xff, params.index >> 8, params.index & 0xff244 ]245 };246 }247 async controlTransferOut(params, data, timeout) {248 assert_true(this.opened_);249 if ((params.recipient == mojom.UsbControlTransferRecipient.INTERFACE ||250 params.recipient == mojom.UsbControlTransferRecipient.ENDPOINT) &&251 this.currentConfiguration_ == null) {252 return {253 status: mojom.UsbTransferStatus.PERMISSION_DENIED,254 };255 }256 return {status: mojom.UsbTransferStatus.OK, bytesWritten: data.byteLength};257 }258 genericTransferIn(endpointNumber, length, timeout) {259 assert_true(this.opened_);260 assert_false(this.currentConfiguration_ == null, 'device configured');261 // TODO(reillyg): Assert that endpoint is valid.262 let data = new Array(length);263 for (let i = 0; i < length; ++i)264 data[i] = i & 0xff;265 return Promise.resolve({status: mojom.UsbTransferStatus.OK, data: data});266 }267 genericTransferOut(endpointNumber, data, timeout) {268 assert_true(this.opened_);269 assert_false(this.currentConfiguration_ == null, 'device configured');270 // TODO(reillyg): Assert that endpoint is valid.271 return Promise.resolve(272 {status: mojom.UsbTransferStatus.OK, bytesWritten: data.byteLength});273 }274 isochronousTransferIn(endpointNumber, packetLengths, timeout) {275 assert_true(this.opened_);276 assert_false(this.currentConfiguration_ == null, 'device configured');277 // TODO(reillyg): Assert that endpoint is valid.278 let data = new Array(packetLengths.reduce((a, b) => a + b, 0));279 let dataOffset = 0;280 let packets = new Array(packetLengths.length);281 for (let i = 0; i < packetLengths.length; ++i) {282 for (let j = 0; j < packetLengths[i]; ++j)283 data[dataOffset++] = j & 0xff;284 packets[i] = {285 length: packetLengths[i],286 transferredLength: packetLengths[i],287 status: mojom.UsbTransferStatus.OK288 };289 }290 return Promise.resolve({ data: data, packets: packets });291 }292 isochronousTransferOut(endpointNumber, data, packetLengths, timeout) {293 assert_true(this.opened_);294 assert_false(this.currentConfiguration_ == null, 'device configured');295 // TODO(reillyg): Assert that endpoint is valid.296 let packets = new Array(packetLengths.length);297 for (let i = 0; i < packetLengths.length; ++i) {298 packets[i] = {299 length: packetLengths[i],300 transferredLength: packetLengths[i],301 status: mojom.UsbTransferStatus.OK302 };303 }304 return Promise.resolve({ packets: packets });305 }306}307class FakeWebUsbService {308 constructor() {309 this.receiver_ = new mojom.WebUsbServiceReceiver(this);310 this.devices_ = new Map();311 this.devicesByGuid_ = new Map();312 this.client_ = null;313 this.nextGuid_ = 0;314 }315 addBinding(handle) {316 this.receiver_.$.bindHandle(handle);317 }318 addDevice(fakeDevice, info) {319 let device = {320 fakeDevice: fakeDevice,321 guid: (this.nextGuid_++).toString(),322 info: info,323 receivers: [],324 };325 this.devices_.set(fakeDevice, device);326 this.devicesByGuid_.set(device.guid, device);327 if (this.client_)328 this.client_.onDeviceAdded(fakeDeviceInitToDeviceInfo(device.guid, info));329 }330 removeDevice(fakeDevice) {331 let device = this.devices_.get(fakeDevice);332 if (!device)333 throw new Error('Cannot remove unknown device.');334 for (const receiver of device.receivers)335 receiver.$.close();336 this.devices_.delete(device.fakeDevice);337 this.devicesByGuid_.delete(device.guid);338 if (this.client_) {339 this.client_.onDeviceRemoved(340 fakeDeviceInitToDeviceInfo(device.guid, device.info));341 }342 }343 removeAllDevices() {344 this.devices_.forEach(device => {345 for (const receiver of device.receivers)346 receiver.$.close();347 this.client_.onDeviceRemoved(348 fakeDeviceInitToDeviceInfo(device.guid, device.info));349 });350 this.devices_.clear();351 this.devicesByGuid_.clear();352 }353 getDevices() {354 let devices = [];355 this.devices_.forEach(device => {356 devices.push(fakeDeviceInitToDeviceInfo(device.guid, device.info));357 });358 return Promise.resolve({ results: devices });359 }360 getDevice(guid, request) {361 let retrievedDevice = this.devicesByGuid_.get(guid);362 if (retrievedDevice) {363 const receiver =364 new mojom.UsbDeviceReceiver(new FakeDevice(retrievedDevice.info));365 receiver.$.bindHandle(request.handle);366 receiver.onConnectionError.addListener(() => {367 if (retrievedDevice.fakeDevice.onclose)368 retrievedDevice.fakeDevice.onclose();369 });370 retrievedDevice.receivers.push(receiver);371 } else {372 request.handle.close();373 }374 }375 getPermission(deviceFilters) {376 return new Promise(resolve => {377 if (navigator.usb.test.onrequestdevice) {378 navigator.usb.test.onrequestdevice(379 new USBDeviceRequestEvent(deviceFilters, resolve));380 } else {381 resolve({ result: null });382 }383 });384 }385 setClient(client) {386 this.client_ = client;387 }388}389class USBDeviceRequestEvent {390 constructor(deviceFilters, resolve) {391 this.filters = convertMojoDeviceFilters(deviceFilters);392 this.resolveFunc_ = resolve;393 }394 respondWith(value) {395 // Wait until |value| resolves (if it is a Promise). This function returns396 // no value.397 Promise.resolve(value).then(fakeDevice => {398 let device = internal.webUsbService.devices_.get(fakeDevice);399 let result = null;400 if (device) {401 result = fakeDeviceInitToDeviceInfo(device.guid, device.info);402 }403 this.resolveFunc_({ result: result });404 }, () => {405 this.resolveFunc_({ result: null });406 });407 }408}409// Unlike FakeDevice this class is exported to callers of USBTest.addFakeDevice.410class FakeUSBDevice {411 constructor() {412 this.onclose = null;413 }414 disconnect() {415 setTimeout(() => internal.webUsbService.removeDevice(this), 0);416 }417}418class USBTest {419 constructor() {420 this.onrequestdevice = undefined;421 }422 async initialize() {423 if (internal.initialized)424 return;425 // Be ready to handle 'ReadyForAttachment' message from child iframes.426 if ('window' in self) {427 getMessagePort(window);428 }429 mojom = await loadMojomDefinitions();430 internal.webUsbService = new FakeWebUsbService();431 internal.webUsbServiceInterceptor =432 new MojoInterfaceInterceptor(mojom.WebUsbService.$interfaceName);433 internal.webUsbServiceInterceptor.oninterfacerequest =434 e => internal.webUsbService.addBinding(e.handle);435 internal.webUsbServiceInterceptor.start();436 // Wait for a call to GetDevices() to pass between the renderer and the437 // mock in order to establish that everything is set up.438 await navigator.usb.getDevices();439 internal.initialized = true;440 }441 // Returns a promise that is resolved when the implementation of |usb| in the442 // global scope for |context| is controlled by the current context.443 attachToContext(context) {...
Using AI Code Generation
1importScripts('/resources/testharness.js');2importScripts('/resources/testharnessreport.js');3importScripts('/resources/WebIDLParser.js');4importScripts('/resources/idlharness.js');5importScripts('/resources/testdriver.js');6importScripts('/resources/testdriver-vendor.js');7promise_test(async t => {8 const mojomDefinitions = await loadMojomDefinitions('mojom/test.mojom');9 const idl = WebIDL2.parse(mojomDefinitions);10 const idl_array = new IdlArray();11 idl_array.add_idls(idl);12 idl_array.test();13}, 'Test mojom bindings');14module mojo.test;15interface Test {16 Test();17 void testMethod();18};
Using AI Code Generation
1var mojomDefinitions = await loadMojomDefinitions(url);2var mojomInterface = mojomDefinitions.lookup("test.mojom.TestInterface");3var pipe = new MessagePipe();4var remote = new Remote(mojomInterface, pipe.handle0);5var local = new Local(mojomInterface, pipe.handle1);6var result = await remote.doSomething();7assert_equals(result, "Hello from mojom");8local.close();9remote.close();
Using AI Code Generation
1var wpt = new WebPlatformTest();2wpt.loadMojomDefinitions("path/to/mojom_definitions.json");3{4 {5 "interface": {6 {7 {8 }9 {10 }11 }12 }13 }14}15var testInterface = wpt.getInterface("test.mojom.testInterface");16var testInterfaceProxy = testInterface.getProxy();17var testInterfaceStub = testInterface.getStub();18testInterfaceProxy.testMethod(1).then(function(response) {19});20testInterfaceStub.setHandler({21 testMethod: function(testParam) {22 return Promise.resolve(testParam);23 }24});25var testMethod = wpt.getMethod("test.mojom.testInterface.testMethod");26var testMethodProxy = testMethod.getProxy();27var testMethodStub = testMethod.getStub();28testMethodProxy(1).then(function(response) {29});30testMethodStub.setHandler(function(testParam) {31 return Promise.resolve(testParam);32});33var testParam = wpt.getParameter("test.mojom.testInterface.testMethod.testParam");34var testParamProxy = testParam.getProxy();35var testParamStub = testParam.getStub();36testParamProxy(1).then(function(response) {37});38testParamStub.setHandler(function(testParam) {39 return Promise.resolve(testParam);40});41var testResponse = wpt.getResponse("test.mojom.testInterface.testMethod.testResponse");42var testResponseProxy = testResponse.getProxy();43var testResponseStub = testResponse.getStub();44testResponseProxy(1).then(function(response) {45});
Using AI Code Generation
1if (typeof wptRunner === 'undefined') {2 console.log('wptRunner is undefined');3} else {4 wptRunner.loadMojomDefinitions(mojomDefinitions);5}6var mojomInterface = new mojomServiceInterface.MojomInterfacePtr();7var request = new bindings.InterfaceRequest(mojomServiceInterface.MojomInterface);8mojomInterface.bind(request);9mojomInterface.ptr.doSomething();10var callback = function(result) {11 console.log(result);12};13var mojomInterface = new mojomServiceInterface.MojomInterfacePtr();14var request = new bindings.InterfaceRequest(mojomServiceInterface.MojomInterface);15mojomInterface.bind(request);16mojomInterface.ptr.doSomethingWithCallback(callback);17var callback = function(result) {18 console.log(result);19 var mojomInterface = new mojomServiceInterface.MojomInterfacePtr();20 var request = new bindings.InterfaceRequest(mojomServiceInterface.MojomInterface);21 mojomInterface.bind(request);22 mojomInterface.ptr.doSomethingWithCallback(callback);23};24var mojomInterface = new mojomServiceInterface.MojomInterfacePtr();25var request = new bindings.InterfaceRequest(mojomServiceInterface.MojomInterface);26mojomInterface.bind(request);27mojomInterface.ptr.doSomethingWithCallback(callback);28var callback = function(result) {29 console.log(result);30 var mojomInterface = new mojomServiceInterface.MojomInterfacePtr();31 var request = new bindings.InterfaceRequest(mojomServiceInterface.MojomInterface);32 mojomInterface.bind(request);33 mojomInterface.ptr.doSomethingWithCallback(callback);34};35var mojomInterface = new mojomServiceInterface.MojomInterfacePtr();36var request = new bindings.InterfaceRequest(mojomServiceInterface.MojomInterface);37mojomInterface.bind(request);38mojomInterface.ptr.doSomethingWithCallback(callback);
Using AI Code Generation
1loadMojomDefinitions("mojo/public/mojom/base/values.mojom");2let test = new base.mojom.String16("test");3let test2 = new base.mojom.String16("test2");4let test3 = new base.mojom.String16("test3");5let test4 = new base.mojom.String16("test4");6let array = new base.mojom.Array(base.mojom.String16, [test, test2, test3, test4]);7let dict = new base.mojom.Dictionary(base.mojom.String16, base.mojom.String16);8dict.set("test", test);9dict.set("test2", test2);10dict.set("test3", test3);11dict.set("test4", test4);12let testStruct = new base.mojom.Struct();13testStruct.string16Value = test;14testStruct.string16ArrayValue = array;15testStruct.string16DictionaryValue = dict;16let testStruct2 = new base.mojom.Struct();17testStruct2.string16Value = test2;18testStruct2.string16ArrayValue = array;19testStruct2.string16DictionaryValue = dict;20let testStruct3 = new base.mojom.Struct();21testStruct3.string16Value = test3;22testStruct3.string16ArrayValue = array;23testStruct3.string16DictionaryValue = dict;24let testStruct4 = new base.mojom.Struct();25testStruct4.string16Value = test4;26testStruct4.string16ArrayValue = array;27testStruct4.string16DictionaryValue = dict;28let structArray = new base.mojom.Array(base.mojom.Struct, [testStruct, testStruct2, testStruct3, testStruct4]);29let structDict = new base.mojom.Dictionary(base.mojom.String16, base.mojom.Struct);30structDict.set("test", testStruct);31structDict.set("test2", testStruct2);32structDict.set("test3", testStruct3);33structDict.set("test4", testStruct4);34let testStruct2 = new base.mojom.Struct();35testStruct2.string16Value = test2;36testStruct2.string16ArrayValue = array;37testStruct2.string16DictionaryValue = dict;
Using AI Code Generation
1window.onload = function() {2 var harness = new wptTestHarness();3 harness.loadMojomDefinitions("test.mojom");4};5interface TestInterface {6 testMethod();7};8window.onload = function() {9 var harness = new wptTestHarness();10 harness.loadMojomDefinitions("test.mojom");11 harness.startTest("test.html", function(test) {12 harness.mojom.TestInterfacePtr.newRemote(test, function(testInterface) {13 testInterface.testMethod();14 });15 });16};
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!!