Moving from govendor to dep, updated dependencies (#48)

* Moving from govendor to dep.

* Making the pull request template more friendly.

* Fixing akward space in PR template.

* goimports run on whole project using ` goimports -w $(find . -type f -name '*.go' -not -path "./vendor/*" -not -path "./gen-go/*")`

source of command: https://gist.github.com/bgentry/fd1ffef7dbde01857f66
This commit is contained in:
Renan DelValle 2018-01-07 13:13:47 -08:00 committed by GitHub
parent 9631aa3aab
commit 8d445c1c77
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2186 changed files with 400410 additions and 352 deletions

172
vendor/git.apache.org/thrift.git/lib/js/Gruntfile.js generated vendored Normal file
View file

@ -0,0 +1,172 @@
//To build dist/thrift.js, dist/thrift.min.js and doc/*
//run grunt at the command line in this directory.
//Prerequisites:
// Node Setup - nodejs.org
// Grunt Setup - npm install //reads the ./package.json and installs project dependencies
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';'
},
dist: {
src: ['src/**/*.js'],
dest: 'dist/<%= pkg.name %>.js'
}
},
jsdoc : {
dist : {
src: ['src/*.js', './README.md'],
options: {
destination: 'doc'
}
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
files: {
'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
}
}
},
shell: {
InstallThriftJS: {
command: 'mkdir test/build; mkdir test/build/js; cp src/thrift.js test/build/js/thrift.js'
},
InstallThriftNodeJSDep: {
command: 'cd ../..; npm install'
},
ThriftGen: {
command: '../../compiler/cpp/thrift -gen js -gen js:node -o test ../../test/ThriftTest.thrift'
},
ThriftGenJQ: {
command: '../../compiler/cpp/thrift -gen js:jquery -gen js:node -o test ../../test/ThriftTest.thrift'
},
ThriftGenDeepConstructor: {
command: '../../compiler/cpp/thrift -gen js -o test ../../test/JsDeepConstructorTest.thrift'
}
},
external_daemon: {
ThriftTestServer: {
options: {
startCheck: function(stdout, stderr) {
return (/Thrift Server running on port/).test(stdout);
},
nodeSpawnOptions: {
cwd: "test",
env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"}
}
},
cmd: "node",
args: ["server_http.js"]
},
ThriftTestServer_TLS: {
options: {
startCheck: function(stdout, stderr) {
return (/Thrift Server running on port/).test(stdout);
},
nodeSpawnOptions: {
cwd: "test",
env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"}
}
},
cmd: "node",
args: ["server_https.js"]
}
},
qunit: {
ThriftJS: {
options: {
urls: [
'http://localhost:8088/test-nojq.html'
]
}
},
ThriftJSJQ: {
options: {
urls: [
'http://localhost:8088/test.html'
]
}
},
ThriftWS: {
options: {
urls: [
'http://localhost:8088/testws.html'
]
}
},
ThriftJS_TLS: {
options: {
'--ignore-ssl-errors': true,
urls: [
'https://localhost:8089/test-nojq.html'
]
}
},
ThriftJSJQ_TLS: {
options: {
'--ignore-ssl-errors': true,
urls: [
'https://localhost:8089/test.html'
]
}
},
ThriftWS_TLS: {
options: {
'--ignore-ssl-errors': true,
urls: [
'https://localhost:8089/testws.html'
]
}
},
ThriftDeepConstructor: {
options: {
urls: [
'http://localhost:8088/test-deep-constructor.html'
]
}
}
},
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/*.js'],
options: {
// options here to override JSHint defaults
globals: {
jQuery: true,
console: true,
module: true,
document: true
}
}
},
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-jsdoc');
grunt.loadNpmTasks('grunt-external-daemon');
grunt.loadNpmTasks('grunt-shell');
grunt.registerTask('test', ['jshint', 'shell:InstallThriftJS', 'shell:InstallThriftNodeJSDep', 'shell:ThriftGen',
'external_daemon:ThriftTestServer', 'external_daemon:ThriftTestServer_TLS',
'shell:ThriftGenDeepConstructor', 'qunit:ThriftDeepConstructor',
'qunit:ThriftJS', 'qunit:ThriftJS_TLS',
'shell:ThriftGenJQ', 'qunit:ThriftJSJQ', 'qunit:ThriftJSJQ_TLS'
]);
grunt.registerTask('default', ['jshint', 'shell:InstallThriftJS', 'shell:InstallThriftNodeJSDep', 'shell:ThriftGen',
'external_daemon:ThriftTestServer', 'external_daemon:ThriftTestServer_TLS',
'qunit:ThriftJS', 'qunit:ThriftJS_TLS',
'shell:ThriftGenJQ', 'qunit:ThriftJSJQ', 'qunit:ThriftJSJQ_TLS',
'concat', 'uglify', 'jsdoc'
]);
};

27
vendor/git.apache.org/thrift.git/lib/js/Makefile.am generated vendored Normal file
View file

@ -0,0 +1,27 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# Make sure this doesn't fail if ant is not configured.
SUBDIRS = test
check-local: all
npm install
./node_modules/.bin/grunt

147
vendor/git.apache.org/thrift.git/lib/js/README.md generated vendored Normal file
View file

@ -0,0 +1,147 @@
Thrift Javascript Library
=========================
This browser based Apache Thrift implementation supports
RPC clients using the JSON protocol over Http[s] with XHR
and WebSocket.
License
-------
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
Grunt Build
------------
This is the base directory for the Apache Thrift JavaScript
library. This directory contains a Gruntfile.js and a
package.json. Many of the build and test tools used here
require a recent version of Node.js to be installed. To
install the support files for the Grunt build tool execute
the command:
npm install
This reads the package.json and pulls in the appropriate
sources from the internet. To build the JavaScript branch
of Apache Thrift execute the command:
grunt
This runs the grunt build tool, linting all of the source
files, setting up and running the tests, concatenating and
minifying the main libraries and generating the html
documentation.
If grunt is not installed you can install it with npm
like this:
sudo npm install -g grunt-cli
npm install grunt --save-dev
Tree
----
The following directories are present (some only after the
grunt build):
/src - The JavaScript Apache Thrift source
/doc - HTML documentation
/dist - Distribution files (thrift.js and thrift.min.js)
/test - Various tests, this is a good place to look for
example code
/node_modules - Build support files installed by npm
Example JavaScript Client and Server
------------------------------------
The listing below demonstrates a simple browser based JavaScript
Thrift client and Node.js JavaScript server for the hello_svc
service.
### hello.thrift - Service IDL
### build with: $ thrift -gen js -gen js:node hello.thrift
service hello_svc {
string get_message(1: string name)
}
### hello.html - Browser Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello Thrift</title>
</head>
<body>
Name: <input type="text" id="name_in">
<input type="button" id="get_msg" value="Get Message" >
<div id="output"></div>
<script src="thrift.js"></script>
<script src="gen-js/hello_svc.js"></script>
<script>
(function() {
var transport = new Thrift.TXHRTransport("/hello");
var protocol = new Thrift.TJSONProtocol(transport);
var client = new hello_svcClient(protocol);
var nameElement = document.getElementById("name_in");
var outputElement = document.getElementById("output");
document.getElementById("get_msg")
.addEventListener("click", function(){
client.get_message(nameElement.value, function(result) {
outputElement.innerHTML = result;
});
});
})();
</script>
</body>
</html>
### hello.js - Node Server
var thrift = require('thrift');
var hello_svc = require('./gen-nodejs/hello_svc.js');
var hello_handler = {
get_message: function(name, result) {
var msg = "Hello " + name + "!";
result(null, msg);
}
}
var hello_svc_opt = {
transport: thrift.TBufferedTransport,
protocol: thrift.TJSONProtocol,
processor: hello_svc,
handler: hello_handler
};
var server_opt = {
staticFilePath: ".",
services: {
"/hello": hello_svc_opt
}
}
var server = Thrift.createWebServer(server_opt);
var port = 9099;
server.listen(port);
console.log("Http/Thrift Server running on port: " + port);
TypeScript
------------------------------------
TypeScript definition files can also be generated by running:
thrift --gen js:ts file.thrift

View file

@ -0,0 +1 @@
Please follow [General Coding Standards](/doc/coding_standards.md)

15
vendor/git.apache.org/thrift.git/lib/js/package.json generated vendored Normal file
View file

@ -0,0 +1,15 @@
{
"name": "thrift",
"version": "0.10.0",
"devDependencies": {
"grunt": "^0.4.5",
"grunt-cli": "^1.2.0",
"grunt-contrib-uglify": "^1.0.1",
"grunt-contrib-jshint": "^1.0.0",
"grunt-contrib-qunit": "^1.2.0",
"grunt-contrib-concat": "^1.0.1",
"grunt-jsdoc": "^2.0.0",
"grunt-external-daemon": "^1.1.0",
"grunt-shell": "^1.3.0"
}
}

1555
vendor/git.apache.org/thrift.git/lib/js/src/thrift.js generated vendored Normal file

File diff suppressed because it is too large Load diff

29
vendor/git.apache.org/thrift.git/lib/js/test/Makefile.am generated vendored Executable file
View file

@ -0,0 +1,29 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
export CLASSPATH
# Make sure this doesn't fail if ant is not configured.
clean-local:
ANT=$(ANT) ; if test -z "$$ANT" ; then ANT=: ; fi ; \
$$ANT $(ANT_FLAGS) clean
check-local: all
$(ANT) $(ANT_FLAGS) test

68
vendor/git.apache.org/thrift.git/lib/js/test/README.md generated vendored Normal file
View file

@ -0,0 +1,68 @@
Thrift Javascript Library
=========================
This browser based Apache Thrift implementation supports
RPC clients using the JSON protocol over Http[s] with XHR
and WebSocket.
License
-------
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
Test Servers
------------
drwxr-xr-x 2 randy randy 4096 Feb 8 15:44 sec
-rw-r--r-- 1 randy randy 2183 Feb 9 04:01 server_http.js
-rw-r--r-- 1 randy randy 2386 Feb 9 05:39 server_https.js
server_http.js is a Node.js web server which support the
standard Apache Thrift test suite (thrift/test/ThriftTest.thrift).
The server supports Apache Thrift XHR and WebSocket clients.
server_https.js is the same but uses SSL/TLS. The server key
and cert are pulled from the thrift/test/keys folder.
Both of these servers support WebSocket (the http: supports ws:,
and the https: support wss:).
To run the client test with the Java test server use:
$ make check (requires the Apache Thrift Java branch
and make check must have been run in thrift/lib/java
previously).
To run the client tests with the Node servers run the grunt
build in the parent js directory (see README there).
Test Clients
------------
-rw-r--r-- 1 randy randy 13558 Feb 9 07:18 test-async.js
-rw-r--r-- 1 randy randy 5724 Feb 9 03:45 test_handler.js
-rwxr-xr-x 1 randy randy 2719 Feb 9 06:04 test.html
-rw-r--r-- 1 randy randy 4611 Feb 9 06:05 test-jq.js
-rwxr-xr-x 1 randy randy 12153 Feb 9 06:04 test.js
-rw-r--r-- 1 randy randy 2593 Feb 9 06:16 test-nojq.html
-rw-r--r-- 1 randy randy 1450 Feb 9 06:14 test-nojq.js
-rw-r--r-- 1 randy randy 2847 Feb 9 06:31 testws.html
There are three html test driver files, all of which are
QUnit based. test.html tests the Apache Thrift jQuery
generated code (thrift -gen js:jquery). The test-nojq.html
runs almost identical tests against normal JavaScript builds
(thrift -gen js). Both of the previous tests use the XHR
transport. The testws.html runs similar tests using the
WebSocket transport. The test*.js files are loaded by the
html drivers and contain the actual Apache Thrift tests.

227
vendor/git.apache.org/thrift.git/lib/js/test/build.xml generated vendored Executable file
View file

@ -0,0 +1,227 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<project name="Java Script Test" default="test" basedir="."
xmlns:artifact="antlib:org.apache.maven.artifact.ant"
xmlns:jsl="antlib:com.googlecode.jslint4java">
<description>Java Script Test based on Thrift Java Library</description>
<property name="src" location="src" />
<property name="genjava" location="gen-java" />
<property name="genjs" location="gen-js" />
<property name="build" location="build" />
<property name="jar.file" location="${build}/jstest.jar" />
<!-- the root directory, where you unpack thrift distibution (e.g. thrift-0.x.x.tar.gz) -->
<property name="thrift.dir" location="../../../" />
<property name="thrift.java.dir" location="${thrift.dir}/lib/java" />
<!-- Include the base java properties file -->
<property file="${thrift.java.dir}/build.properties" />
<property name="thrift.compiler" location="${thrift.dir}/compiler/cpp/thrift" />
<path id="libs.classpath">
<fileset dir="${thrift.java.dir}/build/">
<include name="*.jar" />
</fileset>
<fileset dir="${thrift.java.dir}/build/lib">
<include name="*.jar" />
</fileset>
<fileset dir="${build}/lib">
<include name="*.jar" />
</fileset>
</path>
<path id="test.classpath">
<path refid="libs.classpath" />
<pathelement location="${jar.file}" />
</path>
<target name="dependencies">
<fail>
<condition>
<not>
<resourcecount count="2">
<fileset id="fs" dir="${thrift.java.dir}/build">
<include name="libthrift*.jar" />
<exclude name="libthrift*javadoc.jar" />
</fileset>
</resourcecount>
</not>
</condition>
You need libthrift*.jar and libthrift*test.jar located at
${thrift.java.dir}/build
Did you compile Thrift Java library and its test suite by "ant compile-test"?
</fail>
<fail>
<condition>
<not>
<resourcecount count="1">
<fileset id="fs" dir="${thrift.dir}" includes="compiler/cpp/thrift"/>
</resourcecount>
</not>
</condition>
Thrift compiler is missing !
</fail>
</target>
<target name="init" depends="dependencies">
<tstamp />
<mkdir dir="${build}"/>
<mkdir dir="${build}/js/lib"/>
<mkdir dir="${build}/lib"/>
<mkdir dir="${build}/log"/>
<mkdir dir="${build}/test"/>
<mkdir dir="${build}/test/log"/>
</target>
<target name="jslibs" depends="init, proxy">
<get src="http://code.jquery.com/jquery-1.11.3.min.js" dest="${build}/js/lib/jquery.js" usetimestamp="true"/>
<get src="http://code.jquery.com/qunit/qunit-1.18.0.js" dest="${build}/js/lib/qunit.js" usetimestamp="true"/>
<get src="http://code.jquery.com/qunit/qunit-1.18.0.css" dest="${build}/js/lib/qunit.css" usetimestamp="true"/>
</target>
<target name="compile" description="compile the test suite" depends="init, generate, resolve">
<!-- //TODO enable <compilerarg value="-Xlint"/>-->
<javac includeantruntime="false" srcdir="${genjava}" destdir="${build}/test" classpathref="libs.classpath"/>
<javac includeantruntime="false" srcdir="${src}" destdir="${build}/test" classpathref="libs.classpath"/>
</target>
<target name="jstest" description="create the test suite jar file" depends="compile">
<jar jarfile="${jar.file}" basedir="${build}/test"/>
</target>
<target name="testserver" description="run the test server" depends="jstest, jslibs">
<java classname="test.Httpd" fork="true"
classpathref="test.classpath" failonerror="true">
<arg value="../" />
</java>
</target>
<target name="proxy" if="proxy.enabled">
<setproxy proxyhost="${proxy.host}" proxyport="${proxy.port}"
proxyuser="${proxy.user}" proxypassword="${proxy.pass}"/>
</target>
<target name="xvfb">
<echo>check if Xvfb is available:</echo>
<exec executable="Xvfb" failifexecutionfails="no" resultproperty="xvfb.present" failonerror="false" output="${build}/log/xvfb.log">
<arg line="--version"/>
</exec>
</target>
<target name="phantomjs" depends="xvfb" if="xvfb.present">
<echo>check if phantomjs is available:</echo>
<exec executable="phantomjs" failifexecutionfails="no" resultproperty="phantomjs.present" failonerror="false" output="${build}/log/phantomjs.log">
<arg line="--version"/>
</exec>
</target>
<target name="unittest" description="do unit tests with headless browser phantomjs" depends="init, phantomjs, jstest, jslibs" if="phantomjs.present">
<parallel>
<exec executable="Xvfb" spawn="true" failonerror="false">
<arg line=":99" />
</exec>
<java classname="test.Httpd" fork="true" timeout="10000"
classpathref="test.classpath" failonerror="false" output="${build}/log/unittest.log">
<arg value="../" />
</java>
<sequential>
<sleep seconds="2"/>
<echo>Running Unit Tests with headless browser!</echo>
<exec executable="phantomjs" failonerror="true">
<env key="DISPLAY" value=":99"/>
<arg line="phantomjs-qunit.js http://localhost:8088/test/test.html" />
</exec>
</sequential>
</parallel>
</target>
<target name="generate">
<exec executable="${thrift.compiler}" failonerror="true">
<arg line="--gen java ${thrift.dir}/test/ThriftTest.thrift" />
</exec>
<exec executable="${thrift.compiler}" failonerror="true">
<arg line="--gen js:jquery ${thrift.dir}/test/ThriftTest.thrift" />
</exec>
</target>
<target name="test" description="run test suite (lint, unittest)" depends="lint, unittest"/>
<target name="lint" description="code quality checks (jslint and gjslint if available)" depends="generate, gjslint, jslint"/>
<target name="jslint" depends="resolve">
<taskdef uri="antlib:com.googlecode.jslint4java" resource="com/googlecode/jslint4java/antlib.xml" classpathref="libs.classpath" />
<!--
the following options would probably make sense in the future:
browser,undef,eqeqeq,plusplus,bitwise,regexp,strict,newcap,immed
-->
<jsl:jslint options="evil,forin,browser,bitwise,regexp,newcap,immed" encoding="UTF-8">
<formatter type="plain" />
<fileset dir="${genjs}" includes="**/*.js" />
<fileset dir="../src" includes="thrift.js" />
<!-- issues with unsafe character -->
<!-- fileset dir="." includes="*test*.js" /> -->
</jsl:jslint>
</target>
<target name="check-gjslint">
<echo>check if gjslint is available:</echo>
<exec executable="gjslint" failifexecutionfails="no" resultproperty="gjslint.present" failonerror="false">
<arg line="--helpshort"/>
</exec>
</target>
<target name="gjslint" depends="check-gjslint" if="gjslint.present">
<exec executable="gjslint" failifexecutionfails="no">
<arg line="--nojsdoc"/>
<arg line="${genjs}/*.js"/>
<arg line="../src/thrift.js"/>
<!-- issues with unsafe character, etc. -->
<!-- <arg line="*test*.js"/> -->
</exec>
</target>
<target name="clean">
<delete dir="${build}" />
<delete dir="${genjava}" />
<delete dir="${genjs}" />
</target>
<target name="resolve" unless="mvn.finished">
<typedef uri="antlib:org.apache.maven.artifact.ant" classpath="${thrift.java.dir}/build/tools/${mvn.ant.task.jar}"/>
<artifact:dependencies filesetId="js.test.dependency.jars">
<dependency groupId="org.apache.httpcomponents" artifactId="httpclient" version="4.0.1"/>
<dependency groupId="com.googlecode.jslint4java" artifactId="jslint4java-ant" version="1.4.6"/>
<dependency groupId="eu.medsea.mimeutil" artifactId="mime-util" version="2.1.3"/>
</artifact:dependencies>
<!-- Copy the dependencies to the build/lib dir -->
<copy todir="${build}/lib">
<fileset refid="js.test.dependency.jars"/>
<mapper type="flatten"/>
</copy>
<property name="mvn.finished" value="true"/>
</target>
</project>

