maps_test.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. goog.require('proto.jspb.test.MapValueEnum');
  33. goog.require('proto.jspb.test.MapValueMessage');
  34. goog.require('proto.jspb.test.MapValueMessageNoBinary');
  35. goog.require('proto.jspb.test.TestMapFields');
  36. goog.require('proto.jspb.test.TestMapFieldsNoBinary');
  37. /**
  38. * Helper: check that the given map has exactly this set of (sorted) entries.
  39. * @param {!jspb.Map} map
  40. * @param {!Array<!Array<?>>} entries
  41. */
  42. function checkMapEquals(map, entries) {
  43. var arr = map.toArray();
  44. assertEquals(arr.length, entries.length);
  45. for (var i = 0; i < arr.length; i++) {
  46. assertElementsEquals(arr[i], entries[i]);
  47. }
  48. }
  49. /**
  50. * Converts an ES6 iterator to an array.
  51. * @template T
  52. * @param {!Iterator<T>} iter an iterator
  53. * @return {!Array<T>}
  54. */
  55. function toArray(iter) {
  56. var arr = [];
  57. while (true) {
  58. var val = iter.next();
  59. if (val.done) {
  60. break;
  61. }
  62. arr.push(val.value);
  63. }
  64. return arr;
  65. }
  66. /**
  67. * Helper: generate test methods for this TestMapFields class.
  68. * @param {?} msgInfo
  69. * @param {?} submessageCtor
  70. * @param {!string} suffix
  71. */
  72. function makeTests(msgInfo, submessageCtor, suffix) {
  73. /**
  74. * Helper: fill all maps on a TestMapFields.
  75. * @param {?} msg
  76. */
  77. var fillMapFields = function(msg) {
  78. msg.getMapStringStringMap().set('asdf', 'jkl;').set('key 2', 'hello world');
  79. msg.getMapStringInt32Map().set('a', 1).set('b', -2);
  80. msg.getMapStringInt64Map().set('c', 0x100000000).set('d', 0x200000000);
  81. msg.getMapStringBoolMap().set('e', true).set('f', false);
  82. msg.getMapStringDoubleMap().set('g', 3.14159).set('h', 2.71828);
  83. msg.getMapStringEnumMap()
  84. .set('i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR)
  85. .set('j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ);
  86. msg.getMapStringMsgMap()
  87. .set('k', new submessageCtor())
  88. .set('l', new submessageCtor());
  89. msg.getMapStringMsgMap().get('k').setFoo(42);
  90. msg.getMapStringMsgMap().get('l').setFoo(84);
  91. msg.getMapInt32StringMap().set(-1, 'a').set(42, 'b');
  92. msg.getMapInt64StringMap().set(0x123456789abc, 'c').set(0xcba987654321, 'd');
  93. msg.getMapBoolStringMap().set(false, 'e').set(true, 'f');
  94. };
  95. /**
  96. * Helper: check all maps on a TestMapFields.
  97. * @param {?} msg
  98. */
  99. var checkMapFields = function(msg) {
  100. checkMapEquals(msg.getMapStringStringMap(), [
  101. ['asdf', 'jkl;'],
  102. ['key 2', 'hello world']
  103. ]);
  104. checkMapEquals(msg.getMapStringInt32Map(), [
  105. ['a', 1],
  106. ['b', -2]
  107. ]);
  108. checkMapEquals(msg.getMapStringInt64Map(), [
  109. ['c', 0x100000000],
  110. ['d', 0x200000000]
  111. ]);
  112. checkMapEquals(msg.getMapStringBoolMap(), [
  113. ['e', true],
  114. ['f', false]
  115. ]);
  116. checkMapEquals(msg.getMapStringDoubleMap(), [
  117. ['g', 3.14159],
  118. ['h', 2.71828]
  119. ]);
  120. checkMapEquals(msg.getMapStringEnumMap(), [
  121. ['i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR],
  122. ['j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ]
  123. ]);
  124. checkMapEquals(msg.getMapInt32StringMap(), [
  125. [-1, 'a'],
  126. [42, 'b']
  127. ]);
  128. checkMapEquals(msg.getMapInt64StringMap(), [
  129. [0x123456789abc, 'c'],
  130. [0xcba987654321, 'd']
  131. ]);
  132. checkMapEquals(msg.getMapBoolStringMap(), [
  133. [false, 'e'],
  134. [true, 'f']
  135. ]);
  136. assertEquals(msg.getMapStringMsgMap().getLength(), 2);
  137. assertEquals(msg.getMapStringMsgMap().get('k').getFoo(), 42);
  138. assertEquals(msg.getMapStringMsgMap().get('l').getFoo(), 84);
  139. var entries = toArray(msg.getMapStringMsgMap().entries());
  140. assertEquals(entries.length, 2);
  141. entries.forEach(function(entry) {
  142. var key = entry[0];
  143. var val = entry[1];
  144. assert(val === msg.getMapStringMsgMap().get(key));
  145. });
  146. msg.getMapStringMsgMap().forEach(function(val, key) {
  147. assert(val === msg.getMapStringMsgMap().get(key));
  148. });
  149. };
  150. it('testMapStringStringField' + suffix, function() {
  151. var msg = new msgInfo.constructor();
  152. assertEquals(msg.getMapStringStringMap().getLength(), 0);
  153. assertEquals(msg.getMapStringInt32Map().getLength(), 0);
  154. assertEquals(msg.getMapStringInt64Map().getLength(), 0);
  155. assertEquals(msg.getMapStringBoolMap().getLength(), 0);
  156. assertEquals(msg.getMapStringDoubleMap().getLength(), 0);
  157. assertEquals(msg.getMapStringEnumMap().getLength(), 0);
  158. assertEquals(msg.getMapStringMsgMap().getLength(), 0);
  159. // Re-create to clear out any internally-cached wrappers, etc.
  160. msg = new msgInfo.constructor();
  161. var m = msg.getMapStringStringMap();
  162. assertEquals(m.has('asdf'), false);
  163. assertEquals(m.get('asdf'), undefined);
  164. m.set('asdf', 'hello world');
  165. assertEquals(m.has('asdf'), true);
  166. assertEquals(m.get('asdf'), 'hello world');
  167. m.set('jkl;', 'key 2');
  168. assertEquals(m.has('jkl;'), true);
  169. assertEquals(m.get('jkl;'), 'key 2');
  170. assertEquals(m.getLength(), 2);
  171. var it = m.entries();
  172. assertElementsEquals(it.next().value, ['asdf', 'hello world']);
  173. assertElementsEquals(it.next().value, ['jkl;', 'key 2']);
  174. assertEquals(it.next().done, true);
  175. checkMapEquals(m, [
  176. ['asdf', 'hello world'],
  177. ['jkl;', 'key 2']
  178. ]);
  179. m.del('jkl;');
  180. assertEquals(m.has('jkl;'), false);
  181. assertEquals(m.get('jkl;'), undefined);
  182. assertEquals(m.getLength(), 1);
  183. it = m.keys();
  184. assertEquals(it.next().value, 'asdf');
  185. assertEquals(it.next().done, true);
  186. it = m.values();
  187. assertEquals(it.next().value, 'hello world');
  188. assertEquals(it.next().done, true);
  189. var count = 0;
  190. m.forEach(function(value, key, map) {
  191. assertEquals(map, m);
  192. assertEquals(key, 'asdf');
  193. assertEquals(value, 'hello world');
  194. count++;
  195. });
  196. assertEquals(count, 1);
  197. m.clear();
  198. assertEquals(m.getLength(), 0);
  199. });
  200. /**
  201. * Tests operations on maps with all key and value types.
  202. */
  203. it('testAllMapTypes' + suffix, function() {
  204. var msg = new msgInfo.constructor();
  205. fillMapFields(msg);
  206. checkMapFields(msg);
  207. });
  208. if (msgInfo.deserializeBinary) {
  209. /**
  210. * Tests serialization and deserialization in binary format.
  211. */
  212. it('testBinaryFormat' + suffix, function() {
  213. if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(10)) {
  214. // IE8/9 currently doesn't support binary format because they lack
  215. // TypedArray.
  216. return;
  217. }
  218. // Check that the format is correct.
  219. var msg = new msgInfo.constructor();
  220. msg.getMapStringStringMap().set('A', 'a');
  221. var serialized = msg.serializeBinary();
  222. var expectedSerialized = [
  223. 0x0a, 0x6, // field 1 (map_string_string), delimited, length 6
  224. 0x0a, 0x1, // field 1 in submessage (key), delimited, length 1
  225. 0x41, // ASCII 'A'
  226. 0x12, 0x1, // field 2 in submessage (value), delimited, length 1
  227. 0x61 // ASCII 'a'
  228. ];
  229. assertEquals(serialized.length, expectedSerialized.length);
  230. for (var i = 0; i < serialized.length; i++) {
  231. assertEquals(serialized[i], expectedSerialized[i]);
  232. }
  233. // Check that all map fields successfully round-trip.
  234. msg = new msgInfo.constructor();
  235. fillMapFields(msg);
  236. serialized = msg.serializeBinary();
  237. var decoded = msgInfo.deserializeBinary(serialized);
  238. checkMapFields(decoded);
  239. });
  240. }
  241. /**
  242. * Tests serialization and deserialization in JSPB format.
  243. */
  244. it('testJSPBFormat' + suffix, function() {
  245. var msg = new msgInfo.constructor();
  246. fillMapFields(msg);
  247. var serialized = msg.serialize();
  248. var decoded = msgInfo.deserialize(serialized);
  249. checkMapFields(decoded);
  250. });
  251. /**
  252. * Tests serialization and deserialization in JSPB format, when there is
  253. * a submessage that also contains map entries. This tests recursive
  254. * sync.
  255. */
  256. it('testJSPBFormatNested' + suffix, function() {
  257. var submsg = new msgInfo.constructor();
  258. var mapValue = new msgInfo.constructor();
  259. var msg = new msgInfo.constructor();
  260. msg.getMapStringTestmapfieldsMap().set('test', mapValue);
  261. msg.setTestMapFields(submsg);
  262. fillMapFields(submsg);
  263. fillMapFields(msg);
  264. fillMapFields(mapValue);
  265. var serialized = msg.serialize();
  266. var decoded = msgInfo.deserialize(serialized);
  267. checkMapFields(decoded);
  268. var decodedSubmsg = decoded.getTestMapFields();
  269. assertNotNull(decodedSubmsg);
  270. checkMapFields(decodedSubmsg);
  271. var decodedMapValue = decoded.getMapStringTestmapfieldsMap().get('test');
  272. assertNotNull(decodedMapValue);
  273. checkMapFields(decodedMapValue);
  274. });
  275. /**
  276. * Tests toObject()/fromObject().
  277. */
  278. it('testToFromObject' + suffix, function() {
  279. var msg = new msgInfo.constructor();
  280. fillMapFields(msg);
  281. var obj = msg.toObject();
  282. var decoded = msgInfo.fromObject(obj);
  283. checkMapFields(decoded);
  284. obj = msgInfo.deserialize(msg.serialize()).toObject();
  285. decoded = msgInfo.fromObject(obj);
  286. checkMapFields(decoded);
  287. });
  288. /**
  289. * Exercises the lazy map<->underlying array sync.
  290. */
  291. it('testLazyMapSync' + suffix, function() {
  292. // Start with a JSPB array containing a few map entries.
  293. var entries = [
  294. ['a', 'entry 1'],
  295. ['c', 'entry 2'],
  296. ['b', 'entry 3']
  297. ];
  298. var msg = new msgInfo.constructor([entries]);
  299. assertEquals(entries.length, 3);
  300. assertEquals(entries[0][0], 'a');
  301. assertEquals(entries[1][0], 'c');
  302. assertEquals(entries[2][0], 'b');
  303. msg.getMapStringStringMap().del('a');
  304. assertEquals(entries.length, 3); // not yet sync'd
  305. msg.toArray(); // force a sync
  306. assertEquals(entries.length, 2);
  307. assertEquals(entries[0][0], 'b'); // now in sorted order
  308. assertEquals(entries[1][0], 'c');
  309. var a = msg.toArray();
  310. assertEquals(a[0], entries); // retains original reference
  311. });
  312. }
  313. describe('mapsTest', function() {
  314. makeTests({
  315. constructor: proto.jspb.test.TestMapFields,
  316. fromObject: proto.jspb.test.TestMapFields.fromObject,
  317. deserialize: proto.jspb.test.TestMapFields.deserialize,
  318. deserializeBinary: proto.jspb.test.TestMapFields.deserializeBinary
  319. }, proto.jspb.test.MapValueMessage, "_Binary");
  320. makeTests({
  321. constructor: proto.jspb.test.TestMapFieldsNoBinary,
  322. fromObject: proto.jspb.test.TestMapFieldsNoBinary.fromObject,
  323. deserialize: proto.jspb.test.TestMapFieldsNoBinary.deserialize,
  324. deserializeBinary: null
  325. }, proto.jspb.test.MapValueMessageNoBinary, "_NoBinary");
  326. });