maps_test.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. goog.require('goog.testing.asserts');
  31. goog.require('goog.userAgent');
  32. // CommonJS-LoadFromFile: testbinary_pb proto.jspb.test
  33. goog.require('proto.jspb.test.MapValueEnum');
  34. goog.require('proto.jspb.test.MapValueMessage');
  35. goog.require('proto.jspb.test.TestMapFields');
  36. goog.require('proto.jspb.test.TestMapFieldsOptionalKeys');
  37. goog.require('proto.jspb.test.TestMapFieldsOptionalValues');
  38. goog.require('proto.jspb.test.MapEntryOptionalKeysStringKey');
  39. goog.require('proto.jspb.test.MapEntryOptionalKeysInt32Key');
  40. goog.require('proto.jspb.test.MapEntryOptionalKeysInt64Key');
  41. goog.require('proto.jspb.test.MapEntryOptionalKeysBoolKey');
  42. goog.require('proto.jspb.test.MapEntryOptionalValuesStringValue');
  43. goog.require('proto.jspb.test.MapEntryOptionalValuesInt32Value');
  44. goog.require('proto.jspb.test.MapEntryOptionalValuesInt64Value');
  45. goog.require('proto.jspb.test.MapEntryOptionalValuesBoolValue');
  46. goog.require('proto.jspb.test.MapEntryOptionalValuesDoubleValue');
  47. goog.require('proto.jspb.test.MapEntryOptionalValuesEnumValue');
  48. goog.require('proto.jspb.test.MapEntryOptionalValuesMessageValue');
  49. // CommonJS-LoadFromFile: test_pb proto.jspb.test
  50. goog.require('proto.jspb.test.MapValueMessageNoBinary');
  51. goog.require('proto.jspb.test.TestMapFieldsNoBinary');
  52. goog.requireType('jspb.Map');
  53. /**
  54. * Helper: check that the given map has exactly this set of (sorted) entries.
  55. * @param {!jspb.Map} map
  56. * @param {!Array<!Array<?>>} entries
  57. */
  58. function checkMapEquals(map, entries) {
  59. var arr = map.toArray();
  60. assertEquals(arr.length, entries.length);
  61. for (var i = 0; i < arr.length; i++) {
  62. if (Array.isArray(arr[i])) {
  63. assertTrue(Array.isArray(entries[i]));
  64. assertArrayEquals(arr[i], entries[i]);
  65. } else {
  66. assertElementsEquals(arr[i], entries[i]);
  67. }
  68. }
  69. }
  70. /**
  71. * Converts an ES6 iterator to an array.
  72. * @template T
  73. * @param {!Iterator<T>} iter an iterator
  74. * @return {!Array<T>}
  75. */
  76. function toArray(iter) {
  77. var arr = [];
  78. while (true) {
  79. var val = iter.next();
  80. if (val.done) {
  81. break;
  82. }
  83. arr.push(val.value);
  84. }
  85. return arr;
  86. }
  87. /**
  88. * Helper: generate test methods for this TestMapFields class.
  89. * @param {?} msgInfo
  90. * @param {?} submessageCtor
  91. * @param {string} suffix
  92. */
  93. function makeTests(msgInfo, submessageCtor, suffix) {
  94. /**
  95. * Helper: fill all maps on a TestMapFields.
  96. * @param {?} msg
  97. */
  98. var fillMapFields = function(msg) {
  99. msg.getMapStringStringMap().set('asdf', 'jkl;').set('key 2', 'hello world');
  100. msg.getMapStringInt32Map().set('a', 1).set('b', -2);
  101. msg.getMapStringInt64Map().set('c', 0x100000000).set('d', 0x200000000);
  102. msg.getMapStringBoolMap().set('e', true).set('f', false);
  103. msg.getMapStringDoubleMap().set('g', 3.14159).set('h', 2.71828);
  104. msg.getMapStringEnumMap()
  105. .set('i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR)
  106. .set('j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ);
  107. msg.getMapStringMsgMap()
  108. .set('k', new submessageCtor())
  109. .set('l', new submessageCtor());
  110. msg.getMapStringMsgMap().get('k').setFoo(42);
  111. msg.getMapStringMsgMap().get('l').setFoo(84);
  112. msg.getMapInt32StringMap().set(-1, 'a').set(42, 'b');
  113. msg.getMapInt64StringMap()
  114. .set(0x123456789abc, 'c')
  115. .set(0xcba987654321, 'd');
  116. msg.getMapBoolStringMap().set(false, 'e').set(true, 'f');
  117. };
  118. /**
  119. * Helper: check all maps on a TestMapFields.
  120. * @param {?} msg
  121. */
  122. var checkMapFields = function(msg) {
  123. checkMapEquals(
  124. msg.getMapStringStringMap(),
  125. [['asdf', 'jkl;'], ['key 2', 'hello world']]);
  126. checkMapEquals(msg.getMapStringInt32Map(), [['a', 1], ['b', -2]]);
  127. checkMapEquals(
  128. msg.getMapStringInt64Map(), [['c', 0x100000000], ['d', 0x200000000]]);
  129. checkMapEquals(msg.getMapStringBoolMap(), [['e', true], ['f', false]]);
  130. checkMapEquals(
  131. msg.getMapStringDoubleMap(), [['g', 3.14159], ['h', 2.71828]]);
  132. checkMapEquals(msg.getMapStringEnumMap(), [
  133. ['i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR],
  134. ['j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ]
  135. ]);
  136. checkMapEquals(msg.getMapInt32StringMap(), [[-1, 'a'], [42, 'b']]);
  137. checkMapEquals(
  138. msg.getMapInt64StringMap(),
  139. [[0x123456789abc, 'c'], [0xcba987654321, 'd']]);
  140. checkMapEquals(msg.getMapBoolStringMap(), [[false, 'e'], [true, 'f']]);
  141. assertEquals(msg.getMapStringMsgMap().getLength(), 2);
  142. assertEquals(msg.getMapStringMsgMap().get('k').getFoo(), 42);
  143. assertEquals(msg.getMapStringMsgMap().get('l').getFoo(), 84);
  144. var entries = toArray(msg.getMapStringMsgMap().entries());
  145. assertEquals(entries.length, 2);
  146. entries.forEach(function(entry) {
  147. var key = entry[0];
  148. var val = entry[1];
  149. assert(val === msg.getMapStringMsgMap().get(key));
  150. });
  151. msg.getMapStringMsgMap().forEach(function(val, key) {
  152. assert(val === msg.getMapStringMsgMap().get(key));
  153. });
  154. };
  155. it('testMapStringStringField' + suffix, function() {
  156. var msg = new msgInfo.constructor();
  157. assertEquals(msg.getMapStringStringMap().getLength(), 0);
  158. assertEquals(msg.getMapStringInt32Map().getLength(), 0);
  159. assertEquals(msg.getMapStringInt64Map().getLength(), 0);
  160. assertEquals(msg.getMapStringBoolMap().getLength(), 0);
  161. assertEquals(msg.getMapStringDoubleMap().getLength(), 0);
  162. assertEquals(msg.getMapStringEnumMap().getLength(), 0);
  163. assertEquals(msg.getMapStringMsgMap().getLength(), 0);
  164. // Re-create to clear out any internally-cached wrappers, etc.
  165. msg = new msgInfo.constructor();
  166. var m = msg.getMapStringStringMap();
  167. assertEquals(m.has('asdf'), false);
  168. assertEquals(m.get('asdf'), undefined);
  169. m.set('asdf', 'hello world');
  170. assertEquals(m.has('asdf'), true);
  171. assertEquals(m.get('asdf'), 'hello world');
  172. m.set('jkl;', 'key 2');
  173. assertEquals(m.has('jkl;'), true);
  174. assertEquals(m.get('jkl;'), 'key 2');
  175. assertEquals(m.getLength(), 2);
  176. var it = m.entries();
  177. assertElementsEquals(it.next().value, ['asdf', 'hello world']);
  178. assertElementsEquals(it.next().value, ['jkl;', 'key 2']);
  179. assertEquals(it.next().done, true);
  180. checkMapEquals(m, [['asdf', 'hello world'], ['jkl;', 'key 2']]);
  181. m.del('jkl;');
  182. assertEquals(m.has('jkl;'), false);
  183. assertEquals(m.get('jkl;'), undefined);
  184. assertEquals(m.getLength(), 1);
  185. it = m.keys();
  186. assertEquals(it.next().value, 'asdf');
  187. assertEquals(it.next().done, true);
  188. it = m.values();
  189. assertEquals(it.next().value, 'hello world');
  190. assertEquals(it.next().done, true);
  191. var count = 0;
  192. m.forEach(function(value, key, map) {
  193. assertEquals(map, m);
  194. assertEquals(key, 'asdf');
  195. assertEquals(value, 'hello world');
  196. count++;
  197. });
  198. assertEquals(count, 1);
  199. m.clear();
  200. assertEquals(m.getLength(), 0);
  201. });
  202. /**
  203. * Tests operations on maps with all key and value types.
  204. */
  205. it('testAllMapTypes' + suffix, function() {
  206. var msg = new msgInfo.constructor();
  207. fillMapFields(msg);
  208. checkMapFields(msg);
  209. });
  210. if (msgInfo.deserializeBinary) {
  211. /**
  212. * Tests serialization and deserialization in binary format.
  213. */
  214. it('testBinaryFormat' + suffix, function() {
  215. if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(10)) {
  216. // IE8/9 currently doesn't support binary format because they lack
  217. // TypedArray.
  218. return;
  219. }
  220. // Check that the format is correct.
  221. var msg = new msgInfo.constructor();
  222. msg.getMapStringStringMap().set('A', 'a');
  223. var serialized = msg.serializeBinary();
  224. var expectedSerialized = [
  225. 0x0a, 0x6, // field 1 (map_string_string), delimited, length 6
  226. 0x0a, 0x1, // field 1 in submessage (key), delimited, length 1
  227. 0x41, // ASCII 'A'
  228. 0x12, 0x1, // field 2 in submessage (value), delimited, length 1
  229. 0x61 // ASCII 'a'
  230. ];
  231. assertEquals(serialized.length, expectedSerialized.length);
  232. for (var i = 0; i < serialized.length; i++) {
  233. assertEquals(serialized[i], expectedSerialized[i]);
  234. }
  235. // Check that all map fields successfully round-trip.
  236. msg = new msgInfo.constructor();
  237. fillMapFields(msg);
  238. serialized = msg.serializeBinary();
  239. var decoded = msgInfo.deserializeBinary(serialized);
  240. checkMapFields(decoded);
  241. });
  242. /**
  243. * Tests deserialization of undefined map keys go to default values in
  244. * binary format.
  245. */
  246. it('testMapDeserializationForUndefinedKeys', function() {
  247. var testMessageOptionalKeys =
  248. new proto.jspb.test.TestMapFieldsOptionalKeys();
  249. var mapEntryStringKey =
  250. new proto.jspb.test.MapEntryOptionalKeysStringKey();
  251. mapEntryStringKey.setValue('a');
  252. testMessageOptionalKeys.setMapStringString(mapEntryStringKey);
  253. var mapEntryInt32Key = new proto.jspb.test.MapEntryOptionalKeysInt32Key();
  254. mapEntryInt32Key.setValue('b');
  255. testMessageOptionalKeys.setMapInt32String(mapEntryInt32Key);
  256. var mapEntryInt64Key = new proto.jspb.test.MapEntryOptionalKeysInt64Key();
  257. mapEntryInt64Key.setValue('c');
  258. testMessageOptionalKeys.setMapInt64String(mapEntryInt64Key);
  259. var mapEntryBoolKey = new proto.jspb.test.MapEntryOptionalKeysBoolKey();
  260. mapEntryBoolKey.setValue('d');
  261. testMessageOptionalKeys.setMapBoolString(mapEntryBoolKey);
  262. var deserializedMessage =
  263. msgInfo.deserializeBinary(testMessageOptionalKeys.serializeBinary());
  264. checkMapEquals(deserializedMessage.getMapStringStringMap(), [['', 'a']]);
  265. checkMapEquals(deserializedMessage.getMapInt32StringMap(), [[0, 'b']]);
  266. checkMapEquals(deserializedMessage.getMapInt64StringMap(), [[0, 'c']]);
  267. checkMapEquals(deserializedMessage.getMapBoolStringMap(), [[false, 'd']]);
  268. });
  269. /**
  270. * Tests deserialization of undefined map values go to default values in
  271. * binary format.
  272. */
  273. it('testMapDeserializationForUndefinedValues', function() {
  274. var testMessageOptionalValues =
  275. new proto.jspb.test.TestMapFieldsOptionalValues();
  276. var mapEntryStringValue =
  277. new proto.jspb.test.MapEntryOptionalValuesStringValue();
  278. mapEntryStringValue.setKey('a');
  279. testMessageOptionalValues.setMapStringString(mapEntryStringValue);
  280. var mapEntryInt32Value =
  281. new proto.jspb.test.MapEntryOptionalValuesInt32Value();
  282. mapEntryInt32Value.setKey('b');
  283. testMessageOptionalValues.setMapStringInt32(mapEntryInt32Value);
  284. var mapEntryInt64Value =
  285. new proto.jspb.test.MapEntryOptionalValuesInt64Value();
  286. mapEntryInt64Value.setKey('c');
  287. testMessageOptionalValues.setMapStringInt64(mapEntryInt64Value);
  288. var mapEntryBoolValue =
  289. new proto.jspb.test.MapEntryOptionalValuesBoolValue();
  290. mapEntryBoolValue.setKey('d');
  291. testMessageOptionalValues.setMapStringBool(mapEntryBoolValue);
  292. var mapEntryDoubleValue =
  293. new proto.jspb.test.MapEntryOptionalValuesDoubleValue();
  294. mapEntryDoubleValue.setKey('e');
  295. testMessageOptionalValues.setMapStringDouble(mapEntryDoubleValue);
  296. var mapEntryEnumValue =
  297. new proto.jspb.test.MapEntryOptionalValuesEnumValue();
  298. mapEntryEnumValue.setKey('f');
  299. testMessageOptionalValues.setMapStringEnum(mapEntryEnumValue);
  300. var mapEntryMessageValue =
  301. new proto.jspb.test.MapEntryOptionalValuesMessageValue();
  302. mapEntryMessageValue.setKey('g');
  303. testMessageOptionalValues.setMapStringMsg(mapEntryMessageValue);
  304. var deserializedMessage = msgInfo.deserializeBinary(
  305. testMessageOptionalValues.serializeBinary());
  306. checkMapEquals(deserializedMessage.getMapStringStringMap(), [['a', '']]);
  307. checkMapEquals(deserializedMessage.getMapStringInt32Map(), [['b', 0]]);
  308. checkMapEquals(deserializedMessage.getMapStringInt64Map(), [['c', 0]]);
  309. checkMapEquals(deserializedMessage.getMapStringBoolMap(), [['d', false]]);
  310. checkMapEquals(deserializedMessage.getMapStringDoubleMap(), [['e', 0.0]]);
  311. checkMapEquals(deserializedMessage.getMapStringEnumMap(), [['f', 0]]);
  312. checkMapEquals(deserializedMessage.getMapStringMsgMap(), [['g', []]]);
  313. });
  314. }
  315. /**
  316. * Exercises the lazy map<->underlying array sync.
  317. */
  318. it('testLazyMapSync' + suffix, function() {
  319. // Start with a JSPB array containing a few map entries.
  320. var entries = [['a', 'entry 1'], ['c', 'entry 2'], ['b', 'entry 3']];
  321. var msg = new msgInfo.constructor([entries]);
  322. assertEquals(entries.length, 3);
  323. assertEquals(entries[0][0], 'a');
  324. assertEquals(entries[1][0], 'c');
  325. assertEquals(entries[2][0], 'b');
  326. msg.getMapStringStringMap().del('a');
  327. assertEquals(entries.length, 3); // not yet sync'd
  328. msg.toArray(); // force a sync
  329. assertEquals(entries.length, 2);
  330. assertEquals(entries[0][0], 'b'); // now in sorted order
  331. assertEquals(entries[1][0], 'c');
  332. var a = msg.toArray();
  333. assertEquals(a[0], entries); // retains original reference
  334. });
  335. /**
  336. * Returns IteratorIterables for entries(), keys() and values().
  337. */
  338. it('testIteratorIterables' + suffix, function() {
  339. var msg = new msgInfo.constructor();
  340. var m = msg.getMapStringStringMap();
  341. m.set('key1', 'value1');
  342. m.set('key2', 'value2');
  343. var entryIterator = m.entries();
  344. assertElementsEquals(entryIterator.next().value, ['key1', 'value1']);
  345. assertElementsEquals(entryIterator.next().value, ['key2', 'value2']);
  346. assertEquals(entryIterator.next().done, true);
  347. try {
  348. var entryIterable = m.entries()[Symbol.iterator]();
  349. assertElementsEquals(entryIterable.next().value, ['key1', 'value1']);
  350. assertElementsEquals(entryIterable.next().value, ['key2', 'value2']);
  351. assertEquals(entryIterable.next().done, true);
  352. } catch (err) {
  353. // jspb.Map.ArrayIteratorIterable_.prototype[Symbol.iterator] may be
  354. // undefined in some environment.
  355. if (err.name != 'TypeError' && err.name != 'ReferenceError') {
  356. throw err;
  357. }
  358. }
  359. var keyIterator = m.keys();
  360. assertEquals(keyIterator.next().value, 'key1');
  361. assertEquals(keyIterator.next().value, 'key2');
  362. assertEquals(keyIterator.next().done, true);
  363. try {
  364. var keyIterable = m.keys()[Symbol.iterator]();
  365. assertEquals(keyIterable.next().value, 'key1');
  366. assertEquals(keyIterable.next().value, 'key2');
  367. assertEquals(keyIterable.next().done, true);
  368. } catch (err) {
  369. // jspb.Map.ArrayIteratorIterable_.prototype[Symbol.iterator] may be
  370. // undefined in some environment.
  371. if (err.name != 'TypeError' && err.name != 'ReferenceError') {
  372. throw err;
  373. }
  374. }
  375. var valueIterator = m.values();
  376. assertEquals(valueIterator.next().value, 'value1');
  377. assertEquals(valueIterator.next().value, 'value2');
  378. assertEquals(valueIterator.next().done, true);
  379. try {
  380. var valueIterable = m.values()[Symbol.iterator]();
  381. assertEquals(valueIterable.next().value, 'value1');
  382. assertEquals(valueIterable.next().value, 'value2');
  383. assertEquals(valueIterable.next().done, true);
  384. } catch (err) {
  385. // jspb.Map.ArrayIteratorIterable_.prototype[Symbol.iterator] may be
  386. // undefined in some environment.
  387. if (err.name != 'TypeError' && err.name != 'ReferenceError') {
  388. throw err;
  389. }
  390. }
  391. });
  392. }
  393. describe('mapsTest', function() {
  394. makeTests(
  395. {
  396. constructor: proto.jspb.test.TestMapFields,
  397. deserializeBinary: proto.jspb.test.TestMapFields.deserializeBinary
  398. },
  399. proto.jspb.test.MapValueMessage, '_Binary');
  400. makeTests(
  401. {
  402. constructor: proto.jspb.test.TestMapFieldsNoBinary,
  403. deserializeBinary: null
  404. },
  405. proto.jspb.test.MapValueMessageNoBinary, '_NoBinary');
  406. });