View file

@ -0,0 +1,195 @@
function serialize(data) {
var transport = new Thrift.Transport("/service");
var protocol = new Thrift.Protocol(transport);
protocol.writeMessageBegin("", 0, 0);
data.write(protocol);
protocol.writeMessageEnd();
return transport.send_buf;
}
function deserialize(serialized, type) {
var transport = new Thrift.Transport("/service");
transport.setRecvBuffer(serialized);
var protocol = new Thrift.Protocol(transport);
protocol.readMessageBegin();
var data = new type();
data.read(protocol);
protocol.readMessageEnd();
return data;
}
function createThriftObj() {
return new Complex({
struct_field: new Simple({value: 'a'}),
struct_list_field: [
new Simple({value: 'b'}),
new Simple({value: 'c'}),
],
struct_set_field: [
new Simple({value: 'd'}),
new Simple({value: 'e'}),
],
struct_map_field: {
A: new Simple({value: 'f'}),
B: new Simple({value: 'g'})
},
struct_nested_containers_field: [
[
{
C: [
new Simple({value: 'h'}),
new Simple({value: 'i'})
]
}
]
],
struct_nested_containers_field2: {
D: [
{
DA: new Simple({value: 'j'})
},
{
DB: new Simple({value: 'k'})
}
]
}
}
);
}
function createJsObj() {
return {
struct_field: {value: 'a'},
struct_list_field: [
{value: 'b'},
{value: 'c'},
],
struct_set_field: [
{value: 'd'},
{value: 'e'},
],
struct_map_field: {
A: {value: 'f'},
B: {value: 'g'}
},
struct_nested_containers_field: [
[
{
C: [
{value: 'h'},
{value: 'i'}
]
}
]
],
struct_nested_containers_field2: {
D: [
{
DA: {value: 'j'}
},
{
DB: {value: 'k'}
}
]
}
};
}
function assertValues(obj, assert) {
assert.equal(obj.struct_field.value, 'a');
assert.equal(obj.struct_list_field[0].value, 'b');
assert.equal(obj.struct_list_field[1].value, 'c');
assert.equal(obj.struct_set_field[0].value, 'd');
assert.equal(obj.struct_set_field[1].value, 'e');
assert.equal(obj.struct_map_field.A.value, 'f');
assert.equal(obj.struct_map_field.B.value, 'g');
assert.equal(obj.struct_nested_containers_field[0][0].C[0].value, 'h');
assert.equal(obj.struct_nested_containers_field[0][0].C[1].value, 'i');
assert.equal(obj.struct_nested_containers_field2.D[0].DA.value, 'j');
assert.equal(obj.struct_nested_containers_field2.D[1].DB.value, 'k');
}
var cases = {
"Serialize/deserialize simple struct should return equal object": function(assert){
var tObj = new Simple({value: 'a'});
var received = deserialize(serialize(tObj), Simple);
assert.ok(tObj !== received);
assert.deepEqual(received, tObj);
},
"Serialize/deserialize should return equal object": function(assert){
var tObj = createThriftObj();
var received = deserialize(serialize(tObj), Complex);
assert.ok(tObj !== received);
assert.deepEqual(received, tObj);
},
"Nested structs and containers initialized from plain js objects should serialize same as if initialized from thrift objects": function(assert) {
var tObj1 = createThriftObj();
var tObj2 = new Complex(createJsObj());
assertValues(tObj2, assert);
assert.equal(serialize(tObj2), serialize(tObj1));
},
"Modifications to args object should not affect constructed Thrift object": function (assert) {
var args = createJsObj();
assertValues(args, assert);
var tObj = new Complex(args);
assertValues(tObj, assert);
args.struct_field.value = 'ZZZ';
args.struct_list_field[0].value = 'ZZZ';
args.struct_list_field[1].value = 'ZZZ';
args.struct_set_field[0].value = 'ZZZ';
args.struct_set_field[1].value = 'ZZZ';
args.struct_map_field.A.value = 'ZZZ';
args.struct_map_field.B.value = 'ZZZ';
args.struct_nested_containers_field[0][0].C[0] = 'ZZZ';
args.struct_nested_containers_field[0][0].C[1] = 'ZZZ';
args.struct_nested_containers_field2.D[0].DA = 'ZZZ';
args.struct_nested_containers_field2.D[0].DB = 'ZZZ';
assertValues(tObj, assert);
},
"nulls are ok": function(assert) {
var tObj = new Complex({
struct_field: null,
struct_list_field: null,
struct_set_field: null,
struct_map_field: null,
struct_nested_containers_field: null,
struct_nested_containers_field2: null
});
var received = deserialize(serialize(tObj), Complex);
assert.ok(tObj !== received);
assert.deepEqual(tObj, received);
}
};
Object.keys(cases).forEach(function(caseName) {
test(caseName, cases[caseName]);
});

