maps_test.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. // CommonJS-LoadFromFile: test_pb proto.jspb.test
  37. goog.require('proto.jspb.test.MapValueMessageNoBinary');
  38. goog.require('proto.jspb.test.TestMapFieldsNoBinary');
  39. /**
  40. * Helper: check that the given map has exactly this set of (sorted) entries.
  41. * @param {!jspb.Map} map
  42. * @param {!Array<!Array<?>>} entries
  43. */
  44. function checkMapEquals(map, entries) {
  45. var arr = map.toArray();
  46. assertEquals(arr.length, entries.length);
  47. for (var i = 0; i < arr.length; i++) {
  48. assertElementsEquals(arr[i], entries[i]);
  49. }
  50. }
  51. /**
  52. * Converts an ES6 iterator to an array.
  53. * @template T
  54. * @param {!Iterator<T>} iter an iterator
  55. * @return {!Array<T>}
  56. */
  57. function toArray(iter) {
  58. var arr = [];
  59. while (true) {
  60. var val = iter.next();
  61. if (val.done) {
  62. break;
  63. }
  64. arr.push(val.value);
  65. }
  66. return arr;
  67. }
  68. /**
  69. * Helper: generate test methods for this TestMapFields class.
  70. * @param {?} msgInfo
  71. * @param {?} submessageCtor
  72. * @param {!string} suffix
  73. */
  74. function makeTests(msgInfo, submessageCtor, suffix) {
  75. /**
  76. * Helper: fill all maps on a TestMapFields.
  77. * @param {?} msg
  78. */
  79. var fillMapFields = function(msg) {
  80. msg.getMapStringStringMap().set('asdf', 'jkl;').set('key 2', 'hello world');
  81. msg.getMapStringInt32Map().set('a', 1).set('b', -2);
  82. msg.getMapStringInt64Map().set('c', 0x100000000).set('d', 0x200000000);
  83. msg.getMapStringBoolMap().set('e', true).set('f', false);
  84. msg.getMapStringDoubleMap().set('g', 3.14159).set('h', 2.71828);
  85. msg.getMapStringEnumMap()
  86. .set('i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR)
  87. .set('j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ);
  88. msg.getMapStringMsgMap()
  89. .set('k', new submessageCtor())
  90. .set('l', new submessageCtor());
  91. msg.getMapStringMsgMap().get('k').setFoo(42);
  92. msg.getMapStringMsgMap().get('l').setFoo(84);
  93. msg.getMapInt32StringMap().set(-1, 'a').set(42, 'b');
  94. msg.getMapInt64StringMap().set(0x123456789abc, 'c').set(0xcba987654321, 'd');
  95. msg.getMapBoolStringMap().set(false, 'e').set(true, 'f');
  96. };
  97. /**
  98. * Helper: check all maps on a TestMapFields.
  99. * @param {?} msg
  100. */
  101. var checkMapFields = function(msg) {
  102. checkMapEquals(msg.getMapStringStringMap(), [
  103. ['asdf', 'jkl;'],
  104. ['key 2', 'hello world']
  105. ]);
  106. checkMapEquals(msg.getMapStringInt32Map(), [
  107. ['a', 1],
  108. ['b', -2]
  109. ]);
  110. checkMapEquals(msg.getMapStringInt64Map(), [
  111. ['c', 0x100000000],
  112. ['d', 0x200000000]
  113. ]);
  114. checkMapEquals(msg.getMapStringBoolMap(), [
  115. ['e', true],
  116. ['f', false]
  117. ]);
  118. checkMapEquals(msg.getMapStringDoubleMap(), [
  119. ['g', 3.14159],
  120. ['h', 2.71828]
  121. ]);
  122. checkMapEquals(msg.getMapStringEnumMap(), [
  123. ['i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR],
  124. ['j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ]
  125. ]);
  126. checkMapEquals(msg.getMapInt32StringMap(), [
  127. [-1, 'a'],
  128. [42, 'b']
  129. ]);
  130. checkMapEquals(msg.getMapInt64StringMap(), [
  131. [0x123456789abc, 'c'],
  132. [0xcba987654321, 'd']
  133. ]);
  134. checkMapEquals(msg.getMapBoolStringMap(), [
  135. [false, 'e'],
  136. [true, 'f']
  137. ]);
  138. assertEquals(msg.getMapStringMsgMap().getLength(), 2);
  139. assertEquals(msg.getMapStringMsgMap().get('k').getFoo(), 42);
  140. assertEquals(msg.getMapStringMsgMap().get('l').getFoo(), 84);
  141. var entries = toArray(msg.getMapStringMsgMap().entries());
  142. assertEquals(entries.length, 2);
  143. entries.forEach(function(entry) {
  144. var key = entry[0];
  145. var val = entry[1];
  146. assert(val === msg.getMapStringMsgMap().get(key));
  147. });
  148. msg.getMapStringMsgMap().forEach(function(val, key) {
  149. assert(val === msg.getMapStringMsgMap().get(key));
  150. });
  151. };
  152. it('testMapStringStringField' + suffix, function() {
  153. var msg = new msgInfo.constructor();
  154. assertEquals(msg.getMapStringStringMap().getLength(), 0);
  155. assertEquals(msg.getMapStringInt32Map().getLength(), 0);
  156. assertEquals(msg.getMapStringInt64Map().getLength(), 0);
  157. assertEquals(msg.getMapStringBoolMap().getLength(), 0);
  158. assertEquals(msg.getMapStringDoubleMap().getLength(), 0);
  159. assertEquals(msg.getMapStringEnumMap().getLength(), 0);
  160. assertEquals(msg.getMapStringMsgMap().getLength(), 0);
  161. // Re-create to clear out any internally-cached wrappers, etc.
  162. msg = new msgInfo.constructor();
  163. var m = msg.getMapStringStringMap();
  164. assertEquals(m.has('asdf'), false);
  165. assertEquals(m.get('asdf'), undefined);
  166. m.set('asdf', 'hello world');
  167. assertEquals(m.has('asdf'), true);
  168. assertEquals(m.get('asdf'), 'hello world');
  169. m.set('jkl;', 'key 2');
  170. assertEquals(m.has('jkl;'), true);
  171. assertEquals(m.get('jkl;'), 'key 2');
  172. assertEquals(m.getLength(), 2);
  173. var it = m.entries();
  174. assertElementsEquals(it.next().value, ['asdf', 'hello world']);
  175. assertElementsEquals(it.next().value, ['jkl;', 'key 2']);
  176. assertEquals(it.next().done, true);
  177. checkMapEquals(m, [
  178. ['asdf', 'hello world'],
  179. ['jkl;', 'key 2']
  180. ]);
  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. /**
  244. * Exercises the lazy map<->underlying array sync.
  245. */
  246. it('testLazyMapSync' + suffix, function() {
  247. // Start with a JSPB array containing a few map entries.
  248. var entries = [
  249. ['a', 'entry 1'],
  250. ['c', 'entry 2'],
  251. ['b', 'entry 3']
  252. ];
  253. var msg = new msgInfo.constructor([entries]);
  254. assertEquals(entries.length, 3);
  255. assertEquals(entries[0][0], 'a');
  256. assertEquals(entries[1][0], 'c');
  257. assertEquals(entries[2][0], 'b');
  258. msg.getMapStringStringMap().del('a');
  259. assertEquals(entries.length, 3); // not yet sync'd
  260. msg.toArray(); // force a sync
  261. assertEquals(entries.length, 2);
  262. assertEquals(entries[0][0], 'b'); // now in sorted order
  263. assertEquals(entries[1][0], 'c');
  264. var a = msg.toArray();
  265. assertEquals(a[0], entries); // retains original reference
  266. });
  267. }
  268. describe('mapsTest', function() {
  269. makeTests({
  270. constructor: proto.jspb.test.TestMapFields,
  271. deserializeBinary: proto.jspb.test.TestMapFields.deserializeBinary
  272. }, proto.jspb.test.MapValueMessage, "_Binary");
  273. makeTests({
  274. constructor: proto.jspb.test.TestMapFieldsNoBinary,
  275. deserializeBinary: null
  276. }, proto.jspb.test.MapValueMessageNoBinary, "_NoBinary");
  277. });