blob: f75b2561456a4db06c76ce20183f4140c5c1d1ee [file] [log] [blame]
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 /* jshint -W100 */
20
21(function() {
22 'use strict';
23
24 // Rudimentary test helper functions
25 // TODO: Return error code based on kind of errors rather than throw
26 var ok = function(t, msg) {
27 if (!t) {
28 console.log('*** FAILED ***');
29 throw new Error(msg);
30 }
31 };
32 var equal = function(a, b) {
33 if (a !== b) {
34 console.log('*** FAILED ***');
35 throw new Error();
36 }
37 };
38 var test = function(name, f) {
39 console.log('TEST : ' + name);
40 f();
41 console.log('OK\n');
42 };
43
44 var parseArgs = function(args) {
45 var skips = [
46 '--transport=http',
47 '--protocol=json',
48 ];
49 var opts = {
50 port: '9090',
51 // protocol: 'json',
52 };
53 var keys = {};
54 for (var key in opts) {
55 keys['--' + key + '='] = key;
56 }
57 for (var i in args) {
58 var arg = args[i];
59 if (skips.indexOf(arg) != -1) {
60 continue;
61 }
62 var hit = false;
63 for (var k in keys) {
64 if (arg.slice(0, k.length) === k) {
65 opts[keys[k]] = arg.slice(k.length);
66 hit = true;
67 break;
68 }
69 }
70 if (!hit) {
71 throw new Error('Unknown argument: ' + arg);
72 }
73 }
74 opts.port = parseInt(opts.port, 10);
75 if (!opts.port || opts.port < 1 || opts.port > 65535) {
76 throw new Error('Invalid port number');
77 }
78 return opts;
79 };
80
81 var execute = function() {
82 console.log('### Apache Thrift Javascript standalone test client');
83 console.log('------------------------------------------------------------');
84
85 phantom.page.injectJs('src/thrift.js');
86 phantom.page.injectJs('test/gen-js/ThriftTest_types.js');
87 phantom.page.injectJs('test/gen-js/ThriftTest.js');
88
89 var system = require('system');
90 var opts = parseArgs(system.args.slice(1));
91 var port = opts.port;
92 var transport = new Thrift.Transport('http://localhost:' + port + '/service');
93 var protocol = new Thrift.Protocol(transport);
94 var client = new ThriftTest.ThriftTestClient(protocol);
95
96
97 // TODO: Remove duplicate code with test.js.
98 // all Languages in UTF-8
99 var stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, Bahasa Melayu, مازِرونی, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, ‪Norsk (nynorsk)‬, ‪Norsk (bokmål)‬, Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語";
100
101 function checkRecursively(map1, map2) {
102 if (typeof map1 !== 'function' && typeof map2 !== 'function') {
103 if (!map1 || typeof map1 !== 'object') {
104 equal(map1, map2);
105 } else {
106 for (var key in map1) {
107 checkRecursively(map1[key], map2[key]);
108 }
109 }
110 }
111 }
112
113 test("Void", function() {
114 equal(client.testVoid(), undefined);
115 });
116 test("Binary (String)", function() {
117 var binary = '';
118 for (var v = 255; v >= 0; --v) {
119 binary += String.fromCharCode(v);
120 }
121 equal(client.testBinary(binary), binary);
122 });
123 test("Binary (Uint8Array)", function() {
124 var binary = '';
125 for (var v = 255; v >= 0; --v) {
126 binary += String.fromCharCode(v);
127 }
128 var arr = new Uint8Array(binary.length);
129 for (var i = 0; i < binary.length; ++i) {
130 arr[i] = binary[i].charCodeAt();
131 }
132 equal(client.testBinary(arr), binary);
133 });
134 test("String", function() {
135 equal(client.testString(''), '');
136 equal(client.testString(stringTest), stringTest);
137
138 var specialCharacters = 'quote: \" backslash:' +
139 ' forwardslash-escaped: \/ ' +
140 ' backspace: \b formfeed: \f newline: \n return: \r tab: ' +
141 ' now-all-of-them-together: "\\\/\b\n\r\t' +
142 ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><';
143 equal(client.testString(specialCharacters),specialCharacters);
144 });
145 test("Double", function() {
146 equal(client.testDouble(0), 0);
147 equal(client.testDouble(-1), -1);
148 equal(client.testDouble(3.14), 3.14);
149 equal(client.testDouble(Math.pow(2,60)), Math.pow(2,60));
150 });
151 test("Bool", function() {
152 equal(client.testBool(true), true);
153 equal(client.testBool(false), false);
154 });
155 test("I8", function() {
156 equal(client.testByte(0), 0);
157 equal(client.testByte(0x01), 0x01);
158 });
159 test("I32", function() {
160 equal(client.testI32(0), 0);
161 equal(client.testI32(Math.pow(2,30)), Math.pow(2,30));
162 equal(client.testI32(-Math.pow(2,30)), -Math.pow(2,30));
163 });
164 test("I64", function() {
165 equal(client.testI64(0), 0);
166 //This is usually 2^60 but JS cannot represent anything over 2^52 accurately
167 equal(client.testI64(Math.pow(2,52)), Math.pow(2,52));
168 equal(client.testI64(-Math.pow(2,52)), -Math.pow(2,52));
169 });
170
171 test("Struct", function() {
172 var structTestInput = new ThriftTest.Xtruct();
173 structTestInput.string_thing = 'worked';
174 structTestInput.byte_thing = 0x01;
175 structTestInput.i32_thing = Math.pow(2,30);
176 //This is usually 2^60 but JS cannot represent anything over 2^52 accurately
177 structTestInput.i64_thing = Math.pow(2,52);
178
179 var structTestOutput = client.testStruct(structTestInput);
180
181 equal(structTestOutput.string_thing, structTestInput.string_thing);
182 equal(structTestOutput.byte_thing, structTestInput.byte_thing);
183 equal(structTestOutput.i32_thing, structTestInput.i32_thing);
184 equal(structTestOutput.i64_thing, structTestInput.i64_thing);
185
186 equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput));
187 });
188
189 test("Nest", function() {
190 var xtrTestInput = new ThriftTest.Xtruct();
191 xtrTestInput.string_thing = 'worked';
192 xtrTestInput.byte_thing = 0x01;
193 xtrTestInput.i32_thing = Math.pow(2,30);
194 //This is usually 2^60 but JS cannot represent anything over 2^52 accurately
195 xtrTestInput.i64_thing = Math.pow(2,52);
196
197 var nestTestInput = new ThriftTest.Xtruct2();
198 nestTestInput.byte_thing = 0x02;
199 nestTestInput.struct_thing = xtrTestInput;
200 nestTestInput.i32_thing = Math.pow(2,15);
201
202 var nestTestOutput = client.testNest(nestTestInput);
203
204 equal(nestTestOutput.byte_thing, nestTestInput.byte_thing);
205 equal(nestTestOutput.struct_thing.string_thing, nestTestInput.struct_thing.string_thing);
206 equal(nestTestOutput.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing);
207 equal(nestTestOutput.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing);
208 equal(nestTestOutput.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing);
209 equal(nestTestOutput.i32_thing, nestTestInput.i32_thing);
210
211 equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput));
212 });
213
214 test("Map", function() {
215 var mapTestInput = {7:77, 8:88, 9:99};
216
217 var mapTestOutput = client.testMap(mapTestInput);
218
219 for (var key in mapTestOutput) {
220 equal(mapTestOutput[key], mapTestInput[key]);
221 }
222 });
223
224 test("StringMap", function() {
225 var mapTestInput = {
226 "a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key",
227 "longValue":stringTest, stringTest:"long key"
228 };
229
230 var mapTestOutput = client.testStringMap(mapTestInput);
231
232 for (var key in mapTestOutput) {
233 equal(mapTestOutput[key], mapTestInput[key]);
234 }
235 });
236
237 test("Set", function() {
238 var setTestInput = [1,2,3];
239 ok(client.testSet(setTestInput), setTestInput);
240 });
241
242 test("List", function() {
243 var listTestInput = [1,2,3];
244 ok(client.testList(listTestInput), listTestInput);
245 });
246
247 test("Enum", function() {
248 equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE);
249 });
250
251 test("TypeDef", function() {
252 equal(client.testTypedef(69), 69);
253 });
254
255 test("Skip", function() {
256 var structTestInput = new ThriftTest.Xtruct();
257 var modifiedClient = new ThriftTest.ThriftTestClient(protocol);
258
259 modifiedClient.recv_testStruct = function() {
260 var input = modifiedClient.input;
261 var xtruct3 = new ThriftTest.Xtruct3();
262
263 input.readMessageBegin();
264 input.readStructBegin();
265
266 // read Xtruct data with Xtruct3
267 input.readFieldBegin();
268 xtruct3.read(input);
269 input.readFieldEnd();
270 // read Thrift.Type.STOP message
271 input.readFieldBegin();
272 input.readFieldEnd();
273
274 input.readStructEnd();
275 input.readMessageEnd();
276
277 return xtruct3;
278 };
279
280 structTestInput.string_thing = 'worked';
281 structTestInput.byte_thing = 0x01;
282 structTestInput.i32_thing = Math.pow(2,30);
283 structTestInput.i64_thing = Math.pow(2,52);
284
285 var structTestOutput = modifiedClient.testStruct(structTestInput);
286
287 equal(structTestOutput instanceof ThriftTest.Xtruct3, true);
288 equal(structTestOutput.string_thing, structTestInput.string_thing);
289 equal(structTestOutput.changed, null);
290 equal(structTestOutput.i32_thing, structTestInput.i32_thing);
291 equal(structTestOutput.i64_thing, structTestInput.i64_thing);
292 });
293
294 test("MapMap", function() {
295 var mapMapTestExpectedResult = {
296 "4":{"1":1,"2":2,"3":3,"4":4},
297 "-4":{"-4":-4, "-3":-3, "-2":-2, "-1":-1}
298 };
299
300 var mapMapTestOutput = client.testMapMap(1);
301
302
303 for (var key in mapMapTestOutput) {
304 for (var key2 in mapMapTestOutput[key]) {
305 equal(mapMapTestOutput[key][key2], mapMapTestExpectedResult[key][key2]);
306 }
307 }
308
309 checkRecursively(mapMapTestOutput, mapMapTestExpectedResult);
310 });
311
312 test("Xception", function() {
313 try {
314 client.testException("Xception");
315 ok(false);
316 } catch (e) {
317 equal(e.errorCode, 1001);
318 equal(e.message, "Xception");
319 }
320 });
321
322 test("no Exception", function() {
323 try {
324 client.testException("no Exception");
325 } catch (e) {
326 ok(false);
327 }
328 });
329
330 test("TException", function() {
331 try {
332 client.testException("TException");
333 ok(false);
334 } catch(e) {
335 ok(ok);
336 }
337 });
338
339 var crazy = {
340 "userMap":{ "5":5, "8":8 },
341 "xtructs":[{
342 "string_thing":"Goodbye4",
343 "byte_thing":4,
344 "i32_thing":4,
345 "i64_thing":4
346 },
347 {
348 "string_thing":"Hello2",
349 "byte_thing":2,
350 "i32_thing":2,
351 "i64_thing":2
352 }]
353 };
354 test("Insanity", function() {
355 var insanity = {
356 "1":{
357 "2":crazy,
358 "3":crazy
359 },
360 "2":{ "6":{ "userMap":null, "xtructs":null } }
361 };
362 var res = client.testInsanity(new ThriftTest.Insanity(crazy));
363 ok(res, JSON.stringify(res));
364 ok(insanity, JSON.stringify(insanity));
365
366 checkRecursively(res, insanity);
367 });
368
369 console.log('------------------------------------------------------------');
370 console.log('### All tests succeeded.');
371 return 0;
372 };
373
374 try {
375 var ret = execute();
376 phantom.exit(ret);
377 } catch (err) {
378 // Catch all and exit to avoid hang.
379 console.error(err);
380 phantom.exit(1);
381 }
382})();