View file

@ -0,0 +1,17 @@
server: http://localhost:9876
load:
# Qunit adapter
- build/js/lib/equiv.js
- build/js/lib/QUnitAdapter.js
# dependencies
- build/js/lib/jquery.js
- build/js/thrift.js
- gen-js/ThriftTest_types.js
- gen-js/ThriftTest.js
# the test suite
- test.js
# redirect to the Java based Thrift testserver
proxy:
- {matcher: "*", server: " http://localhost:8088"}

View file

@ -0,0 +1,382 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* jshint -W100 */
(function() {
'use strict';
// Rudimentary test helper functions
// TODO: Return error code based on kind of errors rather than throw
var ok = function(t, msg) {
if (!t) {
console.log('*** FAILED ***');
throw new Error(msg);
}
};
var equal = function(a, b) {
if (a !== b) {
console.log('*** FAILED ***');
throw new Error();
}
};
var test = function(name, f) {
console.log('TEST : ' + name);
f();
console.log('OK\n');
};
var parseArgs = function(args) {
var skips = [
'--transport=http',
'--protocol=json',
];
var opts = {
port: '9090',
// protocol: 'json',
};
var keys = {};
for (var key in opts) {
keys['--' + key + '='] = key;
}
for (var i in args) {
var arg = args[i];
if (skips.indexOf(arg) != -1) {
continue;
}
var hit = false;
for (var k in keys) {
if (arg.slice(0, k.length) === k) {
opts[keys[k]] = arg.slice(k.length);
hit = true;
break;
}
}
if (!hit) {
throw new Error('Unknown argument: ' + arg);
}
}
opts.port = parseInt(opts.port, 10);
if (!opts.port || opts.port < 1 || opts.port > 65535) {
throw new Error('Invalid port number');
}
return opts;
};
var execute = function() {
console.log('### Apache Thrift Javascript standalone test client');
console.log('------------------------------------------------------------');
phantom.page.injectJs('src/thrift.js');
phantom.page.injectJs('test/gen-js/ThriftTest_types.js');
phantom.page.injectJs('test/gen-js/ThriftTest.js');
var system = require('system');
var opts = parseArgs(system.args.slice(1));
var port = opts.port;
var transport = new Thrift.Transport('http://localhost:' + port + '/service');
var protocol = new Thrift.Protocol(transport);
var client = new ThriftTest.ThriftTestClient(protocol);
// TODO: Remove duplicate code with test.js.
// all Languages in UTF-8
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ú, 粵語";
function checkRecursively(map1, map2) {
if (typeof map1 !== 'function' && typeof map2 !== 'function') {
if (!map1 || typeof map1 !== 'object') {
equal(map1, map2);
} else {
for (var key in map1) {
checkRecursively(map1[key], map2[key]);
}
}
}
}
test("Void", function() {
equal(client.testVoid(), undefined);
});
test("Binary (String)", function() {
var binary = '';
for (var v = 255; v >= 0; --v) {
binary += String.fromCharCode(v);
}
equal(client.testBinary(binary), binary);
});
test("Binary (Uint8Array)", function() {
var binary = '';
for (var v = 255; v >= 0; --v) {
binary += String.fromCharCode(v);
}
var arr = new Uint8Array(binary.length);
for (var i = 0; i < binary.length; ++i) {
arr[i] = binary[i].charCodeAt();
}
equal(client.testBinary(arr), binary);
});
test("String", function() {
equal(client.testString(''), '');
equal(client.testString(stringTest), stringTest);
var specialCharacters = 'quote: \" backslash:' +
' forwardslash-escaped: \/ ' +
' backspace: \b formfeed: \f newline: \n return: \r tab: ' +
' now-all-of-them-together: "\\\/\b\n\r\t' +
' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><';
equal(client.testString(specialCharacters),specialCharacters);
});
test("Double", function() {
equal(client.testDouble(0), 0);
equal(client.testDouble(-1), -1);
equal(client.testDouble(3.14), 3.14);
equal(client.testDouble(Math.pow(2,60)), Math.pow(2,60));
});
test("Bool", function() {
equal(client.testBool(true), true);
equal(client.testBool(false), false);
});
test("I8", function() {
equal(client.testByte(0), 0);
equal(client.testByte(0x01), 0x01);
});
test("I32", function() {
equal(client.testI32(0), 0);
equal(client.testI32(Math.pow(2,30)), Math.pow(2,30));
equal(client.testI32(-Math.pow(2,30)), -Math.pow(2,30));
});
test("I64", function() {
equal(client.testI64(0), 0);
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
equal(client.testI64(Math.pow(2,52)), Math.pow(2,52));
equal(client.testI64(-Math.pow(2,52)), -Math.pow(2,52));
});
test("Struct", function() {
var structTestInput = new ThriftTest.Xtruct();
structTestInput.string_thing = 'worked';
structTestInput.byte_thing = 0x01;
structTestInput.i32_thing = Math.pow(2,30);
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
structTestInput.i64_thing = Math.pow(2,52);
var structTestOutput = client.testStruct(structTestInput);
equal(structTestOutput.string_thing, structTestInput.string_thing);
equal(structTestOutput.byte_thing, structTestInput.byte_thing);
equal(structTestOutput.i32_thing, structTestInput.i32_thing);
equal(structTestOutput.i64_thing, structTestInput.i64_thing);
equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput));
});
test("Nest", function() {
var xtrTestInput = new ThriftTest.Xtruct();
xtrTestInput.string_thing = 'worked';
xtrTestInput.byte_thing = 0x01;
xtrTestInput.i32_thing = Math.pow(2,30);
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
xtrTestInput.i64_thing = Math.pow(2,52);
var nestTestInput = new ThriftTest.Xtruct2();
nestTestInput.byte_thing = 0x02;
nestTestInput.struct_thing = xtrTestInput;
nestTestInput.i32_thing = Math.pow(2,15);
var nestTestOutput = client.testNest(nestTestInput);
equal(nestTestOutput.byte_thing, nestTestInput.byte_thing);
equal(nestTestOutput.struct_thing.string_thing, nestTestInput.struct_thing.string_thing);
equal(nestTestOutput.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing);
equal(nestTestOutput.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing);
equal(nestTestOutput.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing);
equal(nestTestOutput.i32_thing, nestTestInput.i32_thing);
equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput));
});
test("Map", function() {
var mapTestInput = {7:77, 8:88, 9:99};
var mapTestOutput = client.testMap(mapTestInput);
for (var key in mapTestOutput) {
equal(mapTestOutput[key], mapTestInput[key]);
}
});
test("StringMap", function() {
var mapTestInput = {
"a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key",
"longValue":stringTest, stringTest:"long key"
};
var mapTestOutput = client.testStringMap(mapTestInput);
for (var key in mapTestOutput) {
equal(mapTestOutput[key], mapTestInput[key]);
}
});
test("Set", function() {
var setTestInput = [1,2,3];
ok(client.testSet(setTestInput), setTestInput);
});
test("List", function() {
var listTestInput = [1,2,3];
ok(client.testList(listTestInput), listTestInput);
});
test("Enum", function() {
equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE);
});
test("TypeDef", function() {
equal(client.testTypedef(69), 69);
});
test("Skip", function() {
var structTestInput = new ThriftTest.Xtruct();
var modifiedClient = new ThriftTest.ThriftTestClient(protocol);
modifiedClient.recv_testStruct = function() {
var input = modifiedClient.input;
var xtruct3 = new ThriftTest.Xtruct3();
input.readMessageBegin();
input.readStructBegin();
// read Xtruct data with Xtruct3
input.readFieldBegin();
xtruct3.read(input);
input.readFieldEnd();
// read Thrift.Type.STOP message
input.readFieldBegin();
input.readFieldEnd();
input.readStructEnd();
input.readMessageEnd();
return xtruct3;
};
structTestInput.string_thing = 'worked';
structTestInput.byte_thing = 0x01;
structTestInput.i32_thing = Math.pow(2,30);
structTestInput.i64_thing = Math.pow(2,52);
var structTestOutput = modifiedClient.testStruct(structTestInput);
equal(structTestOutput instanceof ThriftTest.Xtruct3, true);
equal(structTestOutput.string_thing, structTestInput.string_thing);
equal(structTestOutput.changed, null);
equal(structTestOutput.i32_thing, structTestInput.i32_thing);
equal(structTestOutput.i64_thing, structTestInput.i64_thing);
});
test("MapMap", function() {
var mapMapTestExpectedResult = {
"4":{"1":1,"2":2,"3":3,"4":4},
"-4":{"-4":-4, "-3":-3, "-2":-2, "-1":-1}
};
var mapMapTestOutput = client.testMapMap(1);
for (var key in mapMapTestOutput) {
for (var key2 in mapMapTestOutput[key]) {
equal(mapMapTestOutput[key][key2], mapMapTestExpectedResult[key][key2]);
}
}
checkRecursively(mapMapTestOutput, mapMapTestExpectedResult);
});
test("Xception", function() {
try {
client.testException("Xception");
ok(false);
} catch (e) {
equal(e.errorCode, 1001);
equal(e.message, "Xception");
}
});
test("no Exception", function() {
try {
client.testException("no Exception");
} catch (e) {
ok(false);
}
});
test("TException", function() {
try {
client.testException("TException");
ok(false);
} catch(e) {
ok(ok);
}
});
var crazy = {
"userMap":{ "5":5, "8":8 },
"xtructs":[{
"string_thing":"Goodbye4",
"byte_thing":4,
"i32_thing":4,
"i64_thing":4
},
{
"string_thing":"Hello2",
"byte_thing":2,
"i32_thing":2,
"i64_thing":2
}]
};
test("Insanity", function() {
var insanity = {
"1":{
"2":crazy,
"3":crazy
},
"2":{ "6":{ "userMap":null, "xtructs":null } }
};
var res = client.testInsanity(new ThriftTest.Insanity(crazy));
ok(res, JSON.stringify(res));
ok(insanity, JSON.stringify(insanity));
checkRecursively(res, insanity);
});
console.log('------------------------------------------------------------');
console.log('### All tests succeeded.');
return 0;
};
try {
var ret = execute();
phantom.exit(ret);
} catch (err) {
// Catch all and exit to avoid hang.
console.error(err);
phantom.exit(1);
}
})();

