1/*
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
21import { ThriftTest } from "./gen-js/ThriftTest_types";
22import "./gen-js/ThriftTest";
23var Int64 = require("node-int64");
24var phantom = require("phantom");
25
26const int64_2_pow_60: typeof Int64 = new Int64('1000000000000000');
27const int64_minus_2_pow_60: typeof Int64 = new Int64('f000000000000000');
28
29 (function() {
30    'use strict';
31
32    // Rudimentary test helper functions
33    // TODO: Return error code based on kind of errors rather than throw
34    var ok = function(t, msg) {
35      if (!t) {
36        console.log('*** FAILED ***');
37        throw new Error(msg);
38      }
39    };
40    var equal = function(a, b) {
41      if (a !== b) {
42        console.log('*** FAILED ***');
43        throw new Error();
44      }
45    };
46    var test = function(name, f) {
47      console.log('TEST : ' + name);
48      f();
49      console.log('OK\n');
50    };
51
52    var parseArgs = function(args) {
53      var skips = [
54        '--transport=http',
55        '--protocol=json'
56      ];
57      var opts = {
58        port: '9090'
59        // protocol: 'json',
60      };
61      var keys = {};
62      for (var key in opts) {
63        keys['--' + key + '='] = key;
64      }
65      for (var i in args) {
66        var arg = args[i];
67        if (skips.indexOf(arg) != -1) {
68          continue;
69        }
70        var hit = false;
71        for (var k in keys) {
72          if (arg.slice(0, k.length) === k) {
73            opts[keys[k]] = arg.slice(k.length);
74            hit = true;
75            break;
76          }
77        }
78        if (!hit) {
79          throw new Error('Unknown argument: ' + arg);
80        }
81      }
82      var portAsInt: number = parseInt(opts.port, 10);
83      if (!opts.port || portAsInt < 1 || portAsInt > 65535) {
84        throw new Error('Invalid port number');
85      }
86      return opts;
87    };
88
89    var execute = function() {
90      console.log('### Apache Thrift Javascript standalone test client');
91      console.log('------------------------------------------------------------');
92
93      phantom.page.injectJs('thrift.js');
94      phantom.page.injectJs('gen-js/ThriftTest_types.js');
95      phantom.page.injectJs('gen-js/ThriftTest.js');
96
97      var system = require('system');
98      var opts = parseArgs(system.args.slice(1));
99      var port = opts.port;
100      var transport = new Thrift.Transport('http://localhost:' + port + '/service');
101      var protocol = new Thrift.Protocol(transport);
102      var client = new ThriftTest.ThriftTestClient(protocol);
103
104
105      // TODO: Remove duplicate code with test.js.
106      // all Languages in UTF-8
107      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ú, 粵語";
108
109      function checkRecursively(map1, map2) {
110        if (typeof map1 !== 'function' && typeof map2 !== 'function') {
111          if (!map1 || typeof map1 !== 'object') {
112            equal(map1, map2);
113          } else {
114            for (var key in map1) {
115              checkRecursively(map1[key], map2[key]);
116            }
117          }
118        }
119      }
120
121      test('Void', function() {
122        equal(client.testVoid(), undefined);
123      });
124      test('Binary (String)', function() {
125        var binary: string = '';
126        for (var v = 255; v >= 0; --v) {
127          binary += String.fromCharCode(v);
128        }
129        equal(client.testBinary(binary), binary);
130      });
131      test('Binary (Uint8Array)', function() {
132        var binary: string = '';
133        for (var v = 255; v >= 0; --v) {
134          binary += String.fromCharCode(v);
135        }
136        var arr = new Uint8Array(binary.length);
137        for (var i = 0; i < binary.length; ++i) {
138          arr[i] = binary[i].charCodeAt(0);
139        }
140        const hexEncodedString = Array.from(arr, function(byte) {
141            return String.fromCharCode(byte);
142        }).join('')
143        equal(client.testBinary(hexEncodedString), binary);
144      });
145      test('String', function() {
146        equal(client.testString(''), '');
147        equal(client.testString(stringTest), stringTest);
148
149        var specialCharacters = 'quote: \" backslash:' +
150          ' forwardslash-escaped: \/ ' +
151            ' backspace: \b formfeed: \f newline: \n return: \r tab: ' +
152              ' now-all-of-them-together: "\\\/\b\n\r\t' +
153                ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><';
154                equal(client.testString(specialCharacters), specialCharacters);
155      });
156      test('Double', function() {
157        equal(client.testDouble(0), 0);
158        equal(client.testDouble(-1), -1);
159        equal(client.testDouble(3.14), 3.14);
160        equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60));
161      });
162      test('Bool', function() {
163        equal(client.testBool(true), true);
164        equal(client.testBool(false), false);
165      });
166      test('I8', function() {
167        equal(client.testByte(0), 0);
168        equal(client.testByte(0x01), 0x01);
169      });
170      test('I32', function() {
171        equal(client.testI32(0), 0);
172        equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30));
173        equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30));
174      });
175      test('I64', function() {
176        equal(client.testI64(new Int64(0)), 0);
177        equal(client.testI64(int64_2_pow_60), Math.pow(2, 52));
178        equal(client.testI64(int64_minus_2_pow_60), -Math.pow(2, 52));
179      });
180
181      test('Struct', function() {
182        var structTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct();
183        structTestInput.string_thing = 'worked';
184        structTestInput.byte_thing = 0x01;
185        structTestInput.i32_thing = Math.pow(2, 30);
186        structTestInput.i64_thing = int64_2_pow_60;
187
188        var structTestOutput: ThriftTest.Xtruct = client.testStruct(structTestInput);
189
190        equal(structTestOutput.string_thing, structTestInput.string_thing);
191        equal(structTestOutput.byte_thing, structTestInput.byte_thing);
192        equal(structTestOutput.i32_thing, structTestInput.i32_thing);
193        equal(structTestOutput.i64_thing, structTestInput.i64_thing);
194
195        equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput));
196      });
197
198      test('Nest', function() {
199        var xtrTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct();
200        xtrTestInput.string_thing = 'worked';
201        xtrTestInput.byte_thing = 0x01;
202        xtrTestInput.i32_thing = Math.pow(2, 30);
203        xtrTestInput.i64_thing = int64_2_pow_60;
204
205        var nestTestInput: ThriftTest.Xtruct2 = new ThriftTest.Xtruct2();
206        nestTestInput.byte_thing = 0x02;
207        nestTestInput.struct_thing = xtrTestInput;
208        nestTestInput.i32_thing = Math.pow(2, 15);
209
210        var nestTestOutput = client.testNest(nestTestInput);
211
212        equal(nestTestOutput.byte_thing, nestTestInput.byte_thing);
213        equal(nestTestOutput.struct_thing.string_thing, nestTestInput.struct_thing.string_thing);
214        equal(nestTestOutput.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing);
215        equal(nestTestOutput.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing);
216        equal(nestTestOutput.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing);
217        equal(nestTestOutput.i32_thing, nestTestInput.i32_thing);
218
219        equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput));
220      });
221
222      test('Map', function() {
223        var mapTestInput: {[k: number]: number;} = {7: 77, 8: 88, 9: 99};
224
225        var mapTestOutput: {[k: number]: number;} = client.testMap(mapTestInput);
226
227        for (var key in mapTestOutput) {
228          equal(mapTestOutput[key], mapTestInput[key]);
229        }
230      });
231
232      test('StringMap', function() {
233        var mapTestInput: {[k: string]: string;} = {
234          'a': '123', 'a b': 'with spaces ', 'same': 'same', '0': 'numeric key',
235          'longValue': stringTest, stringTest: 'long key'
236        };
237
238        var mapTestOutput: {[k: string]: string;} = client.testStringMap(mapTestInput);
239
240        for (var key in mapTestOutput) {
241          equal(mapTestOutput[key], mapTestInput[key]);
242        }
243      });
244
245      test('Set', function() {
246        var setTestInput: number[] = [1, 2, 3];
247        ok(client.testSet(setTestInput), setTestInput);
248      });
249
250      test('List', function() {
251        var listTestInput: number[] = [1, 2, 3];
252        ok(client.testList(listTestInput), listTestInput);
253      });
254
255      test('Enum', function() {
256        equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE);
257      });
258
259      test('TypeDef', function() {
260        equal(client.testTypedef(new Int64(69)), 69);
261      });
262
263      test('MapMap', function() {
264        var mapMapTestExpectedResult: {[K: number]: {[k: number]: number}} = {
265          '4': {'1': 1, '2': 2, '3': 3, '4': 4},
266          '-4': {'-4': -4, '-3': -3, '-2': -2, '-1': -1}
267        };
268
269        var mapMapTestOutput = client.testMapMap(1);
270
271
272        for (var key in mapMapTestOutput) {
273          for (var key2 in mapMapTestOutput[key]) {
274            equal(mapMapTestOutput[key][key2], mapMapTestExpectedResult[key][key2]);
275          }
276        }
277
278        checkRecursively(mapMapTestOutput, mapMapTestExpectedResult);
279      });
280
281      test('Xception', function() {
282        try {
283          client.testException('Xception');
284          ok(false, "expected an exception but there was no exception");
285        } catch (e) {
286          equal(e.errorCode, 1001);
287          equal(e.message, 'Xception');
288        }
289      });
290
291      test('no Exception', function() {
292        try {
293          client.testException('no Exception');
294        } catch (e) {
295          ok(false, "expected no exception but here was an exception");
296        }
297      });
298
299      test('TException', function() {
300        try {
301          client.testException('TException');
302          ok(false, "expected an exception but there was no exception");
303        } catch (e) {
304          ok(ok, "succesfully got exception");
305        }
306      });
307
308      const crazy: ThriftTest.Insanity = {
309        'userMap': { '5': new Int64(5), '8': new Int64(8) },
310        'xtructs': [{
311            'string_thing': 'Goodbye4',
312            'byte_thing': 4,
313            'i32_thing': 4,
314            'i64_thing': new Int64(4)
315        },
316        {
317            'string_thing': 'Hello2',
318            'byte_thing': 2,
319            'i32_thing': 2,
320            'i64_thing': new Int64(2)
321        }]
322    };
323      test('Insanity', function() {
324        const insanity: {[k: number]: (ThriftTest.Insanity | {[k:number]: ThriftTest.Insanity})} = {
325            '1': {
326                '2': crazy,
327                '3': crazy
328            },
329            '2': { '6': new ThriftTest.Insanity() }
330        };
331        var res = client.testInsanity(new ThriftTest.Insanity(crazy));
332        ok(res, JSON.stringify(res));
333        ok(insanity, JSON.stringify(insanity));
334
335        checkRecursively(res, insanity);
336      });
337
338      console.log('------------------------------------------------------------');
339      console.log('### All tests succeeded.');
340      return 0;
341    };
342
343    try {
344      var ret = execute();
345      phantom.exit(ret);
346    } catch (err) {
347      // Catch all and exit to avoid hang.
348      console.error(err);
349      phantom.exit(1);
350    }
351  })();
352