Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(118)

Side by Side Diff: third_party/WebKit/LayoutTests/nfc/resources/nfc-helpers.js

Issue 1759373003: [webnfc] Implement nfc.watch in blink nfc module. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@implement_nfc_push_in_android
Patch Set: Rebased to master and improved tests Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 'use strict'; 1 'use strict';
2 2
3 var test_text_data = 'Test text data.'; 3 var test_text_data = 'Test text data.';
4 var test_text_byte_array = new TextEncoder('utf-8').encode(test_text_data); 4 var test_text_byte_array = new TextEncoder('utf-8').encode(test_text_data);
5 var test_number_data = 42; 5 var test_number_data = 42;
6 var test_json_data = {level: 1, score: 100, label: 'Game'}; 6 var test_json_data = {level: 1, score: 100, label: 'Game'};
7 var test_url_data = 'https://w3c.github.io/web-nfc/'; 7 var test_url_data = 'https://w3c.github.io/web-nfc/';
8 var test_message_origin = 'https://127.0.0.1:8443'; 8 var test_message_origin = 'https://127.0.0.1:8443';
9 var test_buffer_data = new ArrayBuffer(test_text_byte_array.length); 9 var test_buffer_data = new ArrayBuffer(test_text_byte_array.length);
10 var test_buffer_view = new Uint8Array(test_buffer_data).set(test_text_byte_array ); 10 var test_buffer_view = new Uint8Array(test_buffer_data).set(test_text_byte_array );
11 11
12 var NFCHWStatus = {}; 12 var NFCHWStatus = {};
13 NFCHWStatus.ENABLED = 1; 13 NFCHWStatus.ENABLED = 1;
14 NFCHWStatus.NOT_SUPPORTED = NFCHWStatus.ENABLED + 1; 14 NFCHWStatus.NOT_SUPPORTED = NFCHWStatus.ENABLED + 1;
15 NFCHWStatus.DISABLED = NFCHWStatus.NOT_SUPPORTED + 1; 15 NFCHWStatus.DISABLED = NFCHWStatus.NOT_SUPPORTED + 1;
16 16
17 function noop() {}
18
19 function assertRejectsWithError(promise, name) {
20 return promise.then(() => {
21 assert_unreached('expected promise to reject with ' + name);
22 }, error => {
23 assert_equals(error.name, name);
24 });
25 }
26
17 function createMessage(records) { 27 function createMessage(records) {
18 if (records !== undefined) { 28 if (records !== undefined) {
19 let message = {} 29 let message = {}
20 message.data = records; 30 message.data = records;
21 return message; 31 return message;
22 } 32 }
23 } 33 }
24 34
25 function createRecord(recordType, mediaType, data) { 35 function createRecord(recordType, mediaType, data) {
26 let record = {}; 36 let record = {};
27 if (recordType !== undefined) 37 if (recordType !== undefined)
28 record.recordType = recordType; 38 record.recordType = recordType;
29 if (mediaType !== undefined) 39 if (mediaType !== undefined)
30 record.mediaType = mediaType; 40 record.mediaType = mediaType;
31 if (data !== undefined) 41 if (data !== undefined)
32 record.data = data; 42 record.data = data;
33 return record; 43 return record;
34 } 44 }
35 45
36 function createNFCPushOptions(target, timeout, ignoreRead) { 46 function createNFCPushOptions(target, timeout, ignoreRead) {
37 return { target, timeout, ignoreRead }; 47 return { target, timeout, ignoreRead };
38 } 48 }
39 49
50 function createNFCWatchOptions(url, recordType, mediaType, mode) {
51 return { url, recordType, mediaType, mode};
52 }
53
40 function createTextRecord(text) { 54 function createTextRecord(text) {
41 return createRecord('text', 'text/plain', text); 55 return createRecord('text', 'text/plain', text);
42 } 56 }
43 57
44 function createJsonRecord(json) { 58 function createJsonRecord(json) {
45 return createRecord('json', 'application/json', json); 59 return createRecord('json', 'application/json', json);
46 } 60 }
47 61
48 function createOpaqueRecord(buffer) { 62 function createOpaqueRecord(buffer) {
49 return createRecord('opaque', 'application/octet-stream', buffer); 63 return createRecord('opaque', 'application/octet-stream', buffer);
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
81 return nfc.NFCPushTarget.ANY; 95 return nfc.NFCPushTarget.ANY;
82 case 'peer': 96 case 'peer':
83 return nfc.NFCPushTarget.PEER; 97 return nfc.NFCPushTarget.PEER;
84 case 'tag': 98 case 'tag':
85 return nfc.NFCPushTarget.TAG; 99 return nfc.NFCPushTarget.TAG;
86 } 100 }
87 101
88 return nfc.NFCPushTarget.ANY; 102 return nfc.NFCPushTarget.ANY;
89 } 103 }
90 104
105 function toMojoNFCWatchMode(mode) {
106 if (mode === 'web-nfc-only')
107 return nfc.NFCWatchMode.WEBNFC_ONLY;
108 return nfc.NFCWatchMode.ANY;
109 }
110
111 // Converts between NFCMessage https://w3c.github.io/web-nfc/#dom-nfcmessage
112 // and mojo::NFCMessage structure, so that nfc.watch function can be tested.
113 function toMojoNFCMessage(message) {
114 let nfcMessage = new nfc.NFCMessage();
115 nfcMessage.url = message.url;
116 nfcMessage.data = [];
117 for (let record of message.data)
118 nfcMessage.data.push(toMojoNFCRecord(record));
119 return nfcMessage;
120 }
121
122 function toMojoNFCRecord(record) {
123 let nfcRecord = new nfc.NFCRecord();
124 nfcRecord.record_type = toMojoNFCRecordType(record.recordType);
125 nfcRecord.media_type = record.mediaType;
126 nfcRecord.data = toByteArray(record.data);
127 return nfcRecord;
128 }
129
91 function toByteArray(data) { 130 function toByteArray(data) {
92 // Convert JS objects to byte array 131 // Convert JS objects to byte array
93 let byteArray; 132 let byteArray;
94 let tmpData = data; 133 let tmpData = data;
95 134
96 if (tmpData instanceof ArrayBuffer) 135 if (tmpData instanceof ArrayBuffer)
97 byteArray = new Uint8Array(tmpData); 136 byteArray = new Uint8Array(tmpData);
98 else if (typeof tmpData === 'object' || typeof tmpData === 'number') 137 else if (typeof tmpData === 'object' || typeof tmpData === 'number')
99 tmpData = JSON.stringify(tmpData); 138 tmpData = JSON.stringify(tmpData);
100 139
(...skipping 17 matching lines...) Expand all
118 provided = createMessage([createTextRecord(providedMessage)]); 157 provided = createMessage([createTextRecord(providedMessage)]);
119 158
120 assert_equals(provided.data.length, receivedMessage.data.length, 159 assert_equals(provided.data.length, receivedMessage.data.length,
121 'NFCMessages must have same number of NFCRecords'); 160 'NFCMessages must have same number of NFCRecords');
122 161
123 // Compare contents of each individual NFCRecord 162 // Compare contents of each individual NFCRecord
124 for (let i = 0; i < provided.data.length; ++i) 163 for (let i = 0; i < provided.data.length; ++i)
125 compareNFCRecords(provided.data[i], receivedMessage.data[i]); 164 compareNFCRecords(provided.data[i], receivedMessage.data[i]);
126 } 165 }
127 166
167 // Used to compare two WebNFC messages, one that is provided to mock NFC
168 // service through triggerWatchCallback and another that is received by
169 // callback that is provided to navigator.nfc.watch function.
170 function assertWebNFCMessagesEqual(a, b) {
171 assert_equals(a.url, b.url);
172 assert_equals(a.data.length, b.data.length);
173 for(let i in a.data) {
174 let recordA = a.data[i];
175 let recordB = b.data[i];
176 assert_equals(recordA.recordType, recordB.recordType);
177 assert_equals(recordA.mediaType, recordB.mediaType);
178
179 if (recordA.data instanceof ArrayBuffer) {
180 assert_array_equals(new Uint8Array(recordA.data),
181 new Uint8Array(recordB.data));
182 } else if (typeof recordA.data === 'object') {
183 assert_object_equals(recordA.data, recordB.data);
184 }
185
186 if (typeof recordA.data === 'number'
187 || typeof recordA.data === 'string') {
188 assert_true(recordA.data == recordB.data);
189 }
190 }
191 }
192
128 // Compares NFCRecords that were provided / received by the mock service. 193 // Compares NFCRecords that were provided / received by the mock service.
129 function compareNFCRecords(providedRecord, receivedRecord) { 194 function compareNFCRecords(providedRecord, receivedRecord) {
130 assert_equals(toMojoNFCRecordType(providedRecord.recordType), 195 assert_equals(toMojoNFCRecordType(providedRecord.recordType),
131 receivedRecord.record_type); 196 receivedRecord.record_type);
132 197
133 // Compare media types without charset. 198 // Compare media types without charset.
134 // Charset should be compared when watch method is implemented, in order 199 // Charset should be compared when watch method is implemented, in order
135 // to check that written and read strings are equal. 200 // to check that written and read strings are equal.
136 assert_equals(providedRecord.mediaType, 201 assert_equals(providedRecord.mediaType,
137 receivedRecord.media_type.substring(0, providedRecord.mediaType.length )); 202 receivedRecord.media_type.substring(0, providedRecord.mediaType.length ));
(...skipping 17 matching lines...) Expand all
155 assert_equals(provided.timeout, received.timeout); 220 assert_equals(provided.timeout, received.timeout);
156 else 221 else
157 assert_equals(received.timeout, Infinity); 222 assert_equals(received.timeout, Infinity);
158 223
159 if (provided.target !== undefined) 224 if (provided.target !== undefined)
160 assert_equals(toMojoNFCPushTarget(provided.target), received.target); 225 assert_equals(toMojoNFCPushTarget(provided.target), received.target);
161 else 226 else
162 assert_equals(received.target, nfc.NFCPushTarget.ANY); 227 assert_equals(received.target, nfc.NFCPushTarget.ANY);
163 } 228 }
164 229
230 // Compares NFCWatchOptions structures that were provided to API and
231 // received by the mock mojo service.
232 function assertNFCWatchOptionsEqual(provided, received) {
233 if (provided.url !== undefined)
234 assert_equals(provided.url, received.url);
235 else
236 assert_equals(received.url, '');
237
238 if (provided.mediaType !== undefined)
239 assert_equals(provided.mediaType, received.media_type);
240 else
241 assert_equals(received.media_type, '');
242
243 if (provided.mode !== undefined)
244 assert_equals(toMojoNFCWatchMode(provided.mode), received.mode);
245 else
246 assert_equals(received.mode, nfc.NFCWatchMode.WEBNFC_ONLY);
247
248 if (provided.recordType !== undefined) {
249 assert_equals(!+received.record_filter, true);
250 assert_equals(toMojoNFCRecordType(provided.recordType),
251 received.record_filter.record_type);
252 }
253 }
254
165 function createNFCError(type) { 255 function createNFCError(type) {
166 return { error: type ? 256 return { error: type ?
167 new nfc.NFCError({ error_type: type }) : null }; 257 new nfc.NFCError({ error_type: type }) : null };
168 } 258 }
169 259
170 class MockNFC { 260 class MockNFC {
171 constructor() { 261 constructor() {
172 this.hw_status_ = NFCHWStatus.ENABLED; 262 this.hw_status_ = NFCHWStatus.ENABLED;
173 this.pushed_message_ = null; 263 this.pushed_message_ = null;
174 this.push_options_ = null; 264 this.push_options_ = null;
175 this.pending_promise_func_ = null; 265 this.pending_promise_func_ = null;
176 this.push_timeout_id_ = null; 266 this.push_timeout_id_ = null;
177 this.push_completed_ = true; 267 this.push_completed_ = true;
268 this.client_ = null;
269 this.watch_id_ = 0;
270 this.watchers_ = [];
178 } 271 }
179 272
180 // NFC.stubClass delegate functions 273 // NFC.stubClass delegate functions
181 push(message, options) { 274 push(message, options) {
182 let error = this.isReady(); 275 let error = this.isReady();
183 if (error) 276 if (error)
184 return Promise.resolve(error); 277 return Promise.resolve(error);
185 278
186 this.pushed_message_ = message; 279 this.pushed_message_ = message;
187 this.push_options_ = options; 280 this.push_options_ = options;
(...skipping 14 matching lines...) Expand all
202 295
203 cancelPush(target) { 296 cancelPush(target) {
204 if (this.push_options_ && ((target === nfc.NFCPushTarget.ANY) || 297 if (this.push_options_ && ((target === nfc.NFCPushTarget.ANY) ||
205 (this.push_options_.target === target))) { 298 (this.push_options_.target === target))) {
206 this.cancelPendingPushOperation(); 299 this.cancelPendingPushOperation();
207 } 300 }
208 301
209 return Promise.resolve(createNFCError(null)); 302 return Promise.resolve(createNFCError(null));
210 } 303 }
211 304
305 setClient(client) {
306 this.client_ = client;
307 }
308
309 watch(options) {
310 let error = this.isReady();
311 if (error) {
312 error.id = 0;
313 return Promise.resolve(error);
314 }
315
316 let retVal = createNFCError(null);
317 retVal.id = ++this.watch_id_;
318 this.watchers_.push({id: this.watch_id_, options: options});
319 return Promise.resolve(retVal);
320 }
321
322 cancelWatch(id) {
323 let index = this.watchers_.findIndex(value => value.id === id);
324 if (index === -1) {
325 return Promise.resolve(createNFCError(nfc.NFCErrorType.NOT_FOUND));
326 }
327
328 this.watchers_.splice(index, 1);
329 return Promise.resolve(createNFCError(null));
330 }
331
332 cancelAllWatches() {
333 if (this.watchers_.length === 0) {
334 return Promise.resolve(createNFCError(nfc.NFCErrorType.NOT_FOUND));
335 }
336
337 this.watchers_.splice(0, this.watchers_.length);
338 return Promise.resolve(createNFCError(null));
339 }
340
341
212 // Mock utility functions 342 // Mock utility functions
213 bindToPipe(pipe) { 343 bindToPipe(pipe) {
214 this.stub_ = connection.bindHandleToStub( 344 this.stub_ = connection.bindHandleToStub(
215 pipe, nfc.NFC); 345 pipe, nfc.NFC);
216 bindings.StubBindings(this.stub_).delegate = this; 346 bindings.StubBindings(this.stub_).delegate = this;
217 } 347 }
218 348
219 isReady() { 349 isReady() {
220 if (this.hw_status_ === NFCHWStatus.DISABLED) 350 if (this.hw_status_ === NFCHWStatus.DISABLED)
221 return createNFCError(nfc.NFCErrorType.DEVICE_DISABLED); 351 return createNFCError(nfc.NFCErrorType.DEVICE_DISABLED);
222 if (this.hw_status_ === NFCHWStatus.NOT_SUPPORTED) 352 if (this.hw_status_ === NFCHWStatus.NOT_SUPPORTED)
223 return createNFCError(nfc.NFCErrorType.NOT_SUPPORTED); 353 return createNFCError(nfc.NFCErrorType.NOT_SUPPORTED);
224 return null; 354 return null;
225 } 355 }
226 356
227 setHWStatus(status) { 357 setHWStatus(status) {
228 this.hw_status_ = status; 358 this.hw_status_ = status;
229 } 359 }
230 360
231 pushedMessage() { 361 pushedMessage() {
232 return this.pushed_message_; 362 return this.pushed_message_;
233 } 363 }
234 364
235 pushOptions() { 365 pushOptions() {
236 return this.push_options_; 366 return this.push_options_;
237 } 367 }
238 368
369 watchOptions() {
370 assert_not_equals(this.watchers_.length, 0);
371 return this.watchers_[this.watchers_.length - 1].options;
372 }
373
239 setPendingPushCompleted(result) { 374 setPendingPushCompleted(result) {
240 this.push_completed_ = result; 375 this.push_completed_ = result;
241 } 376 }
242 377
243 reset() { 378 reset() {
244 this.hw_status_ = NFCHWStatus.ENABLED; 379 this.hw_status_ = NFCHWStatus.ENABLED;
245 this.push_completed_ = true; 380 this.push_completed_ = true;
381 this.watch_id_ = 0;
382 this.watchers_ = [];
246 this.cancelPendingPushOperation(); 383 this.cancelPendingPushOperation();
247 } 384 }
248 385
249 cancelPendingPushOperation() { 386 cancelPendingPushOperation() {
250 if (this.push_timeout_id_) { 387 if (this.push_timeout_id_) {
251 window.clearTimeout(this.push_timeout_id_); 388 window.clearTimeout(this.push_timeout_id_);
252 } 389 }
253 390
254 if (this.pending_promise_func_) { 391 if (this.pending_promise_func_) {
255 this.pending_promise_func_(createNFCError(nfc.NFCErrorType.OPERATION_C ANCELLED)); 392 this.pending_promise_func_(createNFCError(nfc.NFCErrorType.OPERATION_C ANCELLED));
256 } 393 }
257 394
258 this.pushed_message_ = null; 395 this.pushed_message_ = null;
259 this.push_options_ = null; 396 this.push_options_ = null;
260 this.pending_promise_func_ = null; 397 this.pending_promise_func_ = null;
261 } 398 }
399
400 triggerWatchCallback(id, message) {
401 assert_true(this.client_ !== null);
402 if (this.watchers_.length > 0) {
403 this.client_.onWatch([id], toMojoNFCMessage(message));
404 }
405 }
262 } 406 }
263 407
264 let mockNFC = new MockNFC; 408 let mockNFC = new MockNFC;
265 mojo.frameInterfaces.addInterfaceOverrideForTesting( 409 mojo.frameInterfaces.addInterfaceOverrideForTesting(
266 nfc.NFC.name, 410 nfc.NFC.name,
267 pipe => { 411 pipe => {
268 mockNFC.bindToPipe(pipe); 412 mockNFC.bindToPipe(pipe);
269 }); 413 });
270 414
271 return Promise.resolve({ 415 return Promise.resolve({
272 mockNFC: mockNFC, 416 mockNFC: mockNFC,
273 assertNFCMessagesEqual: assertNFCMessagesEqual, 417 assertNFCMessagesEqual: assertNFCMessagesEqual,
274 assertNFCPushOptionsEqual: assertNFCPushOptionsEqual, 418 assertNFCPushOptionsEqual: assertNFCPushOptionsEqual,
419 assertWebNFCMessagesEqual: assertWebNFCMessagesEqual,
420 assertNFCWatchOptionsEqual: assertNFCWatchOptionsEqual,
275 }); 421 });
276 }); 422 });
277 } 423 }
278 424
279 function nfc_test(func, name, properties) { 425 function nfc_test(func, name, properties) {
280 mojo_test(mojo => nfc_mocks(mojo).then(nfc => { 426 mojo_test(mojo => nfc_mocks(mojo).then(nfc => {
281 let result = Promise.resolve(func(nfc)); 427 let result = Promise.resolve(func(nfc));
282 let cleanUp = () => nfc.mockNFC.reset(); 428 let cleanUp = () => nfc.mockNFC.reset();
283 result.then(cleanUp, cleanUp); 429 result.then(cleanUp, cleanUp);
284 return result; 430 return result;
285 }), name, properties); 431 }), name, properties);
286 } 432 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698