View file

@ -0,0 +1,91 @@
/*jshint evil:true*/
/* This file is only used by the test suite.
*
* Origin: https://github.com/ariya/phantomjs/blob/master/examples/run-qunit.js
* License: https://github.com/ariya/phantomjs/blob/master/LICENSE.BSD
*
* Inclusion into Apache products is allowed according to http://www.apache.org/legal/3party.html
*/
var system = require('system');
/**
* Wait until the test condition is true or a timeout occurs. Useful for waiting
* on a server response or for a ui change (fadeIn, etc.) to occur.
*
* @param testFx javascript condition that evaluates to a boolean,
* it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
* as a callback function.
* @param onReady what to do when testFx condition is fulfilled,
* it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
* as a callback function.
* @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
*/
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timout is 3s
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
console.log("'waitFor()' timeout");
phantom.exit(1);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
if (typeof(onReady) === "string") {
eval(onReady);
} else {
onReady(); //< Do what it's supposed to do once the condition is fulfilled
}
clearInterval(interval); //< Stop this interval
}
}
}, 100); //< repeat check every 250ms
}
if (system.args.length === 1 || system.args.length > 3) {
console.log('Usage: phantomjs phantomjs-qunit.js URL');
phantom.exit(1);
}
var page = new WebPage();
// Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this")
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.open(system.args[1], function(status){
if (status !== "success") {
console.log("Unable to access network");
phantom.exit(1);
} else {
waitFor(function(){
return page.evaluate(function(){
var el = document.getElementById('qunit-testresult');
if (el && el.innerText.match('completed')) {
return true;
}
return false;
});
}, function(){
var failedNum = page.evaluate(function(){
var el = document.getElementById('qunit-testresult');
console.log(el.innerText);
try {
return el.getElementsByClassName('failed')[0].innerHTML;
} catch (e) { }
return 10000;
});
phantom.exit((parseInt(failedNum, 10) > 0) ? 1 : 0);
});
}
});

View file

@ -0,0 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//This HTTP server is designed to serve the test.html browser
// based JavaScript test page (which must be in the current directory).
// This server also supplies the Thrift based test service, which depends
// on the standard ThriftTest.thrift IDL service (which must be compiled
// for Node and browser based JavaScript in ./gen-nodejs and ./gen-js
// respectively).
var thrift = require('../../nodejs/lib/thrift');
var ThriftTestSvc = require('./gen-nodejs/ThriftTest.js');
var ThriftTestHandler = require('./test_handler').ThriftTestHandler;
var ThriftTestSvcOpt = {
transport: thrift.TBufferedTransport,
protocol: thrift.TJSONProtocol,
processor: ThriftTestSvc,
handler: ThriftTestHandler
};
var ThriftWebServerOptions = {
files: ".",
services: {
"/service": ThriftTestSvcOpt
}
};
var server = thrift.createWebServer(ThriftWebServerOptions);
var port = 8088;
server.listen(port);
console.log("Serving files from: " + __dirname);
console.log("Http/Thrift Server running on port: " + port);

View file

@ -0,0 +1,57 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//This HTTP server is designed to server the test.html browser
// based JavaScript test page (which must be in the current directory).
// This server also supplies the Thrift based test service, which depends
// on the standard ThriftTest.thrift IDL service (which must be compiled
// for Node and browser based JavaScript in ./gen-nodejs and ./gen-js
// respectively). The current directory must also include the browser
// support libraries for test.html (jquery.js, qunit.js and qunit.css
// in ./build/js/lib).
var fs = require("fs");
var thrift = require('../../nodejs/lib/thrift');
var ThriftTestSvc = require('./gen-nodejs/ThriftTest.js');
var ThriftTestHandler = require('./test_handler').ThriftTestHandler;
//Setup the I/O stack options for the ThriftTest service
var ThriftTestSvcOpt = {
transport: thrift.TBufferedTransport,
protocol: thrift.TJSONProtocol,
processor: ThriftTestSvc,
handler: ThriftTestHandler
};
var ThriftWebServerOptions = {
files: ".",
tls: {
key: fs.readFileSync("../../../test/keys/server.key"),
cert: fs.readFileSync("../../../test/keys/server.crt")
},
services: {
"/service": ThriftTestSvcOpt
}
};
var server = thrift.createWebServer(ThriftWebServerOptions);
var port = 8089;
server.listen(port);
console.log("Serving files from: " + __dirname);
console.log("Http/Thrift Server running on port: " + port);

View file

@ -0,0 +1,323 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package test;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.Locale;
import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpServerConnection;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.impl.NoConnectionReuseStrategy;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.HttpService;
import org.apache.http.util.EntityUtils;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TMemoryBuffer;
import thrift.test.ThriftTest;
import org.apache.thrift.server.ServerTestBase.TestHandler;
import eu.medsea.mimeutil.detector.ExtensionMimeDetector;
import eu.medsea.mimeutil.MimeUtil2;
import eu.medsea.mimeutil.MimeType;
import java.util.Collection;
import java.util.Iterator;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
* <p>
* Please note the purpose of this application is demonstrate the usage of
* HttpCore APIs. It is NOT intended to demonstrate the most efficient way of
* building an HTTP file server.
*
*
*/
public class Httpd {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
Thread t = new RequestListenerThread(8088, args[0]);
t.setDaemon(false);
t.start();
}
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
String target = request.getRequestLine().getUri();
if (request instanceof HttpEntityEnclosingRequest && target.equals("/service")) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming content: " + new String(entityContent));
final String output = this.thriftRequest(entityContent);
System.out.println("Outgoing content: "+output);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write(output);
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
} else {
if(target.indexOf("?") != -1) {
target = target.substring(1, target.indexOf("?"));
}
final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("File ");
writer.write(file.getPath());
writer.write(" not found");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("Access denied");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("Cannot read file " + file.getPath());
} else {
String mimeType = "application/octet-stream";
MimeUtil2 mimeUtil = new MimeUtil2();
synchronized (this) {
mimeUtil.registerMimeDetector(ExtensionMimeDetector.class.getName());
}
Collection<MimeType> collection = mimeUtil.getMimeTypes(file);
Iterator<MimeType> iterator = collection.iterator();
while(iterator.hasNext()) {
MimeType mt = iterator.next();
mimeType = mt.getMediaType() + "/" + mt.getSubType();
break;
}
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(file, mimeType);
response.addHeader("Content-Type", mimeType);
response.setEntity(body);
System.out.println("Serving file " + file.getPath());
}
}
}
private String thriftRequest(byte[] input){
try{
//Input
TMemoryBuffer inbuffer = new TMemoryBuffer(input.length);
inbuffer.write(input);
TProtocol inprotocol = new TJSONProtocol(inbuffer);
//Output
TMemoryBuffer outbuffer = new TMemoryBuffer(100);
TProtocol outprotocol = new TJSONProtocol(outbuffer);
TProcessor processor = new ThriftTest.Processor(new TestHandler());
processor.process(inprotocol, outprotocol);
byte[] output = new byte[outbuffer.length()];
outbuffer.readAll(output, 0, output.length);
return new String(output,"UTF-8");
}catch(Throwable t){
return "Error:"+t.getMessage();
}
}
}
static class RequestListenerThread extends Thread {
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final String docroot) throws IOException {
this.serversocket = new ServerSocket(port);
this.params = new BasicHttpParams();
this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 1000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
HttpProcessor httpproc = new BasicHttpProcessor();
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(docroot));
// Set up the HTTP service
this.httpService = new HttpService(httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory());
this.httpService.setParams(this.params);
this.httpService.setHandlerResolver(reqistry);
}
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
System.out.println("Point your browser to http://localhost:8088/test/test.html");
while (!Thread.interrupted()) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from " + socket.getInetAddress());
conn.bind(socket, this.params);
// Start worker thread
Thread t = new WorkerThread(this.httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: " + e.getMessage());
break;
}
}
}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(final HttpService httpservice, final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
}
}
}

View file

@ -0,0 +1,348 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* jshint -W100 */
/*
* Fully Async JavaScript test suite for ThriftTest.thrift.
* These tests are designed to exercise the WebSocket transport
* (which is exclusively async).
*
* To compile client code for this test use:
* $ thrift -gen js ThriftTest.thrift
*/
// all Languages in UTF-8
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ú, 粵語";
function checkRecursively(map1, map2) {
if (typeof map1 !== 'function' && typeof map2 !== 'function') {
if (!map1 || typeof map1 !== 'object') {
equal(map1, map2);
} else {
for (var key in map1) {
checkRecursively(map1[key], map2[key]);
}
}
}
}
module("Base Types");
asyncTest("Void", function() {
expect( 1 );
client.testVoid(function(result) {
equal(result, undefined);
QUnit.start();
});
});
asyncTest("String", function() {
expect( 3 );
QUnit.stop(2);
client.testString('', function(result){
equal(result, '');
QUnit.start();
});
client.testString(stringTest, function(result){
equal(result, stringTest);
QUnit.start();
});
var specialCharacters = 'quote: \" backslash:' +
' forwardslash-escaped: \/ ' +
' backspace: \b formfeed: \f newline: \n return: \r tab: ' +
' now-all-of-them-together: "\\\/\b\n\r\t' +
' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><';
client.testString(specialCharacters, function(result){
equal(result, specialCharacters);
QUnit.start();
});
});
asyncTest("Double", function() {
expect( 4 );
QUnit.stop(3);
client.testDouble(0, function(result){
equal(result, 0);
QUnit.start();
});
client.testDouble(-1, function(result){
equal(result, -1);
QUnit.start();
});
client.testDouble(3.14, function(result){
equal(result, 3.14);
QUnit.start();
});
client.testDouble(Math.pow(2,60), function(result){
equal(result, Math.pow(2,60));
QUnit.start();
});
});
// TODO: add testBinary()
asyncTest("Byte", function() {
expect( 2 );
QUnit.stop();
client.testByte(0, function(result) {
equal(result, 0);
QUnit.start();
});
client.testByte(0x01, function(result) {
equal(result, 0x01);
QUnit.start();
});
});
asyncTest("I32", function() {
expect( 3 );
QUnit.stop(2);
client.testI32(0, function(result){
equal(result, 0);
QUnit.start();
});
client.testI32(Math.pow(2,30), function(result){
equal(result, Math.pow(2,30));
QUnit.start();
});
client.testI32(-Math.pow(2,30), function(result){
equal(result, -Math.pow(2,30));
QUnit.start();
});
});
asyncTest("I64", function() {
expect( 3 );
QUnit.stop(2);
client.testI64(0, function(result){
equal(result, 0);
QUnit.start();
});
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
client.testI64(Math.pow(2,52), function(result){
equal(result, Math.pow(2,52));
QUnit.start();
});
client.testI64(-Math.pow(2,52), function(result){
equal(result, -Math.pow(2,52));
QUnit.start();
});
});
module("Structured Types");
asyncTest("Struct", function() {
expect( 5 );
var structTestInput = new ThriftTest.Xtruct();
structTestInput.string_thing = 'worked';
structTestInput.byte_thing = 0x01;
structTestInput.i32_thing = Math.pow(2,30);
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
structTestInput.i64_thing = Math.pow(2,52);
client.testStruct(structTestInput, function(result){
equal(result.string_thing, structTestInput.string_thing);
equal(result.byte_thing, structTestInput.byte_thing);
equal(result.i32_thing, structTestInput.i32_thing);
equal(result.i64_thing, structTestInput.i64_thing);
equal(JSON.stringify(result), JSON.stringify(structTestInput));
QUnit.start();
});
});
asyncTest("Nest", function() {
expect( 7 );
var xtrTestInput = new ThriftTest.Xtruct();
xtrTestInput.string_thing = 'worked';
xtrTestInput.byte_thing = 0x01;
xtrTestInput.i32_thing = Math.pow(2,30);
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
xtrTestInput.i64_thing = Math.pow(2,52);
var nestTestInput = new ThriftTest.Xtruct2();
nestTestInput.byte_thing = 0x02;
nestTestInput.struct_thing = xtrTestInput;
nestTestInput.i32_thing = Math.pow(2,15);
client.testNest(nestTestInput, function(result){
equal(result.byte_thing, nestTestInput.byte_thing);
equal(result.struct_thing.string_thing, nestTestInput.struct_thing.string_thing);
equal(result.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing);
equal(result.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing);
equal(result.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing);
equal(result.i32_thing, nestTestInput.i32_thing);
equal(JSON.stringify(result), JSON.stringify(nestTestInput));
QUnit.start();
});
});
asyncTest("Map", function() {
expect( 3 );
var mapTestInput = {7:77, 8:88, 9:99};
client.testMap(mapTestInput, function(result){
for (var key in result) {
equal(result[key], mapTestInput[key]);
}
QUnit.start();
});
});
asyncTest("StringMap", function() {
expect( 6 );
var mapTestInput = {
"a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key",
"longValue":stringTest, stringTest:"long key"
};
client.testStringMap(mapTestInput, function(result){
for (var key in result) {
equal(result[key], mapTestInput[key]);
}
QUnit.start();
});
});
asyncTest("Set", function() {
expect( 1 );
var setTestInput = [1,2,3];
client.testSet(setTestInput, function(result){
ok(result, setTestInput);
QUnit.start();
});
});
asyncTest("List", function() {
expect( 1 );
var listTestInput = [1,2,3];
client.testList(listTestInput, function(result){
ok(result, listTestInput);
QUnit.start();
});
});
asyncTest("Enum", function() {
expect( 1 );
client.testEnum(ThriftTest.Numberz.ONE, function(result){
equal(result, ThriftTest.Numberz.ONE);
QUnit.start();
});
});
asyncTest("TypeDef", function() {
expect( 1 );
client.testTypedef(69, function(result){
equal(result, 69);
QUnit.start();
});
});
module("deeper!");
asyncTest("MapMap", function() {
expect( 16 );
var mapMapTestExpectedResult = {
"4":{"1":1,"2":2,"3":3,"4":4},
"-4":{"-4":-4, "-3":-3, "-2":-2, "-1":-1}
};
client.testMapMap(1, function(result){
for (var key in result) {
for (var key2 in result[key]) {
equal(result[key][key2], mapMapTestExpectedResult[key][key2]);
}
}
checkRecursively(result, mapMapTestExpectedResult);
QUnit.start();
});
});
module("Exception");
asyncTest("Xception", function() {
expect(2);
client.testException("Xception", function(e){
equal(e.errorCode, 1001);
equal(e.message, "Xception");
QUnit.start();
});
});
asyncTest("no Exception", 0, function() {
expect( 1 );
client.testException("no Exception", function(e){
ok(!e);
QUnit.start();
});
});
module("Insanity");
asyncTest("testInsanity", function() {
expect( 24 );
var insanity = {
"1":{
"2":{
"userMap":{ "5":5, "8":8 },
"xtructs":[{
"string_thing":"Goodbye4",
"byte_thing":4,
"i32_thing":4,
"i64_thing":4
},
{
"string_thing":"Hello2",
"byte_thing":2,
"i32_thing":2,
"i64_thing":2
}
]
},
"3":{
"userMap":{ "5":5, "8":8 },
"xtructs":[{
"string_thing":"Goodbye4",
"byte_thing":4,
"i32_thing":4,
"i64_thing":4
},
{
"string_thing":"Hello2",
"byte_thing":2,
"i32_thing":2,
"i64_thing":2
}
]
}
},
"2":{ "6":{ "userMap":null, "xtructs":null } }
};
client.testInsanity(new ThriftTest.Insanity(), function(res){
ok(res, JSON.stringify(res));
ok(insanity, JSON.stringify(insanity));
checkRecursively(res, insanity);
QUnit.start();
});
});

View file

@ -0,0 +1,49 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Thrift Javascript Bindings: Unit Test</title>
<script src="build/js/thrift.js" type="text/javascript" charset="utf-8"></script>
<script src="gen-js/JsDeepConstructorTest_types.js" type="text/javascript" charset="utf-8"></script>
<!-- jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js" charset="utf-8"></script>
<!-- QUnit Test framework-->
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.14.0.js" charset="utf-8"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.14.0.css" type="text/css" media="screen" />
<!-- the Test Suite-->
<script type="text/javascript" src="deep-constructor.test.js" charset="utf-8"></script>
</head>
<body>
<h1 id="qunit-header">Thrift Javascript Bindings: Deep Constructor Test (<a href="https://git-wip-us.apache.org/repos/asf?p=thrift.git;a=blob;f=test/JsDeepConstructorTest.thrift;hb=HEAD">JsDeepConstructorTest.thrift</a>)</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"><li><!-- get valid xhtml strict--></li></ol>
<p>
<a href="http://validator.w3.org/check/referer"><img
src="http://www.w3.org/Icons/valid-xhtml10"
alt="Valid XHTML 1.0!" height="31" width="88" /></a>
</p>
</body>
</html>

158
vendor/git.apache.org/thrift.git/lib/js/test/test-jq.js generated vendored Normal file
View file

@ -0,0 +1,158 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* jshint -W100 */
/*
* JavaScript test suite for ThriftTest.thrift. These tests
* will run only with jQuery (-gen js:jquery) Apache Thrift
* interfaces. To create client code:
* $ thrift -gen js:jquery ThriftTest.thrift
*
* See also:
* ++ test.js for generic tests
* ++ test-nojq.js for "-gen js" only tests
*/
//////////////////////////////////
//jQuery asynchronous tests
jQuery.ajaxSetup({ timeout: 0 });
$(document).ajaxError( function() { QUnit.start(); } );
module("jQ Async Manual");
test("testI32", function() {
expect( 2 );
QUnit.stop();
var transport = new Thrift.Transport();
var protocol = new Thrift.Protocol(transport);
var client = new ThriftTest.ThriftTestClient(protocol);
var jqxhr = jQuery.ajax({
url: "/service",
data: client.send_testI32(Math.pow(-2,31)),
type: "POST",
cache: false,
dataType: "text",
success: function(res){
transport.setRecvBuffer( res );
equal(client.recv_testI32(), Math.pow(-2,31));
},
error: function() { ok(false); },
complete: function() {
ok(true);
QUnit.start();
}
});
});
test("testI64", function() {
expect( 2 );
QUnit.stop();
var transport = new Thrift.Transport();
var protocol = new Thrift.Protocol(transport);
var client = new ThriftTest.ThriftTestClient(protocol);
jQuery.ajax({
url: "/service",
//This is usually 2^61 but JS cannot represent anything over 2^52 accurately
data: client.send_testI64(Math.pow(-2,52)),
type: "POST",
cache: false,
dataType: "text",
success: function(res){
transport.setRecvBuffer( res );
//This is usually 2^61 but JS cannot represent anything over 2^52 accurately
equal(client.recv_testI64(), Math.pow(-2,52));
},
error: function() { ok(false); },
complete: function() {
ok(true);
QUnit.start();
}
});
});
module("jQ Async");
test("I32", function() {
expect( 3 );
QUnit.stop();
client.testI32(Math.pow(2,30), function(result) {
equal(result, Math.pow(2,30));
QUnit.start();
});
QUnit.stop();
var jqxhr = client.testI32(Math.pow(-2,31), function(result) {
equal(result, Math.pow(-2,31));
});
jqxhr.success(function(result) {
equal(result, Math.pow(-2,31));
QUnit.start();
});
});
test("I64", function() {
expect( 4 );
QUnit.stop();
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
client.testI64(Math.pow(2,52), function(result) {
equal(result, Math.pow(2,52));
QUnit.start();
});
QUnit.stop();
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
client.testI64(Math.pow(-2,52), function(result) {
equal(result, Math.pow(-2,52));
})
.error( function(xhr, status, e) { ok(false, e.message); } )
.success(function(result) {
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
equal(result, Math.pow(-2,52));
})
.complete(function() {
ok(true);
QUnit.start();
});
});
test("Xception", function() {
expect( 2 );
QUnit.stop();
var dfd = client.testException("Xception", function(result) {
ok(false);
QUnit.start();
})
.error(function(xhr, status, e){
equal(e.errorCode, 1001);
equal(e.message, "Xception");
//QUnit.start();
//Note start is not required here because:
//$(document).ajaxError( function() { QUnit.start(); } );
});
});

View file

@ -0,0 +1,52 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Thrift Javascript Bindings: Unit Test</title>
<script src="build/js/thrift.js" type="text/javascript" charset="utf-8"></script>
<script src="gen-js/ThriftTest_types.js" type="text/javascript" charset="utf-8"></script>
<script src="gen-js/ThriftTest.js" type="text/javascript" charset="utf-8"></script>
<!-- QUnit Test framework-->
<script type="text/javascript" src="build/js/lib/qunit.js" charset="utf-8"></script>
<link rel="stylesheet" href="build/js/lib/qunit.css" type="text/css" media="screen" />
<!-- the Test Suite-->
<script type="text/javascript" src="test.js" charset="utf-8"></script>
<script type="text/javascript" src="test-nojq.js" charset="utf-8"></script>
</head>
<body>
<h1 id="qunit-header">Thrift Javascript Bindings: Unit Test (<a href="https://git-wip-us.apache.org/repos/asf?p=thrift.git;a=blob;f=test/ThriftTest.thrift;hb=HEAD">ThriftTest.thrift</a>)</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"><li><!-- get valid xhtml strict--></li></ol>
<!-- Uncomment this to check the validity. This significantly slows down the test.
<p>
<a href="http://validator.w3.org/check/referer"><img
src="http://www.w3.org/Icons/valid-xhtml10"
alt="Valid XHTML 1.0!" height="31" width="88" /></a>
</p>
-->
</body>
</html>

View file

@ -0,0 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* jshint -W100 */
/*
* JavaScript test suite for ThriftTest.thrift. These tests
* will run only with normal "-gen js" Apache Thrift interfaces.
* To create client code:
* $ thrift -gen js ThriftTest.thrift
*
* See also:
* ++ test.js for generic tests
* ++ test-jq.js for "-gen js:jquery" only tests
*/
//////////////////////////////////
//Async exception tests
module("NojQ Async");
test("Xception", function() {
expect( 2 );
QUnit.stop();
client.testException("Xception", function(result) {
equal(result.errorCode, 1001);
equal(result.message, "Xception");
QUnit.start();
});
});

59
vendor/git.apache.org/thrift.git/lib/js/test/test.html generated vendored Executable file
View file

@ -0,0 +1,59 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Thrift Javascript Bindings: Unit Test</title>
<script src="build/js/thrift.js" type="text/javascript" charset="utf-8"></script>
<script src="gen-js/ThriftTest_types.js" type="text/javascript" charset="utf-8"></script>
<script src="gen-js/ThriftTest.js" type="text/javascript" charset="utf-8"></script>
<!-- jQuery -->
<script type="text/javascript" src="build/js/lib/jquery.js" charset="utf-8"></script>
<!-- QUnit Test framework-->
<script type="text/javascript" src="build/js/lib/qunit.js" charset="utf-8"></script>
<link rel="stylesheet" href="build/js/lib/qunit.css" type="text/css" media="screen" />
<!-- the Test Suite-->
<script>
var transport = new Thrift.Transport("/service");
var protocol = new Thrift.Protocol(transport);
var client = new ThriftTest.ThriftTestClient(protocol);
</script>
<script type="text/javascript" src="test.js" charset="utf-8"></script>
<script type="text/javascript" src="test-jq.js" charset="utf-8"></script>
</head>
<body>
<h1 id="qunit-header">Thrift Javascript Bindings: Unit Test (<a href="https://git-wip-us.apache.org/repos/asf?p=thrift.git;a=blob;f=test/ThriftTest.thrift;hb=HEAD">ThriftTest.thrift</a>)</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"><li><!-- get valid xhtml strict--></li></ol>
<!-- Uncomment this to check the validity. This significantly slows down the test.
<p>
<a href="http://validator.w3.org/check/referer"><img
src="http://www.w3.org/Icons/valid-xhtml10"
alt="Valid XHTML 1.0!" height="31" width="88" /></a>
</p>
-->
</body>
</html>

412
vendor/git.apache.org/thrift.git/lib/js/test/test.js generated vendored Executable file
View file

@ -0,0 +1,412 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* jshint -W100 */
/*
* JavaScript test suite for ThriftTest.thrift. These tests
* will run against Normal (-gen js) and jQuery (-gen js:jquery)
* Apache Thrift interfaces.
*
* Synchronous blocking calls should be identical in both
* Normal and jQuery interfaces. All synchronous tests belong
* here.
*
* Asynchronous success callbacks passed as the last parameter
* of an RPC call should be identical in both Normal and jQuery
* interfaces. Async success tests belong here.
*
* Asynchronous exception processing is different in Normal
* and jQuery interfaces. Such tests belong in the test-nojq.js
* or test-jq.js files respectively. jQuery specific XHR object
* tests also belong in test-jq.js. Do not create any jQuery
* dependencies in this file or in test-nojq.js
*
* To compile client code for this test use:
* $ thrift -gen js ThriftTest.thrift
* -- or --
* $ thrift -gen js:jquery ThriftTest.thrift
*
* See also:
* ++ test-nojq.js for "-gen js" only tests
* ++ test-jq.js for "-gen js:jquery" only tests
*/
var transport = new Thrift.Transport("/service");
var protocol = new Thrift.Protocol(transport);
var client = new ThriftTest.ThriftTestClient(protocol);
// Work around for old API used by QUnitAdapter of jsTestDriver
if (typeof QUnit.log == 'function') {
// When using real QUnit (fron PhantomJS) log failures to console
QUnit.log(function(details) {
if (!details.result) {
console.log('======== FAIL ========');
console.log('TestName: ' + details.name);
if (details.message) console.log(details.message);
console.log('Expected: ' + details.expected);
console.log('Actual : ' + details.actual);
console.log('======================');
}
});
}
// all Languages in UTF-8
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ú, 粵語";
function checkRecursively(map1, map2) {
if (typeof map1 !== 'function' && typeof map2 !== 'function') {
if (!map1 || typeof map1 !== 'object') {
equal(map1, map2);
} else {
for (var key in map1) {
checkRecursively(map1[key], map2[key]);
}
}
}
}
module("Base Types");
test("Void", function() {
equal(client.testVoid(), undefined);
});
test("Binary (String)", function() {
var binary = '';
for (var v = 255; v >= 0; --v) {
binary += String.fromCharCode(v);
}
equal(client.testBinary(binary), binary);
});
test("Binary (Uint8Array)", function() {
var binary = '';
for (var v = 255; v >= 0; --v) {
binary += String.fromCharCode(v);
}
var arr = new Uint8Array(binary.length);
for (var i = 0; i < binary.length; ++i) {
arr[i] = binary[i].charCodeAt();
}
equal(client.testBinary(arr), binary);
});
test("String", function() {
equal(client.testString(''), '');
equal(client.testString(stringTest), stringTest);
var specialCharacters = 'quote: \" backslash:' +
' forwardslash-escaped: \/ ' +
' backspace: \b formfeed: \f newline: \n return: \r tab: ' +
' now-all-of-them-together: "\\\/\b\n\r\t' +
' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><';
equal(client.testString(specialCharacters),specialCharacters);
});
test("Double", function() {
equal(client.testDouble(0), 0);
equal(client.testDouble(-1), -1);
equal(client.testDouble(3.14), 3.14);
equal(client.testDouble(Math.pow(2,60)), Math.pow(2,60));
});
test("Byte", function() {
equal(client.testByte(0), 0);
equal(client.testByte(0x01), 0x01);
});
test("I32", function() {
equal(client.testI32(0), 0);
equal(client.testI32(Math.pow(2,30)), Math.pow(2,30));
equal(client.testI32(-Math.pow(2,30)), -Math.pow(2,30));
});
test("I64", function() {
equal(client.testI64(0), 0);
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
equal(client.testI64(Math.pow(2,52)), Math.pow(2,52));
equal(client.testI64(-Math.pow(2,52)), -Math.pow(2,52));
});
module("Structured Types");
test("Struct", function() {
var structTestInput = new ThriftTest.Xtruct();
structTestInput.string_thing = 'worked';
structTestInput.byte_thing = 0x01;
structTestInput.i32_thing = Math.pow(2,30);
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
structTestInput.i64_thing = Math.pow(2,52);
var structTestOutput = client.testStruct(structTestInput);
equal(structTestOutput.string_thing, structTestInput.string_thing);
equal(structTestOutput.byte_thing, structTestInput.byte_thing);
equal(structTestOutput.i32_thing, structTestInput.i32_thing);
equal(structTestOutput.i64_thing, structTestInput.i64_thing);
equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput));
});
test("Nest", function() {
var xtrTestInput = new ThriftTest.Xtruct();
xtrTestInput.string_thing = 'worked';
xtrTestInput.byte_thing = 0x01;
xtrTestInput.i32_thing = Math.pow(2,30);
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
xtrTestInput.i64_thing = Math.pow(2,52);
var nestTestInput = new ThriftTest.Xtruct2();
nestTestInput.byte_thing = 0x02;
nestTestInput.struct_thing = xtrTestInput;
nestTestInput.i32_thing = Math.pow(2,15);
var nestTestOutput = client.testNest(nestTestInput);
equal(nestTestOutput.byte_thing, nestTestInput.byte_thing);
equal(nestTestOutput.struct_thing.string_thing, nestTestInput.struct_thing.string_thing);
equal(nestTestOutput.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing);
equal(nestTestOutput.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing);
equal(nestTestOutput.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing);
equal(nestTestOutput.i32_thing, nestTestInput.i32_thing);
equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput));
});
test("Map", function() {
var mapTestInput = {7:77, 8:88, 9:99};
var mapTestOutput = client.testMap(mapTestInput);
for (var key in mapTestOutput) {
equal(mapTestOutput[key], mapTestInput[key]);
}
});
test("StringMap", function() {
var mapTestInput = {
"a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key",
"longValue":stringTest, stringTest:"long key"
};
var mapTestOutput = client.testStringMap(mapTestInput);
for (var key in mapTestOutput) {
equal(mapTestOutput[key], mapTestInput[key]);
}
});
test("Set", function() {
var setTestInput = [1,2,3];
ok(client.testSet(setTestInput), setTestInput);
});
test("List", function() {
var listTestInput = [1,2,3];
ok(client.testList(listTestInput), listTestInput);
});
test("Enum", function() {
equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE);
});
test("TypeDef", function() {
equal(client.testTypedef(69), 69);
});
test("Skip", function() {
var structTestInput = new ThriftTest.Xtruct();
var modifiedClient = new ThriftTest.ThriftTestClient(protocol);
modifiedClient.recv_testStruct = function() {
var input = modifiedClient.input;
var xtruct3 = new ThriftTest.Xtruct3();
input.readMessageBegin();
input.readStructBegin();
// read Xtruct data with Xtruct3
input.readFieldBegin();
xtruct3.read(input);
input.readFieldEnd();
// read Thrift.Type.STOP message
input.readFieldBegin();
input.readFieldEnd();
input.readStructEnd();
input.readMessageEnd();
return xtruct3;
};
structTestInput.string_thing = 'worked';
structTestInput.byte_thing = 0x01;
structTestInput.i32_thing = Math.pow(2,30);
structTestInput.i64_thing = Math.pow(2,52);
var structTestOutput = modifiedClient.testStruct(structTestInput);
equal(structTestOutput instanceof ThriftTest.Xtruct3, true);
equal(structTestOutput.string_thing, structTestInput.string_thing);
equal(structTestOutput.changed, null);
equal(structTestOutput.i32_thing, structTestInput.i32_thing);
equal(structTestOutput.i64_thing, structTestInput.i64_thing);
});
module("deeper!");
test("MapMap", function() {
var mapMapTestExpectedResult = {
"4":{"1":1,"2":2,"3":3,"4":4},
"-4":{"-4":-4, "-3":-3, "-2":-2, "-1":-1}
};
var mapMapTestOutput = client.testMapMap(1);
for (var key in mapMapTestOutput) {
for (var key2 in mapMapTestOutput[key]) {
equal(mapMapTestOutput[key][key2], mapMapTestExpectedResult[key][key2]);
}
}
checkRecursively(mapMapTestOutput, mapMapTestExpectedResult);
});
module("Exception");
test("Xception", function() {
expect(2);
try{
client.testException("Xception");
}catch(e){
equal(e.errorCode, 1001);
equal(e.message, "Xception");
}
});
test("no Exception", 0, function() {
try{
client.testException("no Exception");
}catch(e){
ok(false);
}
});
test("TException", function() {
//ThriftTest does not list TException as a legal exception so it will
// generate an exception on the server that does not propagate back to
// the client. This test has been modified to equate to "no exception"
expect(1);
try{
client.testException("TException");
} catch(e) {
//ok(false);
}
ok(true);
});
module("Insanity");
var crazy = {
"userMap":{ "5":5, "8":8 },
"xtructs":[{
"string_thing":"Goodbye4",
"byte_thing":4,
"i32_thing":4,
"i64_thing":4
},
{
"string_thing":"Hello2",
"byte_thing":2,
"i32_thing":2,
"i64_thing":2
}]
};
test("testInsanity", function() {
var insanity = {
"1":{
"2":crazy,
"3":crazy
},
"2":{ "6":{ "userMap":null, "xtructs":null } }
};
var res = client.testInsanity(new ThriftTest.Insanity(crazy));
ok(res, JSON.stringify(res));
ok(insanity, JSON.stringify(insanity));
checkRecursively(res, insanity);
});
//////////////////////////////////
//Run same tests asynchronously
module("Async");
test("Double", function() {
expect( 1 );
QUnit.stop();
client.testDouble(3.14159265, function(result) {
equal(result, 3.14159265);
QUnit.start();
});
});
test("Byte", function() {
expect( 1 );
QUnit.stop();
client.testByte(0x01, function(result) {
equal(result, 0x01);
QUnit.start();
});
});
test("I32", function() {
expect( 2 );
QUnit.stop();
client.testI32(Math.pow(2,30), function(result) {
equal(result, Math.pow(2,30));
QUnit.start();
});
QUnit.stop();
client.testI32(Math.pow(-2,31), function(result) {
equal(result, Math.pow(-2,31));
QUnit.start();
});
});
test("I64", function() {
expect( 2 );
QUnit.stop();
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
client.testI64(Math.pow(2,52), function(result) {
equal(result, Math.pow(2,52));
QUnit.start();
});
QUnit.stop();
//This is usually 2^60 but JS cannot represent anything over 2^52 accurately
client.testI64(Math.pow(-2,52), function(result) {
equal(result, Math.pow(-2,52));
QUnit.start();
});
});

View file

@ -0,0 +1,199 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* 'License'); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//This is the server side Node test handler for the standard
// Apache Thrift test service.
var ttypes = require('./gen-nodejs/ThriftTest_types');
var TException = require('../../nodejs/lib/thrift').TException;
var ThriftTestHandler = exports.ThriftTestHandler = {
testVoid: function(result) {
console.log('testVoid()');
result(null);
},
testString: function(thing, result) {
console.log('testString(\'' + thing + '\')');
result(null, thing);
},
testByte: function(thing, result) {
console.log('testByte(' + thing + ')');
result(null, thing);
},
testI32: function(thing, result) {
console.log('testI32(' + thing + ')');
result(null, thing);
},
testI64: function(thing, result) {
console.log('testI64(' + thing + ')');
result(null, thing);
},
testDouble: function(thing, result) {
console.log('testDouble(' + thing + ')');
result(null, thing);
},
testBinary: function(thing, result) {
console.log('testBinary(\'' + thing + '\')');
result(null, thing);
},
testStruct: function(thing, result) {
console.log('testStruct(');
console.log(thing);
console.log(')');
result(null, thing);
},
testNest: function(nest, result) {
console.log('testNest(');
console.log(nest);
console.log(')');
result(null, nest);
},
testMap: function(thing, result) {
console.log('testMap(');
console.log(thing);
console.log(')');
result(null, thing);
},
testStringMap: function(thing, result) {
console.log('testStringMap(');
console.log(thing);
console.log(')');
result(null, thing);
},
testSet: function(thing, result) {
console.log('testSet(');
console.log(thing);
console.log(')');
result(null, thing);
},
testList: function(thing, result) {
console.log('testList(');
console.log(thing);
console.log(')');
result(null, thing);
},
testEnum: function(thing, result) {
console.log('testEnum(' + thing + ')');
result(null, thing);
},
testTypedef: function(thing, result) {
console.log('testTypedef(' + thing + ')');
result(null, thing);
},
testMapMap: function(hello, result) {
console.log('testMapMap(' + hello + ')');
var mapmap = [];
var pos = [];
var neg = [];
for (var i = 1; i < 5; i++) {
pos[i] = i;
neg[-i] = -i;
}
mapmap[4] = pos;
mapmap[-4] = neg;
result(null, mapmap);
},
testInsanity: function(argument, result) {
console.log('testInsanity(');
console.log(argument);
console.log(')');
var hello = new ttypes.Xtruct();
hello.string_thing = 'Hello2';
hello.byte_thing = 2;
hello.i32_thing = 2;
hello.i64_thing = 2;
var goodbye = new ttypes.Xtruct();
goodbye.string_thing = 'Goodbye4';
goodbye.byte_thing = 4;
goodbye.i32_thing = 4;
goodbye.i64_thing = 4;
var crazy = new ttypes.Insanity();
crazy.userMap = [];
crazy.userMap[ttypes.Numberz.EIGHT] = 8;
crazy.userMap[ttypes.Numberz.FIVE] = 5;
crazy.xtructs = [goodbye, hello];
var first_map = [];
var second_map = [];
first_map[ttypes.Numberz.TWO] = crazy;
first_map[ttypes.Numberz.THREE] = crazy;
var looney = new ttypes.Insanity();
second_map[ttypes.Numberz.SIX] = looney;
var insane = [];
insane[1] = first_map;
insane[2] = second_map;
console.log('insane result:');
console.log(insane);
result(null, insane);
},
testMulti: function(arg0, arg1, arg2, arg3, arg4, arg5, result) {
console.log('testMulti()');
var hello = new ttypes.Xtruct();
hello.string_thing = 'Hello2';
hello.byte_thing = arg0;
hello.i32_thing = arg1;
hello.i64_thing = arg2;
result(null, hello);
},
testException: function(arg, result) {
console.log('testException('+arg+')');
if (arg === 'Xception') {
var x = new ttypes.Xception();
x.errorCode = 1001;
x.message = arg;
result(x);
} else if (arg === 'TException') {
result(new TException(arg));
} else {
result(null);
}
},
testMultiException: function(arg0, arg1, result) {
console.log('testMultiException(' + arg0 + ', ' + arg1 + ')');
if (arg0 === ('Xception')) {
var x = new ttypes.Xception();
x.errorCode = 1001;
x.message = 'This is an Xception';
result(x);
} else if (arg0 === ('Xception2')) {
var x2 = new ttypes.Xception2();
x2.errorCode = 2002;
x2.struct_thing = new ttypes.Xtruct();
x2.struct_thing.string_thing = 'This is an Xception2';
result(x2);
}
var res = new ttypes.Xtruct();
res.string_thing = arg1;
result(null, res);
},
testOneway: function(sleepFor, result) {
console.log('testOneway(' + sleepFor + ') => JavaScript (like Rust) never sleeps!');
}
}; //ThriftTestSvcHandler

View file

@ -0,0 +1,62 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Thrift Javascript Bindings: Unit Test</title>
<script src="build/js/thrift.js" type="text/javascript" charset="utf-8"></script>
<script src="gen-js/ThriftTest_types.js" type="text/javascript" charset="utf-8"></script>
<script src="gen-js/ThriftTest.js" type="text/javascript" charset="utf-8"></script>
<!-- jQuery -->
<script type="text/javascript" src="build/js/lib/jquery.js" charset="utf-8"></script>
<!-- QUnit Test framework-->
<script type="text/javascript" src="build/js/lib/qunit.js" charset="utf-8"></script>
<link rel="stylesheet" href="build/js/lib/qunit.css" type="text/css" media="screen" />
<!-- the Test Suite-->
<script>
var loc = window.location;
var ws_uri = ((loc.protocol === "https:") ? "wss://" : "ws://") +
loc.hostname + ":" + loc.port + loc.pathname;
var transport = new Thrift.TWebSocketTransport(ws_uri);
var protocol = new Thrift.Protocol(transport);
var client = new ThriftTest.ThriftTestClient(protocol);
transport.open();
</script>
<script type="text/javascript" src="test-async.js" charset="utf-8"></script>
</head>
<body>
<h1 id="qunit-header">Thrift Javascript Bindings: Unit Test (<a href="https://git-wip-us.apache.org/repos/asf?p=thrift.git;a=blob;f=test/ThriftTest.thrift;hb=HEAD">ThriftTest.thrift</a>)</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"><li><!-- get valid xhtml strict--></li></ol>
<!-- Uncomment this to check the validity. This significantly slows down the test.
<p>
<a href="http://validator.w3.org/check/referer"><img
src="http://www.w3.org/Icons/valid-xhtml10"
alt="Valid XHTML 1.0!" height="31" width="88" /></a>
</p>
-->
</body>
</html>