Upgrading dependency to Thrift 0.12.0

This commit is contained in:
Renan DelValle 2018-11-27 18:03:50 -08:00
parent 3e4590dcc0
commit 356978cb42
No known key found for this signature in database
GPG key ID: C240AD6D6F443EC9
1302 changed files with 101701 additions and 26784 deletions

View file

@ -57,6 +57,15 @@ senum seasons {
"Winter"
} ( foo = "bar" )
struct ostr_default {
1: i32 bar;
}
struct ostr_custom {
1: i32 bar;
} (cpp.customostream)
service foo_service {
void foo() ( foo = "bar" )
} (a.b="c")

View file

@ -18,6 +18,7 @@
*/
namespace cpp yozone
namespace erl consts_
struct thing {
1: i32 hello,

View file

@ -0,0 +1,17 @@
namespace java thrift.test
namespace cpp thrift.test
// more tests on double constants (precision and type checks)
const double DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST = 1
const double DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST = -100
const double DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST = 9223372036854775807
const double DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST = -9223372036854775807
const double DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST = 3.14159265359
const double DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST = 1000000.1
const double DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST = -1000000.1
const double DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST = 1.7e+308
const double DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST = 9223372036854775816.43
const double DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST = -1.7e+308
const double DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST = -9223372036854775816.43
const list<double> DOUBLE_LIST_TEST = [1,-100,100,9223372036854775807,-9223372036854775807,3.14159265359,1000000.1,-1000000.1,1.7e+308,-1.7e+308,9223372036854775816.43,-9223372036854775816.43]

View file

@ -0,0 +1,46 @@
/*
* 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.
*/
namespace java thrift.test.enumcontainers
enum GreekGodGoddess {
ARES,
APHRODITE,
ZEUS,
POSEIDON,
HERA,
}
typedef GreekGodGoddess GreekGodGoddessType
typedef i32 Power
struct GodBean {
1: optional map<GreekGodGoddessType, Power> power,
2: optional set<GreekGodGoddessType> goddess,
3: optional map<string, GreekGodGoddess> byAlias,
4: optional set<string> images,
}
const map<GreekGodGoddessType, string> ATTRIBUTES =
{
GreekGodGoddess.ZEUS: "lightning bolt",
GreekGodGoddess.POSEIDON: "trident",
}
const set<GreekGodGoddessType> BEAUTY = [ GreekGodGoddess.APHRODITE, GreekGodGoddess.HERA ]

View file

@ -71,6 +71,11 @@ enum MyEnum5 {
e2 = 42 // fails with 0.9.3 and earlier
}
enum MyEnumWithCustomOstream {
custom1 = 1,
CustoM2
} (cpp.customostream)
struct MyStruct {
1: MyEnum2 me2_2 = MyEnum1.ME2_2
2: MyEnum3 me3_n2 = MyEnum3.ME3_N2

View file

@ -0,0 +1,19 @@
include "JavaTypes.thrift"
namespace java thrift.test
struct DeepCopyFoo {
1: optional list<DeepCopyBar> l,
2: optional set<DeepCopyBar> s,
3: optional map<string, DeepCopyBar> m,
4: optional list<JavaTypes.Object> li,
5: optional set<JavaTypes.Object> si,
6: optional map<string, JavaTypes.Object> mi,
7: optional DeepCopyBar bar,
}
struct DeepCopyBar {
1: optional string a,
2: optional i32 b,
3: optional bool c,
}

View file

@ -96,3 +96,8 @@ service AsyncNonblockingService {
7: Map somemap,
) throws (1:Exception ex);
}
struct SafeBytes {
1: binary bytes;
}

View file

@ -25,6 +25,11 @@ SUBDIRS += c_glib
PRECROSS_TARGET += precross-c_glib
endif
if WITH_CL
SUBDIRS += cl
PRECROSS_TARGET += precross-cl
endif
if WITH_MONO
SUBDIRS += csharp
PRECROSS_TARGET += precross-csharp
@ -72,6 +77,10 @@ if WITH_HAXE
SUBDIRS += haxe
endif
if WITH_DOTNETCORE
SUBDIRS += netcore
endif
if WITH_GO
SUBDIRS += go
PRECROSS_TARGET += precross-go
@ -87,6 +96,11 @@ SUBDIRS += lua
PRECROSS_TARGET += precross-lua
endif
if WITH_RS
SUBDIRS += rs
PRECROSS_TARGET += precross-rs
endif
#
# generate html for ThriftTest.thrift
#
@ -101,6 +115,7 @@ EXTRA_DIST = \
crossrunner \
keys \
c_glib \
cl \
cpp \
dart \
erl \
@ -113,17 +128,20 @@ EXTRA_DIST = \
py.twisted \
py.tornado \
rb \
rs \
threads \
AnnotationTest.thrift \
BrokenConstants.thrift \
ConstantsDemo.thrift \
DebugProtoTest.thrift \
DoubleConstantsTest.thrift \
DenseLinkingTest.thrift \
DocTest.thrift \
EnumTest.thrift \
FullCamelTest.thrift \
Include.thrift \
JavaBeansTest.thrift \
JavaDeepCopyTest.thrift \
JavaTypes.thrift \
JsDeepConstructorTest.thrift \
ManyOptionals.thrift \
@ -132,10 +150,12 @@ EXTRA_DIST = \
OptionalRequiredTest.thrift \
Recursive.thrift \
ReuseObjects.thrift \
EnumContainersTest.thrift \
SmallTest.thrift \
StressTest.thrift \
ThriftTest.thrift \
TypedefTest.thrift \
UnsafeTypes.thrift \
known_failures_Linux.json \
test.py \
tests.json \

View file

@ -37,6 +37,7 @@ namespace delphi Thrift.Test
namespace cocoa ThriftTest
namespace lua ThriftTest
namespace xsd test (uri = 'http://thrift.apache.org/ns/ThriftTest')
namespace netcore ThriftTest
// Presence of namespaces and sub-namespaces for which there is
// no generator should compile with warnings only
@ -320,13 +321,12 @@ service ThriftTest
service SecondService
{
void blahBlah()
/**
* Prints 'testString("%s")' with thing as '%s'
* @param string thing - the string to print
* @return string - returns the string 'thing'
*/
string secondtestString(1: string thing),
string secondtestString(1: string thing)
}
struct VersioningTestV1 {

View file

@ -0,0 +1,24 @@
/*
* 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.
*/
namespace java thrift.test
struct UnsafeBytes {
1: binary bytes;
}

View file

@ -45,6 +45,8 @@ test_client_LDADD = \
test_server_SOURCES = \
src/thrift_test_handler.c \
src/thrift_test_handler.h \
src/thrift_second_service_handler.c \
src/thrift_second_service_handler.h \
src/test_server.c
test_server_LDADD = \
@ -54,8 +56,6 @@ test_server_LDADD = \
#
# Common thrift code generation rules
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-c_glib/t_test_second_service.c gen-c_glib/t_test_second_service.h gen-c_glib/t_test_thrift_test.c gen-c_glib/t_test_thrift_test.h gen-c_glib/t_test_thrift_test_types.c gen-c_glib/t_test_thrift_test_types.h: $(top_srcdir)/test/ThriftTest.thrift $(THRIFT)
$(THRIFT) --gen c_glib -r $<

View file

@ -28,11 +28,14 @@
#include <thrift/c_glib/thrift.h>
#include <thrift/c_glib/protocol/thrift_binary_protocol.h>
#include <thrift/c_glib/protocol/thrift_compact_protocol.h>
#include <thrift/c_glib/protocol/thrift_multiplexed_protocol.h>
#include <thrift/c_glib/transport/thrift_buffered_transport.h>
#include <thrift/c_glib/transport/thrift_framed_transport.h>
#include <thrift/c_glib/transport/thrift_ssl_socket.h>
#include <thrift/c_glib/transport/thrift_socket.h>
#include <thrift/c_glib/transport/thrift_transport.h>
#include "../gen-c_glib/t_test_second_service.h"
#include "../gen-c_glib/t_test_thrift_test.h"
/* Handle SIGPIPE signals (indicating the server has closed the
@ -72,42 +75,82 @@ gint32_compare (gconstpointer a, gconstpointer b)
return result;
}
/**
* It gets a multiplexed protocol which uses a concrete protocol underneath
* @param protocol_name the fully qualified protocol path (e.g. "binary:multi")
* @param transport the underlying transport
* @param service_name the single supported service name
* @todo need to allow multiple services to fully test multiplexed
* @return a multiplexed protocol wrapping the correct underlying protocol
*/
ThriftProtocol *
get_multiplexed_protocol(gchar *protocol_name, ThriftTransport *transport, gchar *service_name)
{
ThriftProtocol * multiplexed_protocol = NULL;
if ( strncmp(protocol_name, "binary:", 7) == 0) {
multiplexed_protocol = g_object_new (THRIFT_TYPE_BINARY_PROTOCOL,
"transport", transport,
NULL);
} else if ( strncmp(protocol_name, "compact:", 8) == 0) {
multiplexed_protocol = g_object_new (THRIFT_TYPE_COMPACT_PROTOCOL,
"transport", transport,
NULL);
} else {
fprintf(stderr, "Unknown multiplex protocol name: %s\n", protocol_name);
return NULL;
}
return g_object_new (THRIFT_TYPE_MULTIPLEXED_PROTOCOL,
"transport", transport,
"protocol", multiplexed_protocol,
"service-name", service_name,
NULL);
}
int
main (int argc, char **argv)
{
static gchar *host = NULL;
static gint port = 9090;
static gchar *transport_option = NULL;
static gchar *protocol_option = NULL;
static gint num_tests = 1;
static gchar * host = NULL;
static gint port = 9090;
static gboolean ssl = FALSE;
static gchar * transport_option = NULL;
static gchar * protocol_option = NULL;
static gint num_tests = 1;
static
GOptionEntry option_entries[] ={
{ "host", 0, 0, G_OPTION_ARG_STRING, &host,
{ "host", 'h', 0, G_OPTION_ARG_STRING, &host,
"Host to connect (=localhost)", NULL },
{ "port", 0, 0, G_OPTION_ARG_INT, &port,
{ "port", 'p', 0, G_OPTION_ARG_INT, &port,
"Port number to connect (=9090)", NULL },
{ "transport", 0, 0, G_OPTION_ARG_STRING, &transport_option,
{ "ssl", 's', 0, G_OPTION_ARG_NONE, &ssl,
"Enable SSL", NULL },
{ "transport", 't', 0, G_OPTION_ARG_STRING, &transport_option,
"Transport: buffered, framed (=buffered)", NULL },
{ "protocol", 0, 0, G_OPTION_ARG_STRING, &protocol_option,
"Protocol: binary, compact (=binary)", NULL },
{ "testloops", 'n', 0, G_OPTION_ARG_INT, &num_tests,
{ "protocol", 'r', 0, G_OPTION_ARG_STRING, &protocol_option,
"Protocol: binary, compact, multi, multic (=binary)", NULL },
{ "testloops", 'n', 0, G_OPTION_ARG_INT, &num_tests,
"Number of tests (=1)", NULL },
{ NULL }
};
struct sigaction sigpipe_action;
GType socket_type = THRIFT_TYPE_SOCKET;
gchar *socket_name = "ip";
GType transport_type = THRIFT_TYPE_BUFFERED_TRANSPORT;
gchar *transport_name = "buffered";
GType protocol_type = THRIFT_TYPE_BINARY_PROTOCOL;
gchar *protocol_name = "binary";
ThriftSocket *socket;
ThriftTransport *transport;
ThriftProtocol *protocol;
ThriftSocket *socket = NULL;
ThriftTransport *transport = NULL;
ThriftProtocol *protocol = NULL;
ThriftProtocol *protocol2 = NULL; // for multiplexed tests
TTestThriftTestIf *test_client;
TTestThriftTestIf *test_client = NULL;
TTestSecondServiceIf *second_service = NULL; // for multiplexed tests
struct timeval time_start, time_stop, time_elapsed;
guint64 time_elapsed_usec, time_total_usec = 0;
@ -147,7 +190,18 @@ main (int argc, char **argv)
protocol_type = THRIFT_TYPE_COMPACT_PROTOCOL;
protocol_name = "compact";
}
else if (strncmp (protocol_option, "binary", 7) != 0) {
else if (strncmp (protocol_option, "multi", 6) == 0) {
protocol_type = THRIFT_TYPE_MULTIPLEXED_PROTOCOL;
protocol_name = "binary:multi";
}
else if (strncmp (protocol_option, "multic", 7) == 0) {
protocol_type = THRIFT_TYPE_MULTIPLEXED_PROTOCOL;
protocol_name = "compact:multic";
}
else if (strncmp (protocol_option, "binary", 7) == 0) {
printf("We are going with default protocol\n");
}
else {
fprintf (stderr, "Unknown protocol type %s\n", protocol_option);
options_valid = FALSE;
}
@ -164,12 +218,19 @@ main (int argc, char **argv)
}
}
if (ssl) {
socket_type = THRIFT_TYPE_SSL_SOCKET;
socket_name = "ip-ssl";
printf("Type name %s\n", g_type_name (socket_type));
}
if (!options_valid)
return 254;
printf ("Connecting (%s/%s) to: %s:%d\n",
printf ("Connecting (%s/%s) to: %s/%s:%d\n",
transport_name,
protocol_name,
socket_name,
host,
port);
@ -181,17 +242,50 @@ main (int argc, char **argv)
sigpipe_action.sa_flags = SA_RESETHAND;
sigaction (SIGPIPE, &sigpipe_action, NULL);
if (ssl) {
thrift_ssl_socket_initialize_openssl();
}
/* Establish all our connection objects */
socket = g_object_new (THRIFT_TYPE_SOCKET,
socket = g_object_new (socket_type,
"hostname", host,
"port", port,
NULL);
if (ssl && !thrift_ssl_load_cert_from_file(THRIFT_SSL_SOCKET(socket), "../keys/CA.pem")) {
fprintf(stderr, "Unable to load validation certificate ../keys/CA.pem - did you run in the test/c_glib directory?\n");
g_clear_object (&socket);
return 253;
}
transport = g_object_new (transport_type,
"transport", socket,
NULL);
protocol = g_object_new (protocol_type,
"transport", transport,
NULL);
if(protocol_type==THRIFT_TYPE_MULTIPLEXED_PROTOCOL) {
// TODO: A multiplexed test should also test "Second" (see Java TestServer)
// The context comes from the name of the thrift file. If multiple thrift
// schemas are used we have to redo the way this is done.
protocol = get_multiplexed_protocol(protocol_name, transport, "ThriftTest");
if (NULL == protocol) {
g_clear_object (&transport);
g_clear_object (&socket);
return 252;
}
// Make a second protocol and client running on the same multiplexed transport
protocol2 = get_multiplexed_protocol(protocol_name, transport, "SecondService");
second_service = g_object_new (T_TEST_TYPE_SECOND_SERVICE_CLIENT,
"input_protocol", protocol2,
"output_protocol", protocol2,
NULL);
}else{
protocol = g_object_new (protocol_type,
"transport", transport,
NULL);
}
test_client = g_object_new (T_TEST_TYPE_THRIFT_TEST_CLIENT,
"input_protocol", protocol,
"output_protocol", protocol,
@ -277,10 +371,11 @@ main (int argc, char **argv)
printf (" = void\n");
}
else {
printf ("%s\n", error->message);
g_error_free (error);
error = NULL;
if(error!=NULL){
printf ("%s\n", error->message);
g_error_free (error);
error = NULL;
}
fail_count++;
}
@ -307,6 +402,31 @@ main (int argc, char **argv)
fail_count++;
}
/**
* Multiplexed Test - do this right in the middle of the normal Test Client run
*/
if (second_service) {
printf ("testSecondServiceMultiplexSecondTestString(\"2nd\")");
if (t_test_second_service_if_secondtest_string (second_service,
&string,
"2nd",
&error)) {
printf (" = \"%s\"\n", string);
if (strcmp (string, "testString(\"2nd\")") != 0) {
++fail_count;
}
g_free (string);
string = NULL;
} else {
printf ("%s\n", error->message);
g_error_free (error);
error = NULL;
++fail_count;
}
}
/**
* BOOL TEST
*/
@ -439,8 +559,105 @@ main (int argc, char **argv)
fail_count++;
}
// TODO: add testBinary()
/**
* BINARY TEST
*/
printf ("testBinary(empty)");
GByteArray *emptyArray = g_byte_array_new();
GByteArray *result = NULL;
if (t_test_thrift_test_if_test_binary (test_client,
&result,
emptyArray,
&error)) {
GBytes *response = g_byte_array_free_to_bytes(result); // frees result
result = NULL;
gsize siz = g_bytes_get_size(response);
if (siz == 0) {
printf(" = empty\n");
} else {
printf(" = not empty (%ld bytes)\n", (long)siz);
++fail_count;
}
g_bytes_unref(response);
} else {
printf ("%s\n", error->message);
g_error_free (error);
error = NULL;
fail_count++;
}
g_byte_array_unref(emptyArray);
emptyArray = NULL;
// TODO: add testBinary() with data
printf ("testBinary([-128..127]) = {");
const signed char bin_data[256]
= {-128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114,
-113, -112, -111, -110, -109, -108, -107, -106, -105, -104, -103, -102, -101, -100, -99,
-98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, -84,
-83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69,
-68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54,
-53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39,
-38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24,
-23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9,
-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
127};
GByteArray *fullArray = g_byte_array_new();
g_byte_array_append(fullArray, (guint8 *)(&bin_data[0]), 256);
if (t_test_thrift_test_if_test_binary (test_client,
&result,
fullArray,
&error)) {
GBytes *response = g_byte_array_free_to_bytes(result); // frees result
result = NULL;
gsize siz = g_bytes_get_size(response);
gconstpointer ptr = g_bytes_get_data(response, &siz);
if (siz == 256) {
gboolean first = 1;
gboolean failed = 0;
int i;
for (i = 0; i < 256; ++i) {
if (!first)
printf(",");
else
first = 0;
int val = ((signed char *)ptr)[i];
printf("%d", val);
if (!failed && val != i - 128) {
failed = 1;
}
}
printf("} ");
if (failed) {
printf("FAIL (bad content) size %ld OK\n", (long)siz);
++fail_count;
} else {
printf("OK size %ld OK\n", (long)siz);
}
} else {
printf(" = bad size %ld\n", (long)siz);
++fail_count;
}
g_bytes_unref(response);
} else {
printf ("%s\n", error->message);
g_error_free (error);
error = NULL;
fail_count++;
}
g_byte_array_unref(fullArray);
fullArray = NULL;
/**
* STRUCT TEST
*/
@ -474,6 +691,11 @@ main (int argc, char **argv)
i32_thing != -3 ||
i64_thing != (gint64)-5)
fail_count++;
if (string) {
g_free (string);
string = NULL;
}
}
else {
printf ("%s\n", error->message);
@ -482,7 +704,8 @@ main (int argc, char **argv)
fail_count++;
}
g_object_unref (xtruct_in);
// g_clear_object(&xtruct_out); used below
g_clear_object(&xtruct_in);
/**
* NESTED STRUCT TEST
@ -525,6 +748,11 @@ main (int argc, char **argv)
inner_i64_thing != (gint64)-5 ||
i32_thing != 5)
fail_count++;
if (string) {
g_free(string);
string = NULL;
}
}
else {
printf ("%s\n", error->message);
@ -534,10 +762,10 @@ main (int argc, char **argv)
fail_count++;
}
g_object_unref (xtruct_in);
g_object_unref (xtruct2_in);
g_object_unref (xtruct2_out);
g_object_unref (xtruct_out);
g_clear_object(&xtruct_in);
g_clear_object(&xtruct2_in);
g_clear_object(&xtruct2_out);
g_clear_object(&xtruct_out);
/**
* MAP TEST
@ -1280,7 +1508,7 @@ main (int argc, char **argv)
}
g_hash_table_unref (map_in);
g_object_unref (insanity_out);
g_clear_object (&insanity_out);
/* test exception */
printf ("testClient.testException(\"Xception\") =>");
@ -1296,8 +1524,7 @@ main (int argc, char **argv)
printf (" {%u, \"%s\"}\n", int32, string);
g_free (string);
g_object_unref (xception);
xception = NULL;
g_clear_object (&xception);
g_error_free (error);
error = NULL;
@ -1333,10 +1560,7 @@ main (int argc, char **argv)
printf (" void\nFAILURE\n");
fail_count++;
if (xception != NULL) {
g_object_unref (xception);
xception = NULL;
}
g_clear_object (&xception);
if (error != NULL) {
g_error_free (error);
@ -1354,10 +1578,7 @@ main (int argc, char **argv)
printf (" void\nFAILURE\n");
fail_count++;
if (xception != NULL) {
g_object_unref (xception);
xception = NULL;
}
g_clear_object (&xception);
g_error_free (error);
error = NULL;
@ -1394,15 +1615,8 @@ main (int argc, char **argv)
printf (" result\nFAILURE\n");
fail_count++;
if (xception != NULL) {
g_object_unref (xception);
xception = NULL;
}
if (xception2 != NULL) {
g_object_unref (xception2);
xception = NULL;
}
g_clear_object (&xception);
g_clear_object (&xception2);
if (error != NULL) {
g_error_free (error);
@ -1432,11 +1646,8 @@ main (int argc, char **argv)
printf (" {%u, {\"%s\"}}\n", int32, string);
g_free (string);
g_object_unref (inner_xtruct_in);
inner_xtruct_in = NULL;
g_object_unref (xception2);
xception2 = NULL;
g_clear_object (&inner_xtruct_in);
g_clear_object (&xception2);
g_error_free (error);
error = NULL;
@ -1445,22 +1656,15 @@ main (int argc, char **argv)
printf (" result\nFAILURE\n");
fail_count++;
if (xception != NULL) {
g_object_unref (xception);
xception = NULL;
}
if (xception2 != NULL) {
g_object_unref (xception2);
xception = NULL;
}
g_clear_object (&xception);
g_clear_object (&xception2);
if (error != NULL) {
g_error_free (error);
error = NULL;
}
}
g_object_unref (xtruct_in);
g_clear_object (&xtruct_in);
printf ("testClient.testMultiException(\"success\", \"test 3\") =>");
xtruct_in = g_object_new (T_TEST_TYPE_XTRUCT, NULL);
@ -1483,22 +1687,15 @@ main (int argc, char **argv)
printf (" result\nFAILURE\n");
fail_count++;
if (xception != NULL) {
g_object_unref (xception);
xception = NULL;
}
if (xception2 != NULL) {
g_object_unref (xception2);
xception = NULL;
}
g_clear_object (&xception);
g_clear_object (&xception2);
if (error != NULL) {
g_error_free (error);
error = NULL;
}
}
g_object_unref (xtruct_in);
g_clear_object (&xtruct_in);
/* test oneway void */
printf ("testClient.testOneway(1) =>");
@ -1584,6 +1781,7 @@ main (int argc, char **argv)
/* All done---output statistics */
puts ("\nAll tests done.");
printf("Number of failures: %d\n", fail_count);
time_avg_usec = time_total_usec / num_tests;
@ -1591,10 +1789,16 @@ main (int argc, char **argv)
printf ("Max time: %" PRIu64 " us\n", time_max_usec);
printf ("Avg time: %" PRIu64 " us\n", time_avg_usec);
g_object_unref (test_client);
g_object_unref (protocol);
g_object_unref (transport);
g_free (host);
g_clear_object(&second_service);
g_clear_object(&protocol2);
g_clear_object(&test_client);
g_clear_object(&protocol);
g_clear_object(&transport);
g_clear_object(&socket);
if (ssl) {
thrift_ssl_socket_finalize_openssl();
}
return fail_count;
}

View file

@ -23,6 +23,7 @@
#include <string.h>
#include <thrift/c_glib/thrift.h>
#include <thrift/c_glib/processor/thrift_multiplexed_processor.h>
#include <thrift/c_glib/protocol/thrift_binary_protocol_factory.h>
#include <thrift/c_glib/protocol/thrift_compact_protocol_factory.h>
#include <thrift/c_glib/server/thrift_server.h>
@ -37,8 +38,10 @@
#include <thrift/c_glib/transport/thrift_transport_factory.h>
#include "../gen-c_glib/t_test_thrift_test.h"
#include "../gen-c_glib/t_test_second_service.h"
#include "thrift_test_handler.h"
#include "thrift_second_service_handler.h"
/* Our server object, declared globally so it is accessible within the SIGINT
signal handler */
@ -96,7 +99,10 @@ main (int argc, char **argv)
GType protocol_factory_type = THRIFT_TYPE_BINARY_PROTOCOL_FACTORY;
TTestThriftTestHandler *handler;
TTestThriftTestHandler *handler_second_service = NULL;
ThriftProcessor *processor;
ThriftProcessor *processor_test = NULL;
ThriftProcessor *processor_second_service = NULL;
ThriftServerTransport *server_transport;
ThriftTransportFactory *transport_factory;
ThriftProtocolFactory *protocol_factory;
@ -138,6 +144,13 @@ main (int argc, char **argv)
protocol_factory_type = THRIFT_TYPE_COMPACT_PROTOCOL_FACTORY;
protocol_name = "compact";
}
else if (strncmp (protocol_option, "multi", 6) == 0) {
protocol_name = "binary:multi";
}
else if (strncmp (protocol_option, "multic", 7) == 0) {
protocol_factory_type = THRIFT_TYPE_COMPACT_PROTOCOL_FACTORY;
protocol_name = "compact:multic";
}
else if (strncmp (protocol_option, "binary", 7) != 0) {
fprintf (stderr, "Unknown protocol type %s\n", protocol_option);
options_valid = FALSE;
@ -161,16 +174,57 @@ main (int argc, char **argv)
/* Establish all our connection objects */
handler = g_object_new (TYPE_THRIFT_TEST_HANDLER,
NULL);
processor = g_object_new (T_TEST_TYPE_THRIFT_TEST_PROCESSOR,
"handler", handler,
NULL);
if(strstr(protocol_name, ":multi")){
/* When a multiplexed processor is involved the handler is not
registered as usual. We create the processor and the real
processor is registered. Multiple processors can be registered
at once. This is why we don't have a constructor property */
processor = g_object_new (THRIFT_TYPE_MULTIPLEXED_PROCESSOR,
NULL);
handler_second_service = g_object_new (TYPE_SECOND_SERVICE_HANDLER,
NULL);
processor_test = g_object_new (T_TEST_TYPE_THRIFT_TEST_PROCESSOR,
"handler", handler,
NULL);
processor_second_service = g_object_new (T_TEST_TYPE_SECOND_SERVICE_PROCESSOR,
"handler", handler_second_service,
NULL);
/* We register a test processor with Multiplexed name ThriftTest */
if(!thrift_multiplexed_processor_register_processor(processor,
"ThriftTest", processor_test,
&error)){
g_message ("thrift_server_serve: %s",
error != NULL ? error->message : "(null)");
g_clear_error (&error);
}
/* We register a second test processor with Multiplexed name SecondService
* we are responsible of freeing the processor when it's not used anymore */
if(!thrift_multiplexed_processor_register_processor(processor,
"SecondService", processor_second_service,
&error)){
g_message ("thrift_server_serve: %s",
error != NULL ? error->message : "(null)");
g_clear_error (&error);
}
}else{
processor = g_object_new (T_TEST_TYPE_THRIFT_TEST_PROCESSOR,
"handler", handler,
NULL);
}
server_transport = g_object_new (THRIFT_TYPE_SERVER_SOCKET,
"port", port,
NULL);
transport_factory = g_object_new (transport_factory_type,
NULL);
if (strncmp (protocol_name, "compact", 8) == 0) {
if (strstr (protocol_name, "compact") != NULL) {
protocol_factory = g_object_new (protocol_factory_type,
"string_limit", string_limit,
"container_limit", container_limit,
@ -222,6 +276,15 @@ main (int argc, char **argv)
g_object_unref (server_transport);
g_object_unref (processor);
g_object_unref (handler);
if(handler_second_service){
g_object_unref (handler_second_service);
}
if(processor_test){
g_object_unref (processor_test);
}
if(processor_second_service){
g_object_unref (processor_second_service);
}
return 0;
}

View file

@ -0,0 +1,69 @@
/*
* 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.
*/
#include <inttypes.h>
#include <string.h>
#include <unistd.h>
#include <thrift/c_glib/thrift.h>
#include <thrift/c_glib/thrift_application_exception.h>
#include "thrift_second_service_handler.h"
/* A handler that implements the TTestSecondServiceIf interface */
G_DEFINE_TYPE (SecondServiceHandler,
second_service_handler,
T_TEST_TYPE_SECOND_SERVICE_HANDLER);
gboolean
second_service_handler_secondtest_string (TTestSecondServiceIf *iface,
gchar **_return,
const gchar *thing,
GError **error)
{
THRIFT_UNUSED_VAR (iface);
THRIFT_UNUSED_VAR (error);
gchar buffer[256];
printf ("testSecondServiceMultiplexSecondTestString(\"%s\")\n", thing);
snprintf(buffer, 255, "testString(\"%s\")", thing);
*_return = g_strdup (buffer);
return TRUE;
}
static void
second_service_handler_init (SecondServiceHandler *self)
{
THRIFT_UNUSED_VAR (self);
}
static void
second_service_handler_class_init (SecondServiceHandlerClass *klass)
{
TTestSecondServiceHandlerClass *base_class =
T_TEST_SECOND_SERVICE_HANDLER_CLASS (klass);
base_class->secondtest_string =
second_service_handler_secondtest_string;
}

View file

@ -0,0 +1,73 @@
/*
* 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.
*/
#ifndef _SECOND_SERVICE_HANDLER_H
#define _SECOND_SERVICE_HANDLER_H
#include <glib-object.h>
#include <stdio.h>
#include "../gen-c_glib/t_test_second_service.h"
G_BEGIN_DECLS
/* A handler that implements the TTestSecondServiceIf interface */
#define TYPE_SECOND_SERVICE_HANDLER (second_service_handler_get_type ())
#define SECOND_SERVICE_HANDLER(obj) \
(G_TYPE_CHECK_INSTANCE_CAST ((obj), \
TYPE_SECOND_SERVICE_HANDLER, \
SecondServiceHandler))
#define IS_SECOND_SERVICE_HANDLER(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE ((obj), \
TYPE_SECOND_SERVICE_HANDLER))
#define SECOND_SERVICE_HANDLER_CLASS(c) \
(G_TYPE_CHECK_CLASS_CAST ((c), \
TYPE_SECOND_SERVICE_HANDLER, \
SecondServiceHandlerClass))
#define IS_SECOND_SERVICE_HANDLER_CLASS(c) \
(G_TYPE_CHECK_CLASS_TYPE ((c), \
TYPE_SECOND_SERVICE_HANDLER))
#define SECOND_SERVICE_HANDLER_GET_CLASS(obj) \
(G_TYPE_INSTANCE_GET_CLASS ((obj), \
TYPE_SECOND_SERVICE_HANDLER, \
SecondServiceHandlerClass))
typedef struct _SecondServiceHandler SecondServiceHandler;
typedef struct _SecondServiceHandlerClass SecondServiceHandlerClass;
struct _SecondServiceHandler {
TTestSecondServiceHandler parent;
};
struct _SecondServiceHandlerClass {
TTestSecondServiceHandlerClass parent;
};
/* Used by SECOND_SERVICE_HANDLER_GET_TYPE */
GType second_service_handler_get_type (void);
gboolean second_service_handler_blah_blah (TTestSecondServiceIf *iface, GError **error);
gboolean second_service_handler_secondtest_string (TTestSecondServiceIf *iface, gchar ** _return, const gchar * thing, GError **error);
G_END_DECLS
#endif /* _SECOND_SERVICE_HANDLER_H */

42
vendor/git.apache.org/thrift.git/test/cl/Makefile.am generated vendored Executable file
View file

@ -0,0 +1,42 @@
#
# 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.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
stubs: ../ThriftTest.thrift
$(THRIFT) --gen cl ../ThriftTest.thrift
TestServer: make-test-server.lisp
$(SBCL) --script make-test-server.lisp
TestClient: make-test-client.lisp
$(SBCL) --script make-test-client.lisp
precross: stubs TestServer TestClient
clean-local:
$(RM) -r gen-cl
$(RM) TestServer
$(RM) TestClient
EXTRA_DIST = \
implementation.lisp \
make-test-client.lisp \
make-test-server.lisp \
tests.lisp

View file

@ -0,0 +1,136 @@
(in-package #:thrift.test-implementation)
;;;; Licensed 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.
(defun thrift.test.thrift-test-implementation:test-void ()
(format t "testVoid()~%"))
(defun thrift.test.thrift-test-implementation:test-string (thing)
(format t "testString(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-bool (thing)
(format t "testBool(~a)~%" (if thing "true" "false"))
thing)
(defun thrift.test.thrift-test-implementation:test-byte (thing)
(format t "testByte(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-i32 (thing)
(format t "testI32(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-i64 (thing)
(format t "testI64(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-double (thing)
(format t "testDouble(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-binary (thing)
(format t "testBinary(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-struct (thing)
(format t "testStruct(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-nest (thing)
(format t "testNest(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-map (thing)
(format t "testMap(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-string-map (thing)
(format t "testStringMap(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-set (thing)
(format t "testSet(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-list (thing)
(format t "testList(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-enum (thing)
(format t "testEnum(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-typedef (thing)
(format t "testTypedef(~a)~%" thing)
thing)
(defun thrift.test.thrift-test-implementation:test-map-map (hello)
(format t "testMapMap(~a)~%" hello)
'((-4 . ((-4 . -4) (-3 . -3) (-2 . -2) (-1 . -1))) (4 . ((1 . 1) (2 . 2) (3 . 3) (4 . 4)))))
(defun thrift.test.thrift-test-implementation:test-insanity (argument)
(let ((result `((1 . ((2 . ,argument) (3 . ,argument)))
(2 . ((6 . ,(thrift.test::make-insanity :user-map nil :xtructs nil)))))))
(format t "~a~%" result)
result))
(defun thrift.test.thrift-test-implementation:test-multi (arg0 arg1 arg2 arg3 arg4 arg5)
(declare (ignorable arg3 arg4 arg5))
(format t "testMulti()~%")
(thrift.test:make-xtruct :string-thing "Hello2"
:byte-thing arg0
:i32-thing arg1
:i64-thing arg2))
(defun thrift.test.thrift-test-implementation:test-exception (arg)
(format t "testException(~a)~%" arg)
(cond
((string= arg "Xception") (error 'thrift.test:xception
:error-code 1001
:message arg))
((string= arg "TException") (error 'thrift.test:xception
:error-code 0
:message "Stuff!"))))
(defun thrift.test.thrift-test-implementation:test-multi-exception (arg0 arg1)
(format t "testMultiException(~a, ~a)~%" arg0 arg1)
(cond
((string= arg0 "Xception") (error 'thrift.test:xception
:error-code 1001
:message "This is an Xception"))
((string= arg0 "Xception2") (error 'thrift.test:xception2
:error-code 2002
:struct-thing (thrift.test:make-xtruct :string-thing "This is an Xception2"
:byte-thing 0
:i32-thing 0
:i64-thing 0))))
(thrift.test:make-xtruct :string-thing arg1
:byte-thing 0
:i32-thing 0
:i64-thing 0))
(defun thrift.test.thrift-test-implementation:test-oneway (seconds)
(format t "testOneway(~a): Sleeping...~%" seconds)
(sleep seconds)
(format t "testOneway(~a): done sleeping!~%" seconds))
;;; Removed from the IDL definition.
#+(or)
(defun thrift.test.second-service-implementation:blah-blah ()
(format t "blahBlah()~%"))
(defun thrift.test.second-service-implementation:secondtest-string (thing)
(format t "secondtestString(~a)~%" thing)
(concatenate 'string "testString(\"" thing "\")"))

View file

@ -0,0 +1,93 @@
(in-package #:cl-user)
;;;; Licensed 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.
#+(or) (when (not (boundp 'sb-impl::default-external-format)
(setf sb-impl::default-external-format :UTF-8)))
(require "asdf")
(load (merge-pathnames "../../lib/cl/load-locally.lisp" *load-truename*))
(asdf:load-system :net.didierverna.clon)
(asdf:load-system :fiasco)
(asdf:load-asd (merge-pathnames "gen-cl/ThriftTest/thrift-gen-ThriftTest.asd" *load-truename*))
(asdf:load-system :thrift-gen-thrifttest)
(net.didierverna.clon:nickname-package)
(defpackage #:thrift-cross
(:use #:common-lisp #:fiasco)
(:export #:cross-test))
(in-package #:thrift-cross)
(defparameter *prot* nil)
(load (merge-pathnames "tests.lisp" *load-truename*) :external-format :UTF-8)
(clon:defsynopsis ()
(text :contents "The Common Lisp client for Thrift's cross-language test suite.")
(group (:header "Allowed options:")
(flag :short-name "h" :long-name "help"
:description "Print this help and exit.")
(stropt :long-name "host"
:description "The host to connect to."
:default-value "localhost"
:argument-name "ARG")
(stropt :long-name "port"
:description "Number of the port to listen for connections on."
:default-value "9090"
:argument-name "ARG"
:argument-type :optional)
(stropt :long-name "transport"
:description "Transport: transport to use (\"buffered\", \"framed\")"
:default-value "buffered"
:argument-name "ARG")
(stropt :long-name "protocol"
:description "Protocol: protocol to use (\"binary\", \"multi\")"
:default-value "binary"
:argument-name "ARG")))
(defun main ()
"Entry point for our standalone application."
(clon:make-context)
(when (clon:getopt :short-name "h")
(clon:help)
(clon:exit))
(let ((port "9090")
(host "localhost")
(framed nil)
(multiplexed nil))
(clon:do-cmdline-options (option name value source)
(print (list option name value source))
(if (string= name "host")
(setf host value))
(if (string= name "port")
(setf port value))
(if (string= name "transport")
(cond ((string= value "buffered") (setf framed nil))
((string= value "framed") (setf framed t))
(t (error "Unsupported transport."))))
(if (string= name "protocol")
(cond ((string= value "binary") (setf multiplexed nil))
((string= value "multi") (setf multiplexed t))
(t (error "Unsupported protocol.")))))
(terpri)
(setf *prot* (thrift.implementation::client (puri:parse-uri
(concatenate 'string "thrift://" host ":" port))
:framed framed
:multiplexed multiplexed))
(let ((result (cross-test :multiplexed multiplexed)))
(thrift.implementation::close *prot*)
(clon:exit result))))
(clon:dump "TestClient" main)

View file

@ -0,0 +1,80 @@
(in-package #:cl-user)
;;;; Licensed 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.
(require "asdf")
(load (merge-pathnames "../../lib/cl/load-locally.lisp" *load-truename*))
(asdf:load-system :net.didierverna.clon)
(asdf:load-asd (merge-pathnames "gen-cl/ThriftTest/thrift-gen-ThriftTest.asd" *load-truename*))
(asdf:load-system :thrift-gen-thrifttest)
(load (merge-pathnames "implementation.lisp" *load-truename*))
(net.didierverna.clon:nickname-package)
(clon:defsynopsis ()
(text :contents "The Common Lisp server for Thrift's cross-language test suite.")
(group (:header "Allowed options:")
(flag :short-name "h" :long-name "help"
:description "Print this help and exit.")
(stropt :long-name "port"
:description "Number of the port to listen for connections on."
:default-value "9090"
:argument-name "ARG"
:argument-type :optional)
(stropt :long-name "server-type"
:description "The type of server, currently only \"simple\" is available."
:default-value "simple"
:argument-name "ARG")
(stropt :long-name "transport"
:description "Transport: transport to use (\"buffered\" or \"framed\")"
:default-value "buffered"
:argument-name "ARG")
(stropt :long-name "protocol"
:description "Protocol: protocol to use (\"binary\" or \"multi\")"
:default-value "binary"
:argument-name "ARG")))
(defun main ()
"Entry point for our standalone application."
(clon:make-context)
(when (clon:getopt :short-name "h")
(clon:help)
(clon:exit))
(let ((port "9090")
(framed nil)
(multiplexed nil))
(clon:do-cmdline-options (option name value source)
(print (list option name value source))
(if (string= name "port")
(setf port value))
(if (string= name "transport")
(cond ((string= value "buffered") (setf framed nil))
((string= value "framed") (setf framed t))
(t (error "Unsupported transport."))))
(if (string= name "protocol")
(cond ((string= value "binary") (setf multiplexed nil))
((string= value "multi") (setf multiplexed t))
(t (error "Unsupported protocol.")))))
(terpri)
(let ((services (if multiplexed
(list thrift.test:thrift-test thrift.test:second-service)
thrift.test:thrift-test)))
(thrift:serve (puri:parse-uri (concatenate 'string
"thrift://127.0.0.1:"
port))
services
:framed framed
:multiplexed multiplexed)))
(clon:exit))
(clon:dump "TestServer" main)

240
vendor/git.apache.org/thrift.git/test/cl/tests.lisp generated vendored Normal file
View file

@ -0,0 +1,240 @@
(in-package #:thrift-cross)
;;;; Licensed 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.
;;;; The tests here only make sense in the context of a TestServer
;;;; running and the dynamic variable thrift-cross::*prot*
;;;; being set with a client connection to the TestServer. Normally,
;;;; this is handled in make-test-client.lisp.
;;; Standard Thrift cross-test error codes
(defparameter *test_basetypes* 1)
(defparameter *test_structs* 2)
(defparameter *test_containers* 4)
(defparameter *test_exceptions* 8)
(defparameter *test_unknown* 64)
(defparameter *test_timeout* 128)
(defun cross-test (&key (multiplexed nil))
"The main cross-test runner."
(let ((result nil))
(handler-case
(progn
(unless (run-package-tests :package :base-types)
(pushnew *test_basetypes* result))
(unless (run-package-tests :package :structs)
(pushnew *test_structs* result))
(unless (run-package-tests :package :containers)
(pushnew *test_containers* result))
(unless (run-package-tests :package :exceptions)
(pushnew *test_exceptions* result))
(unless (run-package-tests :package :misc)
(pushnew *test_unknown* result))
;; It doesn't seem like anyone actually uses
;; the second test service when testing multiplexing,
;; so this would fail against servers in other
;; languages. For now, anyway.
#+(or)
(when multiplexed
(unless (run-package-tests :package :multiplex)
(pushnew *test_unknown* result))))
(error (e) (pushnew *test_unknown* result)))
(apply #'+ result)))
(fiasco:define-test-package #:base-types)
(in-package #:base-types)
(defconstant *lang-string* "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, Polski, پنجابی, پښتو, Norfuk / Pitkern, 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ú, 粵語")
(defparameter *trick-string* (format nil "quote: \" backslash: \\ newline: ~% backspace: ~C ~
tab: ~T junk: !@#$%&()(&%$#{}{}<><><" #\backspace))
(defconstant *binary-sequence* #(128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127))
(deftest void-test ()
(is (null (thrift.test.thrift-test:test-void thrift-cross::*prot*))))
(deftest boolean-test ()
(is (thrift.test.thrift-test:test-bool thrift-cross::*prot* t))
(is (not (thrift.test.thrift-test:test-bool thrift-cross::*prot* nil))))
(deftest integer-test ()
(is (= (thrift.test.thrift-test:test-byte thrift-cross::*prot* 127) 127))
(is (= (thrift.test.thrift-test:test-byte thrift-cross::*prot* -128) -128))
(is (= (thrift.test.thrift-test:test-byte thrift-cross::*prot* 42) 42))
(is (= (thrift.test.thrift-test:test-byte thrift-cross::*prot* 0) 0))
(is (= (thrift.test.thrift-test:test-i32 thrift-cross::*prot* 0) 0))
(is (= (thrift.test.thrift-test:test-i32 thrift-cross::*prot* 2147483647) 2147483647))
(is (= (thrift.test.thrift-test:test-i32 thrift-cross::*prot* -2147483648) -2147483648))
(is (= (thrift.test.thrift-test:test-i64 thrift-cross::*prot* 0) 0))
(is (= (thrift.test.thrift-test:test-i64 thrift-cross::*prot* 9223372036854775807) 9223372036854775807))
(is (= (thrift.test.thrift-test:test-i64 thrift-cross::*prot* -9223372036854775808) -9223372036854775808)))
(deftest double-test ()
(is (= (thrift.test.thrift-test:test-double thrift-cross::*prot* 0.0) 0))
(is (= (thrift.test.thrift-test:test-double thrift-cross::*prot* 42.0) 42))
(is (= (thrift.test.thrift-test:test-double thrift-cross::*prot* -555.0) -555))
(is (= (thrift.test.thrift-test:test-double thrift-cross::*prot* -52.3678) -52.3678)))
(deftest string-test ()
(is (string= (thrift.test.thrift-test:test-string thrift-cross::*prot* "") ""))
(is (string= (thrift.test.thrift-test:test-string thrift-cross::*prot* "(defun botsbuildbots () (botsbuilsbots))")
"(defun botsbuildbots () (botsbuilsbots))"))
(is (string= (thrift.test.thrift-test:test-string thrift-cross::*prot* *lang-string*) *lang-string*))
(is (string= (thrift.test.thrift-test:test-string thrift-cross::*prot* *trick-string*) *trick-string*)))
(deftest binary-test ()
(is (equalp (thrift.test.thrift-test:test-binary thrift-cross::*prot* #()) #()))
(is (equalp (thrift.test.thrift-test:test-binary thrift-cross::*prot* *binary-sequence*) *binary-sequence*)))
(deftest enum-test ()
(is (= (thrift.test.thrift-test:test-enum thrift-cross::*prot* thrift.test:numberz.five) thrift.test:numberz.five))
(is (= (thrift.test.thrift-test:test-enum thrift-cross::*prot* thrift.test:numberz.eight) thrift.test:numberz.eight))
(is (= (thrift.test.thrift-test:test-enum thrift-cross::*prot* thrift.test:numberz.one) thrift.test:numberz.one)))
(deftest typedef-test ()
(is (= (thrift.test.thrift-test:test-typedef thrift-cross::*prot* 309858235082523) 309858235082523)))
(fiasco:define-test-package #:structs)
(in-package #:structs)
(defparameter *test-struct* (thrift.test:make-xtruct :string-thing "Hell is empty."
:byte-thing -2
:i32-thing 42
:i64-thing 42424242))
(defparameter *test-nest* (thrift.test:make-xtruct2 :byte-thing 42
:struct-thing *test-struct*
:i32-thing -42))
(deftest struct-test ()
(let ((rec-struct (thrift.test.thrift-test:test-struct thrift-cross::*prot* *test-struct*)))
(is (string= (thrift.test:xtruct-string-thing *test-struct*)
(thrift.test:xtruct-string-thing rec-struct)))
(is (= (thrift.test:xtruct-byte-thing *test-struct*)
(thrift.test:xtruct-byte-thing rec-struct)))
(is (= (thrift.test:xtruct-i32-thing *test-struct*)
(thrift.test:xtruct-i32-thing rec-struct)))
(is (= (thrift.test:xtruct-i64-thing *test-struct*)
(thrift.test:xtruct-i64-thing rec-struct)))))
(deftest nest-test ()
(let* ((rec-nest (thrift.test.thrift-test:test-nest thrift-cross::*prot* *test-nest*))
(rec-struct (thrift.test:xtruct2-struct-thing rec-nest)))
(is (string= (thrift.test:xtruct-string-thing *test-struct*)
(thrift.test:xtruct-string-thing rec-struct)))
(is (= (thrift.test:xtruct-byte-thing *test-struct*)
(thrift.test:xtruct-byte-thing rec-struct)))
(is (= (thrift.test:xtruct-i32-thing *test-struct*)
(thrift.test:xtruct-i32-thing rec-struct)))
(is (= (thrift.test:xtruct-i64-thing *test-struct*)
(thrift.test:xtruct-i64-thing rec-struct)))
(is (= (thrift.test:xtruct2-byte-thing *test-nest*)
(thrift.test:xtruct2-byte-thing rec-nest)))
(is (= (thrift.test:xtruct2-i32-thing *test-nest*)
(thrift.test:xtruct2-i32-thing rec-nest)))))
(fiasco:define-test-package #:containers)
(in-package #:containers)
(deftest list-test ()
(is (null (thrift.test.thrift-test:test-list thrift-cross::*prot* nil)))
(is (equal (thrift.test.thrift-test:test-list thrift-cross::*prot* '(42 -42 0 5)) '(42 -42 0 5))))
(deftest set-test ()
(is (null (thrift.test.thrift-test:test-set thrift-cross::*prot* nil)))
(is (equal (sort (thrift.test.thrift-test:test-set thrift-cross::*prot* (list 42 -42 0 5)) #'<)
'(-42 0 5 42))))
(defun map= (map1 map2 &key (car-predicate #'equal) (cdr-predicate #'equal))
"Compare two assoc maps according to the predicates given."
(not (set-exclusive-or map1 map2 :test (lambda (el1 el2)
(and (funcall car-predicate
(car el1)
(car el2))
(funcall cdr-predicate
(cdr el1)
(cdr el2)))))))
(deftest map-test ()
(is (null (thrift.test.thrift-test:test-map thrift-cross::*prot* nil)))
(is (map= (thrift.test.thrift-test:test-map thrift-cross::*prot* '((0 . 1) (42 . -42) (5 . 5)))
'((0 . 1) (42 . -42) (5 . 5))))
(is (map= (thrift.test.thrift-test:test-map-map thrift-cross::*prot* 42)
'((-4 . ((-4 . -4) (-3 . -3) (-2 . -2) (-1 . -1)))
(4 . ((1 . 1) (2 . 2) (3 . 3) (4 . 4))))
:cdr-predicate #'map=)))
(fiasco:define-test-package #:exceptions)
(in-package #:exceptions)
(defun test-xception (expected-code expected-message function &rest args)
"A helper function to test whether xception is signalled, and whether its fields have the expected values."
(handler-case (progn (apply function args)
nil)
(thrift.test:xception (ex) (and (= (thrift.test::xception-error-code ex) expected-code)
(string= (thrift.test::xception-message ex) expected-message)))))
(defun test-xception2 (expected-code expected-message function &rest args)
"A helper function to test whether xception2 is signalled, and whether its fields have the expected values."
(handler-case (progn (apply function args)
nil)
(thrift.test:xception2 (ex) (and (= (thrift.test::xception2-error-code ex) expected-code)
(string= (thrift.test::xtruct-string-thing
(thrift.test::xception2-struct-thing ex))
expected-message)))))
(deftest exception-test ()
(is (test-xception 1001 "Xception" #'thrift.test.thrift-test:test-exception thrift-cross::*prot* "Xception"))
(signals thrift:application-error (thrift.test.thrift-test:test-exception thrift-cross::*prot* "TException"))
(finishes (thrift.test.thrift-test:test-exception thrift-cross::*prot* "success")))
(deftest multi-exception-test ()
(is (test-xception 1001
"This is an Xception"
#'thrift.test.thrift-test:test-multi-exception
thrift-cross::*prot*
"Xception"
"meaningless"))
(is (test-xception2 2002
"This is an Xception2"
#'thrift.test.thrift-test:test-multi-exception
thrift-cross::*prot*
"Xception2"
"meaningless too!"))
(is (string= "foobar" (thrift.test:xtruct-string-thing
(thrift.test.thrift-test:test-multi-exception thrift-cross::*prot*
"success!"
"foobar")))))
(fiasco:define-test-package #:misc)
(in-package #:misc)
(deftest oneway-test ()
(is (null (thrift.test.thrift-test:test-oneway thrift-cross::*prot* 1))))
(fiasco:define-test-package #:multiplex)
(in-package #:multiplex)
(deftest multiplex-test ()
;; Removed from the IDL definition.
;; (finishes (thrift.test.second-service:blah-blah thrift-cross::*prot*))
(is (string= "asd" (thrift.test.second-service:secondtest-string thrift-cross::*prot* "asd"))))

View file

@ -28,13 +28,16 @@ include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}")
find_package(Libevent REQUIRED) # Libevent comes with CMake support from upstream
include_directories(SYSTEM ${LIBEVENT_INCLUDE_DIRS})
find_package(ZLIB REQUIRED)
include_directories(SYSTEM ${ZLIB_INCLUDE_DIRS})
#Make sure gen-cpp files can be included
include_directories("${CMAKE_CURRENT_BINARY_DIR}")
include_directories("${CMAKE_CURRENT_BINARY_DIR}/gen-cpp")
include_directories("${PROJECT_SOURCE_DIR}/lib/cpp/src")
set(crosstestgencpp_SOURCES
gen-cpp/SecondService.cpp
gen-cpp/ThriftTest.cpp
gen-cpp/ThriftTest_types.cpp
gen-cpp/ThriftTest_constants.cpp
@ -45,7 +48,7 @@ LINK_AGAINST_THRIFT_LIBRARY(crosstestgencpp thrift)
set(crossstressgencpp_SOURCES
gen-cpp/Service.cpp
#gen-cpp/StressTest_types.cpp #basically empty, so omitting
gen-cpp/StressTest_types.cpp
gen-cpp/StressTest_constants.cpp
)
add_library(crossstressgencpp STATIC ${crossstressgencpp_SOURCES})
@ -80,7 +83,7 @@ add_test(NAME StressTestNonBlocking COMMAND StressTestNonBlocking)
# Common thrift code generation rules
#
add_custom_command(OUTPUT gen-cpp/ThriftTest.cpp gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_constants.cpp
add_custom_command(OUTPUT gen-cpp/SecondService.cpp gen-cpp/SecondService.h gen-cpp/ThriftTest.cpp gen-cpp/ThriftTest.h gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_constants.cpp
COMMAND ${THRIFT_COMPILER} --gen cpp:templates,cob_style -r ${PROJECT_SOURCE_DIR}/test/ThriftTest.thrift
)

View file

@ -21,12 +21,16 @@ AUTOMAKE_OPTIONS = subdir-objects serial-tests
BUILT_SOURCES = gen-cpp/ThriftTest.cpp \
gen-cpp/ThriftTest_types.cpp \
gen-cpp/ThriftTest_constants.cpp \
gen-cpp/SecondService.cpp \
gen-cpp/StressTest_types.cpp \
gen-cpp/StressTest_constants.cpp \
gen-cpp/Service.cpp
noinst_LTLIBRARIES = libtestgencpp.la libstresstestgencpp.la
nodist_libtestgencpp_la_SOURCES = \
gen-cpp/SecondService.cpp \
gen-cpp/SecondService.h \
gen-cpp/SecondService.tcc \
gen-cpp/ThriftTest_constants.cpp \
gen-cpp/ThriftTest_constants.h \
gen-cpp/ThriftTest_types.cpp \
@ -98,16 +102,14 @@ StressTestNonBlocking_LDADD = \
#
# Common thrift code generation rules
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-cpp/ThriftTest.cpp gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_constants.cpp: $(top_srcdir)/test/ThriftTest.thrift $(THRIFT)
gen-cpp/ThriftTest.cpp gen-cpp/ThriftTest_types.cpp gen-cpp/ThriftTest_constants.cpp gen-cpp/SecondService.cpp gen-cpp/SecondService.h gen-cpp/SecondService.tcc: $(top_srcdir)/test/ThriftTest.thrift $(THRIFT)
$(THRIFT) --gen cpp:templates,cob_style -r $<
gen-cpp/StressTest_types.cpp gen-cpp/StressTest_constants.cpp gen-cpp/Service.cpp: $(top_srcdir)/test/StressTest.thrift $(THRIFT)
$(THRIFT) --gen cpp $<
AM_CPPFLAGS = $(BOOST_CPPFLAGS) $(LIBEVENT_CPPFLAGS) -I$(top_srcdir)/lib/cpp/src -Igen-cpp
AM_CXXFLAGS = -Wall -Wextra -pedantic
AM_CXXFLAGS = -Wall -Wextra -pedantic -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS
AM_LDFLAGS = $(BOOST_LDFLAGS) $(LIBEVENT_LDFLAGS) $(ZLIB_LIBS)
clean-local:
@ -120,6 +122,4 @@ EXTRA_DIST = \
src/TestClient.cpp \
src/TestServer.cpp \
src/StressTest.cpp \
src/StressTestNonBlocking.cpp \
realloc/realloc_test.c \
realloc/Makefile
src/StressTestNonBlocking.cpp

View file

@ -1,107 +0,0 @@
/*
* 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.
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <dlfcn.h>
int copies;
int non_copies;
void *realloc(void *ptr, size_t size) {
static void *(*real_realloc)(void*, size_t) = NULL;
if (real_realloc == NULL) {
real_realloc = (void* (*) (void*, size_t)) dlsym(RTLD_NEXT, "realloc");
}
void *ret_ptr = (*real_realloc)(ptr, size);
if (ret_ptr == ptr) {
non_copies++;
} else {
copies++;
}
return ret_ptr;
}
struct TMemoryBuffer {
void* ptr;
int size;
};
int main(int argc, char *argv[]) {
int num_buffers;
int init_size;
int max_size;
int doublings;
int iterations;
if (argc < 6 ||
argc > 7 ||
(num_buffers = atoi(argv[1])) == 0 ||
(init_size = atoi(argv[2])) == 0 ||
(max_size = atoi(argv[3])) == 0 ||
init_size > max_size ||
(iterations = atoi(argv[4])) == 0 ||
(doublings = atoi(argv[5])) == 0 ||
(argc == 7 && atoi(argv[6]) == 0)) {
fprintf(stderr, "usage: realloc_test <num_buffers> <init_size> <max_size> <doublings> <iterations> [seed]\n");
exit(EXIT_FAILURE);
}
for ( int i = 0 ; i < argc ; i++ ) {
printf("%s ", argv[i]);
}
printf("\n");
if (argc == 7) {
srand(atoi(argv[6]));
} else {
srand(time(NULL));
}
struct TMemoryBuffer* buffers = calloc(num_buffers, sizeof(*buffers));
if (buffers == NULL) abort();
for ( int i = 0 ; i < num_buffers ; i++ ) {
buffers[i].size = max_size;
}
while (iterations --> 0) {
for ( int i = 0 ; i < doublings * num_buffers ; i++ ) {
struct TMemoryBuffer* buf = &buffers[rand() % num_buffers];
buf->size *= 2;
if (buf->size <= max_size) {
buf->ptr = realloc(buf->ptr, buf->size);
} else {
free(buf->ptr);
buf->size = init_size;
buf->ptr = malloc(buf->size);
}
if (buf->ptr == NULL) abort();
}
}
printf("Non-copied %d/%d (%.2f%%)\n", non_copies, copies + non_copies, 100.0 * non_copies / (copies + non_copies));
return 0;
}

View file

@ -31,6 +31,7 @@
#include <thrift/transport/TTransportUtils.h>
#include <thrift/transport/TFileTransport.h>
#include <thrift/TLogging.h>
#include <thrift/stdcxx.h>
#include "Service.h"
#include <iostream>
@ -107,8 +108,8 @@ enum TransportOpenCloseBehavior {
};
class ClientThread : public Runnable {
public:
ClientThread(boost::shared_ptr<TTransport> transport,
boost::shared_ptr<ServiceIf> client,
ClientThread(stdcxx::shared_ptr<TTransport> transport,
stdcxx::shared_ptr<ServiceIf> client,
Monitor& monitor,
size_t& workerCount,
size_t loopCount,
@ -224,8 +225,8 @@ public:
}
}
boost::shared_ptr<TTransport> _transport;
boost::shared_ptr<ServiceIf> _client;
stdcxx::shared_ptr<TTransport> _transport;
stdcxx::shared_ptr<ServiceIf> _client;
Monitor& _monitor;
size_t& _workerCount;
size_t _loopCount;
@ -285,14 +286,14 @@ int main(int argc, char** argv) {
"server only. Default is " << clientCount << endl
<< "\thelp Prints this help text." << endl
<< "\tcall Service method to call. Default is " << callName << endl
<< "\tloop The number of remote thrift calls each client makes. Default is " << loopCount << endl
<< "\tloop The number of remote thrift calls each client makes. Default is " << loopCount << endl
<< "\tport The port the server and clients should bind to "
"for thrift network connections. Default is " << port << endl
<< "\tserver Run the Thrift server in this process. Default is " << runServer << endl
<< "\tserver Run the Thrift server in this process. Default is " << runServer << endl
<< "\tserver-type Type of server, \"simple\" or \"thread-pool\". Default is " << serverType << endl
<< "\tprotocol-type Type of protocol, \"binary\", \"ascii\", or \"xml\". Default is " << protocolType << endl
<< "\tlog-request Log all request to ./requestlog.tlog. Default is " << logRequests << endl
<< "\treplay-request Replay requests from log file (./requestlog.tlog) Default is " << replayRequests << endl
<< "\tlog-request Log all request to ./requestlog.tlog. Default is " << logRequests << endl
<< "\treplay-request Replay requests from log file (./requestlog.tlog) Default is " << replayRequests << endl
<< "\tworkers Number of thread pools workers. Only valid "
"for thread-pool server type. Default is " << workerCount << endl
<< "\tclient-type Type of client, \"regular\" or \"concurrent\". Default is " << clientType << endl
@ -390,24 +391,24 @@ int main(int argc, char** argv) {
cerr << usage.str();
}
boost::shared_ptr<PlatformThreadFactory> threadFactory
= boost::shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
stdcxx::shared_ptr<PlatformThreadFactory> threadFactory
= stdcxx::shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
// Dispatcher
boost::shared_ptr<Server> serviceHandler(new Server());
stdcxx::shared_ptr<Server> serviceHandler(new Server());
if (replayRequests) {
boost::shared_ptr<Server> serviceHandler(new Server());
boost::shared_ptr<ServiceProcessor> serviceProcessor(new ServiceProcessor(serviceHandler));
stdcxx::shared_ptr<Server> serviceHandler(new Server());
stdcxx::shared_ptr<ServiceProcessor> serviceProcessor(new ServiceProcessor(serviceHandler));
// Transports
boost::shared_ptr<TFileTransport> fileTransport(new TFileTransport(requestLogPath));
stdcxx::shared_ptr<TFileTransport> fileTransport(new TFileTransport(requestLogPath));
fileTransport->setChunkSize(2 * 1024 * 1024);
fileTransport->setMaxEventSize(1024 * 16);
fileTransport->seekToEnd();
// Protocol Factory
boost::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
stdcxx::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TFileProcessor fileProcessor(serviceProcessor, protocolFactory, fileTransport);
@ -417,28 +418,28 @@ int main(int argc, char** argv) {
if (runServer) {
boost::shared_ptr<ServiceProcessor> serviceProcessor(new ServiceProcessor(serviceHandler));
stdcxx::shared_ptr<ServiceProcessor> serviceProcessor(new ServiceProcessor(serviceHandler));
// Transport
boost::shared_ptr<TServerSocket> serverSocket(new TServerSocket(port));
stdcxx::shared_ptr<TServerSocket> serverSocket(new TServerSocket(port));
// Transport Factory
boost::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
stdcxx::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
// Protocol Factory
boost::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
stdcxx::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
if (logRequests) {
// initialize the log file
boost::shared_ptr<TFileTransport> fileTransport(new TFileTransport(requestLogPath));
stdcxx::shared_ptr<TFileTransport> fileTransport(new TFileTransport(requestLogPath));
fileTransport->setChunkSize(2 * 1024 * 1024);
fileTransport->setMaxEventSize(1024 * 16);
transportFactory
= boost::shared_ptr<TTransportFactory>(new TPipedTransportFactory(fileTransport));
= stdcxx::shared_ptr<TTransportFactory>(new TPipedTransportFactory(fileTransport));
}
boost::shared_ptr<TServer> server;
stdcxx::shared_ptr<TServer> server;
if (serverType == "simple") {
@ -452,7 +453,7 @@ int main(int argc, char** argv) {
} else if (serverType == "thread-pool") {
boost::shared_ptr<ThreadManager> threadManager
stdcxx::shared_ptr<ThreadManager> threadManager
= ThreadManager::newSimpleThreadManager(workerCount);
threadManager->threadFactory(threadFactory);
@ -464,9 +465,9 @@ int main(int argc, char** argv) {
threadManager));
}
boost::shared_ptr<TStartObserver> observer(new TStartObserver);
stdcxx::shared_ptr<TStartObserver> observer(new TStartObserver);
server->setServerEventHandler(observer);
boost::shared_ptr<Thread> serverThread = threadFactory->newThread(server);
stdcxx::shared_ptr<Thread> serverThread = threadFactory->newThread(server);
cerr << "Starting the server on port " << port << endl;
@ -485,7 +486,7 @@ int main(int argc, char** argv) {
size_t threadCount = 0;
set<boost::shared_ptr<Thread> > clientThreads;
set<stdcxx::shared_ptr<Thread> > clientThreads;
if (callName == "echoVoid") {
loopType = T_VOID;
@ -504,28 +505,28 @@ int main(int argc, char** argv) {
if(clientType == "regular") {
for (size_t ix = 0; ix < clientCount; ix++) {
boost::shared_ptr<TSocket> socket(new TSocket("127.0.0.1", port));
boost::shared_ptr<TBufferedTransport> bufferedSocket(new TBufferedTransport(socket, 2048));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(bufferedSocket));
boost::shared_ptr<ServiceClient> serviceClient(new ServiceClient(protocol));
stdcxx::shared_ptr<TSocket> socket(new TSocket("127.0.0.1", port));
stdcxx::shared_ptr<TBufferedTransport> bufferedSocket(new TBufferedTransport(socket, 2048));
stdcxx::shared_ptr<TProtocol> protocol(new TBinaryProtocol(bufferedSocket));
stdcxx::shared_ptr<ServiceClient> serviceClient(new ServiceClient(protocol));
clientThreads.insert(threadFactory->newThread(boost::shared_ptr<ClientThread>(
clientThreads.insert(threadFactory->newThread(stdcxx::shared_ptr<ClientThread>(
new ClientThread(socket, serviceClient, monitor, threadCount, loopCount, loopType, OpenAndCloseTransportInThread))));
}
} else if(clientType == "concurrent") {
boost::shared_ptr<TSocket> socket(new TSocket("127.0.0.1", port));
boost::shared_ptr<TBufferedTransport> bufferedSocket(new TBufferedTransport(socket, 2048));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(bufferedSocket));
//boost::shared_ptr<ServiceClient> serviceClient(new ServiceClient(protocol));
boost::shared_ptr<ServiceConcurrentClient> serviceClient(new ServiceConcurrentClient(protocol));
stdcxx::shared_ptr<TSocket> socket(new TSocket("127.0.0.1", port));
stdcxx::shared_ptr<TBufferedTransport> bufferedSocket(new TBufferedTransport(socket, 2048));
stdcxx::shared_ptr<TProtocol> protocol(new TBinaryProtocol(bufferedSocket));
//stdcxx::shared_ptr<ServiceClient> serviceClient(new ServiceClient(protocol));
stdcxx::shared_ptr<ServiceConcurrentClient> serviceClient(new ServiceConcurrentClient(protocol));
socket->open();
for (size_t ix = 0; ix < clientCount; ix++) {
clientThreads.insert(threadFactory->newThread(boost::shared_ptr<ClientThread>(
clientThreads.insert(threadFactory->newThread(stdcxx::shared_ptr<ClientThread>(
new ClientThread(socket, serviceClient, monitor, threadCount, loopCount, loopType, DontOpenAndCloseTransportInThread))));
}
}
for (std::set<boost::shared_ptr<Thread> >::const_iterator thread = clientThreads.begin();
for (std::set<stdcxx::shared_ptr<Thread> >::const_iterator thread = clientThreads.begin();
thread != clientThreads.end();
thread++) {
(*thread)->start();
@ -558,12 +559,12 @@ int main(int argc, char** argv) {
int64_t minTime = 9223372036854775807LL;
int64_t maxTime = 0;
for (set<boost::shared_ptr<Thread> >::iterator ix = clientThreads.begin();
for (set<stdcxx::shared_ptr<Thread> >::iterator ix = clientThreads.begin();
ix != clientThreads.end();
ix++) {
boost::shared_ptr<ClientThread> client
= boost::dynamic_pointer_cast<ClientThread>((*ix)->runnable());
stdcxx::shared_ptr<ClientThread> client
= stdcxx::dynamic_pointer_cast<ClientThread>((*ix)->runnable());
int64_t delta = client->_endTime - client->_startTime;

View file

@ -29,14 +29,14 @@
#include <thrift/server/TNonblockingServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TNonblockingServerSocket.h>
#include <thrift/transport/TTransportUtils.h>
#include <thrift/transport/TFileTransport.h>
#include <thrift/TLogging.h>
#include <thrift/stdcxx.h>
#include "Service.h"
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <set>
#include <stdexcept>
@ -109,8 +109,8 @@ private:
class ClientThread : public Runnable {
public:
ClientThread(boost::shared_ptr<TTransport> transport,
boost::shared_ptr<ServiceClient> client,
ClientThread(stdcxx::shared_ptr<TTransport> transport,
stdcxx::shared_ptr<ServiceClient> client,
Monitor& monitor,
size_t& workerCount,
size_t loopCount,
@ -221,8 +221,8 @@ public:
}
}
boost::shared_ptr<TTransport> _transport;
boost::shared_ptr<ServiceClient> _client;
stdcxx::shared_ptr<TTransport> _transport;
stdcxx::shared_ptr<ServiceClient> _client;
Monitor& _monitor;
size_t& _workerCount;
size_t _loopCount;
@ -344,24 +344,24 @@ int main(int argc, char** argv) {
cerr << usage.str();
}
boost::shared_ptr<PlatformThreadFactory> threadFactory
= boost::shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
stdcxx::shared_ptr<PlatformThreadFactory> threadFactory
= stdcxx::shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
// Dispatcher
boost::shared_ptr<Server> serviceHandler(new Server());
stdcxx::shared_ptr<Server> serviceHandler(new Server());
if (replayRequests) {
boost::shared_ptr<Server> serviceHandler(new Server());
boost::shared_ptr<ServiceProcessor> serviceProcessor(new ServiceProcessor(serviceHandler));
stdcxx::shared_ptr<Server> serviceHandler(new Server());
stdcxx::shared_ptr<ServiceProcessor> serviceProcessor(new ServiceProcessor(serviceHandler));
// Transports
boost::shared_ptr<TFileTransport> fileTransport(new TFileTransport(requestLogPath));
stdcxx::shared_ptr<TFileTransport> fileTransport(new TFileTransport(requestLogPath));
fileTransport->setChunkSize(2 * 1024 * 1024);
fileTransport->setMaxEventSize(1024 * 16);
fileTransport->seekToEnd();
// Protocol Factory
boost::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
stdcxx::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TFileProcessor fileProcessor(serviceProcessor, protocolFactory, fileTransport);
@ -371,45 +371,51 @@ int main(int argc, char** argv) {
if (runServer) {
boost::shared_ptr<ServiceProcessor> serviceProcessor(new ServiceProcessor(serviceHandler));
stdcxx::shared_ptr<ServiceProcessor> serviceProcessor(new ServiceProcessor(serviceHandler));
// Protocol Factory
boost::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
stdcxx::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
// Transport Factory
boost::shared_ptr<TTransportFactory> transportFactory;
stdcxx::shared_ptr<TTransportFactory> transportFactory;
if (logRequests) {
// initialize the log file
boost::shared_ptr<TFileTransport> fileTransport(new TFileTransport(requestLogPath));
stdcxx::shared_ptr<TFileTransport> fileTransport(new TFileTransport(requestLogPath));
fileTransport->setChunkSize(2 * 1024 * 1024);
fileTransport->setMaxEventSize(1024 * 16);
transportFactory
= boost::shared_ptr<TTransportFactory>(new TPipedTransportFactory(fileTransport));
= stdcxx::shared_ptr<TTransportFactory>(new TPipedTransportFactory(fileTransport));
}
boost::shared_ptr<Thread> serverThread;
boost::shared_ptr<Thread> serverThread2;
stdcxx::shared_ptr<Thread> serverThread;
stdcxx::shared_ptr<Thread> serverThread2;
stdcxx::shared_ptr<transport::TNonblockingServerSocket> nbSocket1;
stdcxx::shared_ptr<transport::TNonblockingServerSocket> nbSocket2;
if (serverType == "simple") {
serverThread = threadFactory->newThread(boost::shared_ptr<TServer>(
new TNonblockingServer(serviceProcessor, protocolFactory, port)));
serverThread2 = threadFactory->newThread(boost::shared_ptr<TServer>(
new TNonblockingServer(serviceProcessor, protocolFactory, port + 1)));
nbSocket1.reset(new transport::TNonblockingServerSocket(port));
serverThread = threadFactory->newThread(stdcxx::shared_ptr<TServer>(
new TNonblockingServer(serviceProcessor, protocolFactory, nbSocket1)));
nbSocket2.reset(new transport::TNonblockingServerSocket(port + 1));
serverThread2 = threadFactory->newThread(stdcxx::shared_ptr<TServer>(
new TNonblockingServer(serviceProcessor, protocolFactory, nbSocket2)));
} else if (serverType == "thread-pool") {
boost::shared_ptr<ThreadManager> threadManager
stdcxx::shared_ptr<ThreadManager> threadManager
= ThreadManager::newSimpleThreadManager(workerCount);
threadManager->threadFactory(threadFactory);
threadManager->start();
serverThread = threadFactory->newThread(boost::shared_ptr<TServer>(
new TNonblockingServer(serviceProcessor, protocolFactory, port, threadManager)));
serverThread2 = threadFactory->newThread(boost::shared_ptr<TServer>(
new TNonblockingServer(serviceProcessor, protocolFactory, port + 1, threadManager)));
nbSocket1.reset(new transport::TNonblockingServerSocket(port));
serverThread = threadFactory->newThread(stdcxx::shared_ptr<TServer>(
new TNonblockingServer(serviceProcessor, protocolFactory, nbSocket1, threadManager)));
nbSocket2.reset(new transport::TNonblockingServerSocket(port + 1));
serverThread2 = threadFactory->newThread(stdcxx::shared_ptr<TServer>(
new TNonblockingServer(serviceProcessor, protocolFactory, nbSocket2, threadManager)));
}
cerr << "Starting the server on port " << port << " and " << (port + 1) << endl;
@ -431,7 +437,7 @@ int main(int argc, char** argv) {
size_t threadCount = 0;
set<boost::shared_ptr<Thread> > clientThreads;
set<stdcxx::shared_ptr<Thread> > clientThreads;
if (callName == "echoVoid") {
loopType = T_VOID;
@ -449,16 +455,16 @@ int main(int argc, char** argv) {
for (uint32_t ix = 0; ix < clientCount; ix++) {
boost::shared_ptr<TSocket> socket(new TSocket("127.0.0.1", port + (ix % 2)));
boost::shared_ptr<TFramedTransport> framedSocket(new TFramedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(framedSocket));
boost::shared_ptr<ServiceClient> serviceClient(new ServiceClient(protocol));
stdcxx::shared_ptr<TSocket> socket(new TSocket("127.0.0.1", port + (ix % 2)));
stdcxx::shared_ptr<TFramedTransport> framedSocket(new TFramedTransport(socket));
stdcxx::shared_ptr<TProtocol> protocol(new TBinaryProtocol(framedSocket));
stdcxx::shared_ptr<ServiceClient> serviceClient(new ServiceClient(protocol));
clientThreads.insert(threadFactory->newThread(boost::shared_ptr<ClientThread>(
clientThreads.insert(threadFactory->newThread(stdcxx::shared_ptr<ClientThread>(
new ClientThread(socket, serviceClient, monitor, threadCount, loopCount, loopType))));
}
for (std::set<boost::shared_ptr<Thread> >::const_iterator thread = clientThreads.begin();
for (std::set<stdcxx::shared_ptr<Thread> >::const_iterator thread = clientThreads.begin();
thread != clientThreads.end();
thread++) {
(*thread)->start();
@ -491,12 +497,12 @@ int main(int argc, char** argv) {
int64_t minTime = 9223372036854775807LL;
int64_t maxTime = 0;
for (set<boost::shared_ptr<Thread> >::iterator ix = clientThreads.begin();
for (set<stdcxx::shared_ptr<Thread> >::iterator ix = clientThreads.begin();
ix != clientThreads.end();
ix++) {
boost::shared_ptr<ClientThread> client
= boost::dynamic_pointer_cast<ClientThread>((*ix)->runnable());
stdcxx::shared_ptr<ClientThread> client
= stdcxx::dynamic_pointer_cast<ClientThread>((*ix)->runnable());
int64_t delta = client->_endTime - client->_startTime;

View file

@ -1,4 +1,4 @@
/*
/*
* 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
@ -17,8 +17,6 @@
* under the License.
*/
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <limits>
#include <locale>
#include <ios>
@ -28,29 +26,40 @@
#include <thrift/protocol/TCompactProtocol.h>
#include <thrift/protocol/THeaderProtocol.h>
#include <thrift/protocol/TJSONProtocol.h>
#include <thrift/protocol/TMultiplexedProtocol.h>
#include <thrift/transport/THttpClient.h>
#include <thrift/transport/TTransportUtils.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TSSLSocket.h>
#include <thrift/transport/TZlibTransport.h>
#include <thrift/async/TEvhttpClientChannel.h>
#include <thrift/server/TNonblockingServer.h> // <event.h>
#include <boost/shared_ptr.hpp>
#include <boost/program_options.hpp>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <thrift/cxxfunctional.h>
#include <boost/program_options.hpp>
#include <boost/random/random_device.hpp>
#include <thrift/stdcxx.h>
#if _WIN32
#include <thrift/windows/TWinsockSingleton.h>
#endif
#include "SecondService.h"
#include "ThriftTest.h"
using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::async;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace thrift::test;
using namespace apache::thrift::async;
// Current time, microseconds since the epoch
uint64_t now() {
@ -89,10 +98,10 @@ static void testVoid_clientReturn(event_base* base, ThriftTestCobClient* client)
for (int testNr = 0; testNr < 10; ++testNr) {
std::ostringstream os;
os << "test" << testNr;
client->testString(tcxx::bind(testString_clientReturn,
client->testString(stdcxx::bind(testString_clientReturn,
base,
testNr,
tcxx::placeholders::_1),
stdcxx::placeholders::_1),
os.str());
}
} catch (TException& exn) {
@ -123,16 +132,22 @@ bool print_eq(T expected, T actual) {
return_code |= ERR_BASETYPES; \
}
int binary_test(ThriftTestClient& testClient, string::size_type siz);
BOOST_CONSTEXPR_OR_CONST int ERR_BASETYPES = 1;
BOOST_CONSTEXPR_OR_CONST int ERR_STRUCTS = 2;
BOOST_CONSTEXPR_OR_CONST int ERR_CONTAINERS = 4;
BOOST_CONSTEXPR_OR_CONST int ERR_EXCEPTIONS = 8;
BOOST_CONSTEXPR_OR_CONST int ERR_UNKNOWN = 64;
int main(int argc, char** argv) {
cout.precision(19);
int ERR_BASETYPES = 1;
int ERR_STRUCTS = 2;
int ERR_CONTAINERS = 4;
int ERR_EXCEPTIONS = 8;
int ERR_UNKNOWN = 64;
string testDir = boost::filesystem::system_complete(argv[0]).parent_path().parent_path().parent_path().string();
string pemPath = testDir + "/keys/CA.pem";
string testDir = boost::filesystem::system_complete(argv[0]).parent_path().parent_path().parent_path().string();
string caPath = testDir + "/keys/CA.pem";
string certPath = testDir + "/keys/client.crt";
string keyPath = testDir + "/keys/client.key";
#if _WIN32
transport::TWinsockSingleton::create();
#endif
@ -140,6 +155,7 @@ int main(int argc, char** argv) {
int port = 9090;
int numTests = 1;
bool ssl = false;
bool zlib = false;
string transport_type = "buffered";
string protocol_type = "binary";
string domain_socket = "";
@ -149,28 +165,35 @@ int main(int argc, char** argv) {
int return_code = 0;
boost::program_options::options_description desc("Allowed options");
desc.add_options()("help,h",
"produce help message")("host",
boost::program_options::value<string>(&host)
->default_value(host),
"Host to connect")("port",
boost::program_options::value<int>(
&port)->default_value(port),
"Port number to connect")(
"domain-socket",
boost::program_options::value<string>(&domain_socket)->default_value(domain_socket),
"Domain Socket (e.g. /tmp/ThriftTest.thrift), instead of host and port")(
"abstract-namespace",
"Look for the domain socket in the Abstract Namespace (no connection with filesystem pathnames)")(
"transport",
boost::program_options::value<string>(&transport_type)->default_value(transport_type),
"Transport: buffered, framed, http, evhttp")(
"protocol",
boost::program_options::value<string>(&protocol_type)->default_value(protocol_type),
"Protocol: binary, header, compact, json")("ssl", "Encrypted Transport using SSL")(
"testloops,n",
boost::program_options::value<int>(&numTests)->default_value(numTests),
"Number of Tests")("noinsane", "Do not run insanity test");
desc.add_options()
("help,h", "produce help message")
("host",
boost::program_options::value<string>(&host)->default_value(host),
"Host to connect")
("port",
boost::program_options::value<int>(&port)->default_value(port),
"Port number to connect")
("domain-socket",
boost::program_options::value<string>(&domain_socket)->default_value(domain_socket),
"Domain Socket (e.g. /tmp/ThriftTest.thrift), instead of host and port")
("abstract-namespace",
"Look for the domain socket in the Abstract Namespace"
" (no connection with filesystem pathnames)")
("transport",
boost::program_options::value<string>(&transport_type)->default_value(transport_type),
"Transport: buffered, framed, http, evhttp, zlib")
("protocol",
boost::program_options::value<string>(&protocol_type)->default_value(protocol_type),
"Protocol: binary, compact, header, json, multi, multic, multih, multij")
("ssl",
"Encrypted Transport using SSL")
("zlib",
"Wrap Transport with Zlib")
("testloops,n",
boost::program_options::value<int>(&numTests)->default_value(numTests),
"Number of Tests")
("noinsane",
"Do not run insanity test");
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
@ -187,6 +210,10 @@ int main(int argc, char** argv) {
} else if (protocol_type == "compact") {
} else if (protocol_type == "header") {
} else if (protocol_type == "json") {
} else if (protocol_type == "multi") {
} else if (protocol_type == "multic") {
} else if (protocol_type == "multih") {
} else if (protocol_type == "multij") {
} else {
throw invalid_argument("Unknown protocol type " + protocol_type);
}
@ -197,6 +224,8 @@ int main(int argc, char** argv) {
} else if (transport_type == "framed") {
} else if (transport_type == "http") {
} else if (transport_type == "evhttp") {
} else if (transport_type == "zlib") {
// crosstest will pass zlib as a transport and as a flag right now..
} else {
throw invalid_argument("Unknown transport type " + transport_type);
}
@ -212,6 +241,10 @@ int main(int argc, char** argv) {
ssl = true;
}
if (vm.count("zlib")) {
zlib = true;
}
if (vm.count("abstract-namespace")) {
abstract_namespace = true;
}
@ -220,16 +253,23 @@ int main(int argc, char** argv) {
noinsane = true;
}
boost::shared_ptr<TTransport> transport;
boost::shared_ptr<TProtocol> protocol;
boost::shared_ptr<TSocket> socket;
boost::shared_ptr<TSSLSocketFactory> factory;
// THRIFT-4164: The factory MUST outlive any sockets it creates for correct behavior!
stdcxx::shared_ptr<TSSLSocketFactory> factory;
stdcxx::shared_ptr<TSocket> socket;
stdcxx::shared_ptr<TTransport> transport;
stdcxx::shared_ptr<TProtocol> protocol;
stdcxx::shared_ptr<TProtocol> protocol2; // SecondService for multiplexed
if (ssl) {
factory = boost::shared_ptr<TSSLSocketFactory>(new TSSLSocketFactory());
cout << "Client Certificate File: " << certPath << endl;
cout << "Client Key File: " << keyPath << endl;
cout << "CA File: " << caPath << endl;
factory = stdcxx::shared_ptr<TSSLSocketFactory>(new TSSLSocketFactory());
factory->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
factory->loadTrustedCertificates(pemPath.c_str());
factory->loadTrustedCertificates(caPath.c_str());
factory->loadCertificate(certPath.c_str());
factory->loadPrivateKey(keyPath.c_str());
factory->authenticate(true);
socket = factory->createSocket(host, port);
} else {
@ -237,39 +277,42 @@ int main(int argc, char** argv) {
if (abstract_namespace) {
std::string abstract_socket("\0", 1);
abstract_socket += domain_socket;
socket = boost::shared_ptr<TSocket>(new TSocket(abstract_socket));
socket = stdcxx::shared_ptr<TSocket>(new TSocket(abstract_socket));
} else {
socket = boost::shared_ptr<TSocket>(new TSocket(domain_socket));
socket = stdcxx::shared_ptr<TSocket>(new TSocket(domain_socket));
}
port = 0;
} else {
socket = boost::shared_ptr<TSocket>(new TSocket(host, port));
socket = stdcxx::shared_ptr<TSocket>(new TSocket(host, port));
}
}
if (transport_type.compare("http") == 0) {
boost::shared_ptr<TTransport> httpSocket(new THttpClient(socket, host, "/service"));
transport = httpSocket;
transport = stdcxx::make_shared<THttpClient>(socket, host, "/service");
} else if (transport_type.compare("framed") == 0) {
boost::shared_ptr<TFramedTransport> framedSocket(new TFramedTransport(socket));
transport = framedSocket;
transport = stdcxx::make_shared<TFramedTransport>(socket);
} else {
boost::shared_ptr<TBufferedTransport> bufferedSocket(new TBufferedTransport(socket));
transport = bufferedSocket;
transport = stdcxx::make_shared<TBufferedTransport>(socket);
}
if (protocol_type.compare("json") == 0) {
boost::shared_ptr<TProtocol> jsonProtocol(new TJSONProtocol(transport));
protocol = jsonProtocol;
} else if (protocol_type.compare("compact") == 0) {
boost::shared_ptr<TProtocol> compactProtocol(new TCompactProtocol(transport));
protocol = compactProtocol;
} else if (protocol_type == "header") {
boost::shared_ptr<TProtocol> headerProtocol(new THeaderProtocol(transport));
protocol = headerProtocol;
if (zlib) {
transport = stdcxx::make_shared<TZlibTransport>(transport);
}
if (protocol_type == "json" || protocol_type == "multij") {
protocol = stdcxx::make_shared<TJSONProtocol>(transport);
} else if (protocol_type == "compact" || protocol_type == "multic") {
protocol = stdcxx::make_shared<TCompactProtocol>(transport);
} else if (protocol_type == "header" || protocol_type == "multih") {
protocol = stdcxx::make_shared<THeaderProtocol>(transport);
} else {
boost::shared_ptr<TBinaryProtocol> binaryProtocol(new TBinaryProtocol(transport));
protocol = binaryProtocol;
protocol = stdcxx::make_shared<TBinaryProtocol>(transport);
}
if (boost::starts_with(protocol_type, "multi")) {
protocol2 = stdcxx::make_shared<TMultiplexedProtocol>(protocol, "SecondService");
// we don't need access to the original protocol any more, so...
protocol = stdcxx::make_shared<TMultiplexedProtocol>(protocol, "ThriftTest");
}
// Connection info
@ -291,14 +334,14 @@ int main(int argc, char** argv) {
cout << "Libevent Features: 0x" << hex << event_base_get_features(base) << endl;
#endif
boost::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
stdcxx::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
boost::shared_ptr<TAsyncChannel> channel(
stdcxx::shared_ptr<TAsyncChannel> channel(
new TEvhttpClientChannel(host.c_str(), "/", host.c_str(), port, base));
ThriftTestCobClient* client = new ThriftTestCobClient(channel, protocolFactory.get());
client->testVoid(tcxx::bind(testVoid_clientReturn,
client->testVoid(stdcxx::bind(testVoid_clientReturn,
base,
tcxx::placeholders::_1));
stdcxx::placeholders::_1));
event_base_loop(base, 0);
return 0;
@ -354,7 +397,30 @@ int main(int argc, char** argv) {
return_code |= ERR_BASETYPES;
}
//
// Multiplexed protocol - call another service method
// in the middle of the ThriftTest
//
if (boost::starts_with(protocol_type, "multi")) {
SecondServiceClient ssc(protocol2);
// transport is already open...
try {
cout << "secondService.secondTestString(\"foo\") => " << flush;
std::string result;
ssc.secondtestString(result, "foo");
cout << "{" << result << "}" << endl;
} catch (std::exception& e) {
cout << " *** FAILED *** " << e.what() << endl;
return_code |= ERR_EXCEPTIONS;
}
}
try {
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4566 )
#endif
string str(
"}{Afrikaans, Alemannisch, Aragonés, العربية, مصرى, "
"Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, "
@ -381,6 +447,9 @@ int main(int argc, char** argv) {
"Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, "
"Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, "
"Bân-lâm-gú, 粵語");
#ifdef _MSC_VER
#pragma warning( pop )
#endif
cout << "testString(" << str << ") = " << flush;
testClient.testString(s, str);
cout << s << endl;
@ -457,10 +526,10 @@ int main(int argc, char** argv) {
BASETYPE_IDENTITY_TEST(testI64, (int64_t)-1);
BASETYPE_IDENTITY_TEST(testI64, (int64_t)7000000000000000123LL);
BASETYPE_IDENTITY_TEST(testI64, (int64_t)-7000000000000000123LL);
BASETYPE_IDENTITY_TEST(testI64, (int64_t)pow(2LL, 32));
BASETYPE_IDENTITY_TEST(testI64, (int64_t)-pow(2LL, 32));
BASETYPE_IDENTITY_TEST(testI64, (int64_t)pow(2LL, 32) + 1);
BASETYPE_IDENTITY_TEST(testI64, (int64_t)-pow(2LL, 32) - 1);
BASETYPE_IDENTITY_TEST(testI64, (int64_t)pow(static_cast<double>(2LL), 32));
BASETYPE_IDENTITY_TEST(testI64, (int64_t)-pow(static_cast<double>(2LL), 32));
BASETYPE_IDENTITY_TEST(testI64, (int64_t)pow(static_cast<double>(2LL), 32) + 1);
BASETYPE_IDENTITY_TEST(testI64, (int64_t)-pow(static_cast<double>(2LL), 32) - 1);
BASETYPE_IDENTITY_TEST(testI64, numeric_limits<int64_t>::max());
BASETYPE_IDENTITY_TEST(testI64, numeric_limits<int64_t>::min());
@ -472,19 +541,19 @@ int main(int argc, char** argv) {
BASETYPE_IDENTITY_TEST(testDouble, -1.0);
BASETYPE_IDENTITY_TEST(testDouble, -5.2098523);
BASETYPE_IDENTITY_TEST(testDouble, -0.000341012439638598279);
BASETYPE_IDENTITY_TEST(testDouble, pow(2, 32));
BASETYPE_IDENTITY_TEST(testDouble, pow(2, 32) + 1);
BASETYPE_IDENTITY_TEST(testDouble, pow(2, 53) - 1);
BASETYPE_IDENTITY_TEST(testDouble, -pow(2, 32));
BASETYPE_IDENTITY_TEST(testDouble, -pow(2, 32) - 1);
BASETYPE_IDENTITY_TEST(testDouble, -pow(2, 53) + 1);
BASETYPE_IDENTITY_TEST(testDouble, pow(static_cast<double>(2), 32));
BASETYPE_IDENTITY_TEST(testDouble, pow(static_cast<double>(2), 32) + 1);
BASETYPE_IDENTITY_TEST(testDouble, pow(static_cast<double>(2), 53) - 1);
BASETYPE_IDENTITY_TEST(testDouble, -pow(static_cast<double>(2), 32));
BASETYPE_IDENTITY_TEST(testDouble, -pow(static_cast<double>(2), 32) - 1);
BASETYPE_IDENTITY_TEST(testDouble, -pow(static_cast<double>(2), 53) + 1);
try {
double expected = pow(10, 307);
double expected = pow(static_cast<double>(10), 307);
cout << "testDouble(" << expected << ") = " << flush;
double actual = testClient.testDouble(expected);
cout << "(" << actual << ")" << endl;
if (expected - actual > pow(10, 292)) {
if (expected - actual > pow(static_cast<double>(10), 292)) {
cout << "*** FAILED ***" << endl
<< "Expected: " << expected << " but got: " << actual << endl;
}
@ -496,11 +565,11 @@ int main(int argc, char** argv) {
}
try {
double expected = pow(10, -292);
double expected = pow(static_cast<double>(10), -292);
cout << "testDouble(" << expected << ") = " << flush;
double actual = testClient.testDouble(expected);
cout << "(" << actual << ")" << endl;
if (expected - actual > pow(10, -307)) {
if (expected - actual > pow(static_cast<double>(10), -307)) {
cout << "*** FAILED ***" << endl
<< "Expected: " << expected << " but got: " << actual << endl;
}
@ -514,72 +583,9 @@ int main(int argc, char** argv) {
/**
* BINARY TEST
*/
cout << "testBinary(empty)" << endl;
try {
string bin_result;
testClient.testBinary(bin_result, string());
if (!bin_result.empty()) {
cout << endl << "*** FAILED ***" << endl;
cout << "invalid length: " << bin_result.size() << endl;
return_code |= ERR_BASETYPES;
}
} catch (TTransportException&) {
throw;
} catch (exception& ex) {
cout << "*** FAILED ***" << endl << ex.what() << endl;
return_code |= ERR_BASETYPES;
}
cout << "testBinary([-128..127]) = {" << flush;
const signed char bin_data[256]
= {-128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114,
-113, -112, -111, -110, -109, -108, -107, -106, -105, -104, -103, -102, -101, -100, -99,
-98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, -84,
-83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69,
-68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54,
-53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39,
-38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24,
-23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9,
-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
127};
try {
string bin_result;
testClient.testBinary(bin_result, string(reinterpret_cast<const char *>(bin_data), 256));
if (bin_result.size() != 256) {
cout << endl << "*** FAILED ***" << endl;
cout << "invalid length: " << bin_result.size() << endl;
return_code |= ERR_BASETYPES;
} else {
bool first = true;
bool failed = false;
for (int i = 0; i < 256; ++i) {
if (!first)
cout << ",";
else
first = false;
cout << static_cast<int>(bin_result[i]);
if (!failed && bin_result[i] != i - 128) {
failed = true;
}
}
cout << "}" << endl;
if (failed) {
cout << "*** FAILED ***" << endl;
return_code |= ERR_BASETYPES;
}
}
} catch (TTransportException&) {
throw;
} catch (exception& ex) {
cout << "*** FAILED ***" << endl << ex.what() << endl;
return_code |= ERR_BASETYPES;
for (string::size_type i = 0; i < 131073 && !return_code; ) {
return_code |= binary_test(testClient, i);
if (i > 0) { i *= 2; } else { ++i; }
}
@ -951,7 +957,7 @@ int main(int argc, char** argv) {
failed = true;
} else {
map<Numberz::type, Insanity>::const_iterator it26 = it2->second.find(Numberz::SIX);
if (it26 == it1->second.end() || it26->second != Insanity()) {
if (it26 == it2->second.end() || it26->second != Insanity()) {
failed = true;
}
}
@ -1076,12 +1082,14 @@ int main(int argc, char** argv) {
/**
* I32 TEST
*/
cout << "re-test testI32(-1)";
cout << "re-test testI32(-1)" << flush;
int i32 = testClient.testI32(-1);
cout << " = " << i32 << endl;
if (i32 != -1)
return_code |= ERR_BASETYPES;
cout << endl << "All tests done." << endl << flush;
uint64_t stop = now();
uint64_t tot = stop - start;
@ -1095,10 +1103,10 @@ int main(int argc, char** argv) {
time_max = tot;
}
cout << flush;
transport->close();
}
cout << endl << "All tests done." << endl;
uint64_t time_avg = time_tot / numTests;
@ -1108,3 +1116,66 @@ int main(int argc, char** argv) {
return return_code;
}
void binary_fill(std::string& str, string::size_type siz)
{
static const signed char bin_data[256]
= {-128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114,
-113, -112, -111, -110, -109, -108, -107, -106, -105, -104, -103, -102, -101, -100, -99,
-98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, -84,
-83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69,
-68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54,
-53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39,
-38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24,
-23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9,
-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
127};
str.resize(siz);
char *ptr = &str[0];
string::size_type pos = 0;
for (string::size_type i = 0; i < siz; ++i)
{
if (pos == 255) { pos = 0; } else { ++pos; }
*ptr++ = bin_data[pos];
}
}
int binary_test(ThriftTestClient& testClient, string::size_type siz)
{
string bin_request;
string bin_result;
cout << "testBinary(siz = " << siz << ")" << endl;
binary_fill(bin_request, siz);
try {
testClient.testBinary(bin_result, bin_request);
if (bin_request.size() != bin_result.size()) {
cout << "*** FAILED: request size " << bin_request.size() << "; result size " << bin_result.size() << endl;
return ERR_BASETYPES;
}
for (string::size_type i = 0; i < siz; ++i) {
if (bin_request.at(i) != bin_result.at(i)) {
cout << "*** FAILED: at position " << i << " request[i] is h" << hex << bin_request.at(i) << " result[i] is h" << hex << bin_result.at(i) << endl;
return ERR_BASETYPES;
}
}
} catch (TTransportException&) {
throw;
} catch (exception& ex) {
cout << "*** FAILED ***" << endl << ex.what() << endl;
return ERR_BASETYPES;
}
return 0;
}

View file

@ -17,39 +17,52 @@
* under the License.
*/
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <thrift/concurrency/ThreadManager.h>
#include <thrift/async/TAsyncBufferProcessor.h>
#include <thrift/async/TAsyncProtocolProcessor.h>
#include <thrift/async/TEvhttpServer.h>
#include <thrift/concurrency/PlatformThreadFactory.h>
#include <thrift/concurrency/ThreadManager.h>
#include <thrift/processor/TMultiplexedProcessor.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/protocol/TCompactProtocol.h>
#include <thrift/protocol/THeaderProtocol.h>
#include <thrift/protocol/TJSONProtocol.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/server/TThreadedServer.h>
#include <thrift/server/TThreadPoolServer.h>
#include <thrift/async/TEvhttpServer.h>
#include <thrift/async/TAsyncBufferProcessor.h>
#include <thrift/async/TAsyncProtocolProcessor.h>
#include <thrift/server/TNonblockingServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TSSLServerSocket.h>
#include <thrift/transport/TSSLSocket.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/server/TThreadPoolServer.h>
#include <thrift/server/TThreadedServer.h>
#include <thrift/transport/THttpServer.h>
#include <thrift/transport/THttpTransport.h>
#include <thrift/transport/TNonblockingSSLServerSocket.h>
#include <thrift/transport/TNonblockingServerSocket.h>
#include <thrift/transport/TSSLServerSocket.h>
#include <thrift/transport/TSSLSocket.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TTransportUtils.h>
#include <thrift/transport/TZlibTransport.h>
#include "SecondService.h"
#include "ThriftTest.h"
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#include <iostream>
#include <stdexcept>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <thrift/cxxfunctional.h>
#include <thrift/stdcxx.h>
#include <signal.h>
#if _WIN32
#include <thrift/windows/TWinsockSingleton.h>
#endif
@ -57,14 +70,25 @@
using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::async;
using namespace apache::thrift::concurrency;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace apache::thrift::server;
using namespace apache::thrift::async;
using namespace thrift::test;
// to handle a controlled shutdown, signal handling is mandatory
#ifdef HAVE_SIGNAL_H
apache::thrift::concurrency::Monitor gMonitor;
void signal_handler(int signum)
{
if (signum == SIGINT) {
gMonitor.notifyAll();
}
}
#endif
class TestHandler : public ThriftTestIf {
public:
TestHandler() {}
@ -104,7 +128,7 @@ public:
void testBinary(std::string& _return, const std::string& thing) {
std::ostringstream hexstr;
hexstr << std::hex << thing;
printf("testBinary(%s)\n", hexstr.str().c_str());
printf("testBinary(%lu: %s)\n", safe_numeric_cast<unsigned long>(thing.size()), hexstr.str().c_str());
_return = thing;
}
@ -326,13 +350,18 @@ public:
}
}
void testOneway(const int32_t sleepFor) {
printf("testOneway(%d): Sleeping...\n", sleepFor);
THRIFT_SLEEP_SEC(sleepFor);
printf("testOneway(%d): done sleeping!\n", sleepFor);
void testOneway(const int32_t aNum) {
printf("testOneway(%d): call received\n", aNum);
}
};
class SecondHandler : public SecondServiceIf
{
public:
void secondtestString(std::string& result, const std::string& thing)
{ result = "testString(\"" + thing + "\")"; }
};
class TestProcessorEventHandler : public TProcessorEventHandler {
virtual void* getContext(const char* fn_name, void* serverContext) {
(void)serverContext;
@ -366,66 +395,66 @@ class TestProcessorEventHandler : public TProcessorEventHandler {
class TestHandlerAsync : public ThriftTestCobSvIf {
public:
TestHandlerAsync(boost::shared_ptr<TestHandler>& handler) : _delegate(handler) {}
TestHandlerAsync(stdcxx::shared_ptr<TestHandler>& handler) : _delegate(handler) {}
virtual ~TestHandlerAsync() {}
virtual void testVoid(tcxx::function<void()> cob) {
virtual void testVoid(stdcxx::function<void()> cob) {
_delegate->testVoid();
cob();
}
virtual void testString(tcxx::function<void(std::string const& _return)> cob,
virtual void testString(stdcxx::function<void(std::string const& _return)> cob,
const std::string& thing) {
std::string res;
_delegate->testString(res, thing);
cob(res);
}
virtual void testBool(tcxx::function<void(bool const& _return)> cob, const bool thing) {
virtual void testBool(stdcxx::function<void(bool const& _return)> cob, const bool thing) {
bool res = _delegate->testBool(thing);
cob(res);
}
virtual void testByte(tcxx::function<void(int8_t const& _return)> cob, const int8_t thing) {
virtual void testByte(stdcxx::function<void(int8_t const& _return)> cob, const int8_t thing) {
int8_t res = _delegate->testByte(thing);
cob(res);
}
virtual void testI32(tcxx::function<void(int32_t const& _return)> cob, const int32_t thing) {
virtual void testI32(stdcxx::function<void(int32_t const& _return)> cob, const int32_t thing) {
int32_t res = _delegate->testI32(thing);
cob(res);
}
virtual void testI64(tcxx::function<void(int64_t const& _return)> cob, const int64_t thing) {
virtual void testI64(stdcxx::function<void(int64_t const& _return)> cob, const int64_t thing) {
int64_t res = _delegate->testI64(thing);
cob(res);
}
virtual void testDouble(tcxx::function<void(double const& _return)> cob, const double thing) {
virtual void testDouble(stdcxx::function<void(double const& _return)> cob, const double thing) {
double res = _delegate->testDouble(thing);
cob(res);
}
virtual void testBinary(tcxx::function<void(std::string const& _return)> cob,
virtual void testBinary(stdcxx::function<void(std::string const& _return)> cob,
const std::string& thing) {
std::string res;
_delegate->testBinary(res, thing);
cob(res);
}
virtual void testStruct(tcxx::function<void(Xtruct const& _return)> cob, const Xtruct& thing) {
virtual void testStruct(stdcxx::function<void(Xtruct const& _return)> cob, const Xtruct& thing) {
Xtruct res;
_delegate->testStruct(res, thing);
cob(res);
}
virtual void testNest(tcxx::function<void(Xtruct2 const& _return)> cob, const Xtruct2& thing) {
virtual void testNest(stdcxx::function<void(Xtruct2 const& _return)> cob, const Xtruct2& thing) {
Xtruct2 res;
_delegate->testNest(res, thing);
cob(res);
}
virtual void testMap(tcxx::function<void(std::map<int32_t, int32_t> const& _return)> cob,
virtual void testMap(stdcxx::function<void(std::map<int32_t, int32_t> const& _return)> cob,
const std::map<int32_t, int32_t>& thing) {
std::map<int32_t, int32_t> res;
_delegate->testMap(res, thing);
@ -433,40 +462,40 @@ public:
}
virtual void testStringMap(
tcxx::function<void(std::map<std::string, std::string> const& _return)> cob,
stdcxx::function<void(std::map<std::string, std::string> const& _return)> cob,
const std::map<std::string, std::string>& thing) {
std::map<std::string, std::string> res;
_delegate->testStringMap(res, thing);
cob(res);
}
virtual void testSet(tcxx::function<void(std::set<int32_t> const& _return)> cob,
virtual void testSet(stdcxx::function<void(std::set<int32_t> const& _return)> cob,
const std::set<int32_t>& thing) {
std::set<int32_t> res;
_delegate->testSet(res, thing);
cob(res);
}
virtual void testList(tcxx::function<void(std::vector<int32_t> const& _return)> cob,
virtual void testList(stdcxx::function<void(std::vector<int32_t> const& _return)> cob,
const std::vector<int32_t>& thing) {
std::vector<int32_t> res;
_delegate->testList(res, thing);
cob(res);
}
virtual void testEnum(tcxx::function<void(Numberz::type const& _return)> cob,
virtual void testEnum(stdcxx::function<void(Numberz::type const& _return)> cob,
const Numberz::type thing) {
Numberz::type res = _delegate->testEnum(thing);
cob(res);
}
virtual void testTypedef(tcxx::function<void(UserId const& _return)> cob, const UserId thing) {
virtual void testTypedef(stdcxx::function<void(UserId const& _return)> cob, const UserId thing) {
UserId res = _delegate->testTypedef(thing);
cob(res);
}
virtual void testMapMap(
tcxx::function<void(std::map<int32_t, std::map<int32_t, int32_t> > const& _return)> cob,
stdcxx::function<void(std::map<int32_t, std::map<int32_t, int32_t> > const& _return)> cob,
const int32_t hello) {
std::map<int32_t, std::map<int32_t, int32_t> > res;
_delegate->testMapMap(res, hello);
@ -474,14 +503,14 @@ public:
}
virtual void testInsanity(
tcxx::function<void(std::map<UserId, std::map<Numberz::type, Insanity> > const& _return)> cob,
stdcxx::function<void(std::map<UserId, std::map<Numberz::type, Insanity> > const& _return)> cob,
const Insanity& argument) {
std::map<UserId, std::map<Numberz::type, Insanity> > res;
_delegate->testInsanity(res, argument);
cob(res);
}
virtual void testMulti(tcxx::function<void(Xtruct const& _return)> cob,
virtual void testMulti(stdcxx::function<void(Xtruct const& _return)> cob,
const int8_t arg0,
const int32_t arg1,
const int64_t arg2,
@ -494,8 +523,8 @@ public:
}
virtual void testException(
tcxx::function<void()> cob,
tcxx::function<void(::apache::thrift::TDelayedException* _throw)> exn_cob,
stdcxx::function<void()> cob,
stdcxx::function<void(::apache::thrift::TDelayedException* _throw)> exn_cob,
const std::string& arg) {
try {
_delegate->testException(arg);
@ -507,8 +536,8 @@ public:
}
virtual void testMultiException(
tcxx::function<void(Xtruct const& _return)> cob,
tcxx::function<void(::apache::thrift::TDelayedException* _throw)> exn_cob,
stdcxx::function<void(Xtruct const& _return)> cob,
stdcxx::function<void(::apache::thrift::TDelayedException* _throw)> exn_cob,
const std::string& arg0,
const std::string& arg1) {
Xtruct res;
@ -521,13 +550,13 @@ public:
cob(res);
}
virtual void testOneway(tcxx::function<void()> cob, const int32_t secondsToSleep) {
virtual void testOneway(stdcxx::function<void()> cob, const int32_t secondsToSleep) {
_delegate->testOneway(secondsToSleep);
cob();
}
protected:
boost::shared_ptr<TestHandler> _delegate;
stdcxx::shared_ptr<TestHandler> _delegate;
};
namespace po = boost::program_options;
@ -543,6 +572,7 @@ int main(int argc, char** argv) {
#endif
int port = 9090;
bool ssl = false;
bool zlib = false;
string transport_type = "buffered";
string protocol_type = "binary";
string server_type = "simple";
@ -559,9 +589,10 @@ int main(int argc, char** argv) {
("domain-socket", po::value<string>(&domain_socket) ->default_value(domain_socket), "Unix Domain Socket (e.g. /tmp/ThriftTest.thrift)")
("abstract-namespace", "Create the domain socket in the Abstract Namespace (no connection with filesystem pathnames)")
("server-type", po::value<string>(&server_type)->default_value(server_type), "type of server, \"simple\", \"thread-pool\", \"threaded\", or \"nonblocking\"")
("transport", po::value<string>(&transport_type)->default_value(transport_type), "transport: buffered, framed, http")
("protocol", po::value<string>(&protocol_type)->default_value(protocol_type), "protocol: binary, compact, header, json")
("transport", po::value<string>(&transport_type)->default_value(transport_type), "transport: buffered, framed, http, zlib")
("protocol", po::value<string>(&protocol_type)->default_value(protocol_type), "protocol: binary, compact, header, json, multi, multic, multih, multij")
("ssl", "Encrypted Transport using SSL")
("zlib", "Wrapped Transport using Zlib")
("processor-events", "processor-events")
("workers,n", po::value<size_t>(&workers)->default_value(workers), "Number of thread pools workers. Only valid for thread-pool server type")
("string-limit", po::value<int>(&string_limit))
@ -592,6 +623,10 @@ int main(int argc, char** argv) {
} else if (protocol_type == "compact") {
} else if (protocol_type == "json") {
} else if (protocol_type == "header") {
} else if (protocol_type == "multi") { // multiplexed binary
} else if (protocol_type == "multic") { // multiplexed compact
} else if (protocol_type == "multih") { // multiplexed header
} else if (protocol_type == "multij") { // multiplexed json
} else {
throw invalid_argument("Unknown protocol type " + protocol_type);
}
@ -601,6 +636,8 @@ int main(int argc, char** argv) {
if (transport_type == "buffered") {
} else if (transport_type == "framed") {
} else if (transport_type == "http") {
} else if (transport_type == "zlib") {
// crosstester will pass zlib as a flag and a transport right now...
} else {
throw invalid_argument("Unknown transport type " + transport_type);
}
@ -616,22 +653,32 @@ int main(int argc, char** argv) {
ssl = true;
}
if (vm.count("zlib")) {
zlib = true;
}
#if defined(HAVE_SIGNAL_H) && defined(SIGPIPE)
if (ssl) {
signal(SIGPIPE, SIG_IGN); // for OpenSSL, otherwise we end abruptly
}
#endif
if (vm.count("abstract-namespace")) {
abstract_namespace = true;
}
// Dispatcher
boost::shared_ptr<TProtocolFactory> protocolFactory;
if (protocol_type == "json") {
boost::shared_ptr<TProtocolFactory> jsonProtocolFactory(new TJSONProtocolFactory());
stdcxx::shared_ptr<TProtocolFactory> protocolFactory;
if (protocol_type == "json" || protocol_type == "multij") {
stdcxx::shared_ptr<TProtocolFactory> jsonProtocolFactory(new TJSONProtocolFactory());
protocolFactory = jsonProtocolFactory;
} else if (protocol_type == "compact") {
} else if (protocol_type == "compact" || protocol_type == "multic") {
TCompactProtocolFactoryT<TBufferBase> *compactProtocolFactory = new TCompactProtocolFactoryT<TBufferBase>();
compactProtocolFactory->setContainerSizeLimit(container_limit);
compactProtocolFactory->setStringSizeLimit(string_limit);
protocolFactory.reset(compactProtocolFactory);
} else if (protocol_type == "header") {
boost::shared_ptr<TProtocolFactory> headerProtocolFactory(new THeaderProtocolFactory());
} else if (protocol_type == "header" || protocol_type == "multih") {
stdcxx::shared_ptr<TProtocolFactory> headerProtocolFactory(new THeaderProtocolFactory());
protocolFactory = headerProtocolFactory;
} else {
TBinaryProtocolFactoryT<TBufferBase>* binaryProtocolFactory = new TBinaryProtocolFactoryT<TBufferBase>();
@ -640,53 +687,57 @@ int main(int argc, char** argv) {
protocolFactory.reset(binaryProtocolFactory);
}
// Processor
boost::shared_ptr<TestHandler> testHandler(new TestHandler());
boost::shared_ptr<ThriftTestProcessor> testProcessor(new ThriftTestProcessor(testHandler));
// Processors
stdcxx::shared_ptr<TestHandler> testHandler(new TestHandler());
stdcxx::shared_ptr<TProcessor> testProcessor(new ThriftTestProcessor(testHandler));
if (vm.count("processor-events")) {
testProcessor->setEventHandler(
boost::shared_ptr<TProcessorEventHandler>(new TestProcessorEventHandler()));
stdcxx::shared_ptr<TProcessorEventHandler>(new TestProcessorEventHandler()));
}
// Transport
boost::shared_ptr<TSSLSocketFactory> sslSocketFactory;
boost::shared_ptr<TServerSocket> serverSocket;
stdcxx::shared_ptr<TSSLSocketFactory> sslSocketFactory;
stdcxx::shared_ptr<TServerSocket> serverSocket;
if (ssl) {
sslSocketFactory = boost::shared_ptr<TSSLSocketFactory>(new TSSLSocketFactory());
sslSocketFactory = stdcxx::shared_ptr<TSSLSocketFactory>(new TSSLSocketFactory());
sslSocketFactory->loadCertificate(certPath.c_str());
sslSocketFactory->loadPrivateKey(keyPath.c_str());
sslSocketFactory->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
serverSocket = boost::shared_ptr<TServerSocket>(new TSSLServerSocket(port, sslSocketFactory));
if (server_type != "nonblocking") {
serverSocket = stdcxx::shared_ptr<TServerSocket>(new TSSLServerSocket(port, sslSocketFactory));
}
} else {
if (domain_socket != "") {
if (abstract_namespace) {
std::string abstract_socket("\0", 1);
abstract_socket += domain_socket;
serverSocket = boost::shared_ptr<TServerSocket>(new TServerSocket(abstract_socket));
serverSocket = stdcxx::shared_ptr<TServerSocket>(new TServerSocket(abstract_socket));
} else {
unlink(domain_socket.c_str());
serverSocket = boost::shared_ptr<TServerSocket>(new TServerSocket(domain_socket));
serverSocket = stdcxx::shared_ptr<TServerSocket>(new TServerSocket(domain_socket));
}
port = 0;
} else {
serverSocket = boost::shared_ptr<TServerSocket>(new TServerSocket(port));
serverSocket = stdcxx::shared_ptr<TServerSocket>(new TServerSocket(port));
}
}
// Factory
boost::shared_ptr<TTransportFactory> transportFactory;
stdcxx::shared_ptr<TTransportFactory> transportFactory;
if (transport_type == "http" && server_type != "nonblocking") {
boost::shared_ptr<TTransportFactory> httpTransportFactory(new THttpServerTransportFactory());
transportFactory = httpTransportFactory;
transportFactory = stdcxx::make_shared<THttpServerTransportFactory>();
} else if (transport_type == "framed") {
boost::shared_ptr<TTransportFactory> framedTransportFactory(new TFramedTransportFactory());
transportFactory = framedTransportFactory;
transportFactory = stdcxx::make_shared<TFramedTransportFactory>();
} else {
boost::shared_ptr<TTransportFactory> bufferedTransportFactory(new TBufferedTransportFactory());
transportFactory = bufferedTransportFactory;
transportFactory = stdcxx::make_shared<TBufferedTransportFactory>();
}
if (zlib) {
// hmm.. doesn't seem to be a way to make it wrap the others...
transportFactory = stdcxx::make_shared<TZlibTransportFactory>();
}
// Server Info
@ -701,20 +752,30 @@ int main(int argc, char** argv) {
}
cout << endl;
// Multiplexed Processor if needed
if (boost::starts_with(protocol_type, "multi")) {
stdcxx::shared_ptr<SecondHandler> secondHandler(new SecondHandler());
stdcxx::shared_ptr<SecondServiceProcessor> secondProcessor(new SecondServiceProcessor(secondHandler));
stdcxx::shared_ptr<TMultiplexedProcessor> multiplexedProcessor(new TMultiplexedProcessor());
multiplexedProcessor->registerDefault(testProcessor); // non-multi clients go to the default processor (multi:binary, multic:compact, ...)
multiplexedProcessor->registerProcessor("ThriftTest", testProcessor);
multiplexedProcessor->registerProcessor("SecondService", secondProcessor);
testProcessor = stdcxx::dynamic_pointer_cast<TProcessor>(multiplexedProcessor);
}
// Server
boost::shared_ptr<apache::thrift::server::TServer> server;
stdcxx::shared_ptr<apache::thrift::server::TServer> server;
if (server_type == "simple") {
server.reset(new TSimpleServer(testProcessor, serverSocket, transportFactory, protocolFactory));
} else if (server_type == "thread-pool") {
boost::shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(workers);
boost::shared_ptr<PlatformThreadFactory> threadFactory
= boost::shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
stdcxx::shared_ptr<PlatformThreadFactory> threadFactory
= stdcxx::shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
stdcxx::shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(workers);
threadManager->threadFactory(threadFactory);
threadManager->start();
server.reset(new TThreadPoolServer(testProcessor,
@ -723,15 +784,14 @@ int main(int argc, char** argv) {
protocolFactory,
threadManager));
} else if (server_type == "threaded") {
server.reset(
new TThreadedServer(testProcessor, serverSocket, transportFactory, protocolFactory));
} else if (server_type == "nonblocking") {
if (transport_type == "http") {
boost::shared_ptr<TestHandlerAsync> testHandlerAsync(new TestHandlerAsync(testHandler));
boost::shared_ptr<TAsyncProcessor> testProcessorAsync(
stdcxx::shared_ptr<TestHandlerAsync> testHandlerAsync(new TestHandlerAsync(testHandler));
stdcxx::shared_ptr<TAsyncProcessor> testProcessorAsync(
new ThriftTestAsyncProcessor(testHandlerAsync));
boost::shared_ptr<TAsyncBufferProcessor> testBufferProcessor(
stdcxx::shared_ptr<TAsyncBufferProcessor> testBufferProcessor(
new TAsyncProtocolProcessor(testProcessorAsync, protocolFactory));
// not loading nonblockingServer into "server" because
@ -739,8 +799,15 @@ int main(int argc, char** argv) {
// provide a stop method.
TEvhttpServer nonblockingServer(testBufferProcessor, port);
nonblockingServer.serve();
} else if (transport_type == "framed") {
stdcxx::shared_ptr<transport::TNonblockingServerTransport> nbSocket;
nbSocket.reset(
ssl ? new transport::TNonblockingSSLServerSocket(port, sslSocketFactory)
: new transport::TNonblockingServerSocket(port));
server.reset(new TNonblockingServer(testProcessor, protocolFactory, nbSocket));
} else {
server.reset(new TNonblockingServer(testProcessor, protocolFactory, port));
cerr << "server-type nonblocking requires transport of http or framed" << endl;
exit(1);
}
}
@ -748,22 +815,25 @@ int main(int argc, char** argv) {
if (protocol_type == "header") {
// Tell the server to use the same protocol for input / output
// if using header
server->setOutputProtocolFactory(boost::shared_ptr<TProtocolFactory>());
server->setOutputProtocolFactory(stdcxx::shared_ptr<TProtocolFactory>());
}
apache::thrift::concurrency::PlatformThreadFactory factory;
factory.setDetached(false);
boost::shared_ptr<apache::thrift::concurrency::Runnable> serverThreadRunner(server);
boost::shared_ptr<apache::thrift::concurrency::Thread> thread
stdcxx::shared_ptr<apache::thrift::concurrency::Runnable> serverThreadRunner(server);
stdcxx::shared_ptr<apache::thrift::concurrency::Thread> thread
= factory.newThread(serverThreadRunner);
thread->start();
// HACK: cross language test suite is unable to handle cin properly
// that's why we stay in a endless loop here
while (1) {
}
// FIXME: find another way to stop the server (e.g. a signal)
// cout<<"Press enter to stop the server."<<endl;
// cin.ignore(); //wait until a key is pressed
#ifdef HAVE_SIGNAL_H
signal(SIGINT, signal_handler);
#endif
thread->start();
gMonitor.waitForever(); // wait for a shutdown signal
#ifdef HAVE_SIGNAL_H
signal(SIGINT, SIG_DFL);
#endif
server->stop();
thread->join();
@ -773,3 +843,4 @@ int main(int argc, char** argv) {
cout << "done." << endl;
return 0;
}

View file

@ -51,6 +51,7 @@ VALID_JSON_KEYS = [
]
DEFAULT_MAX_DELAY = 5
DEFAULT_SIGNAL = 1
DEFAULT_TIMEOUT = 5
@ -112,7 +113,7 @@ def _do_collect_tests(servers, clients):
yield name, impl1, impl2
def maybe_max(key, o1, o2, default):
"""maximum of two if present, otherwise defult value"""
"""maximum of two if present, otherwise default value"""
v1 = o1.get(key)
v2 = o2.get(key)
return max(v1, v2) if v1 and v2 else v1 or v2 or default
@ -138,6 +139,7 @@ def _do_collect_tests(servers, clients):
'server': merge_metadata(sv, **{'protocol': proto1, 'transport': trans1}),
'client': merge_metadata(cl, **{'protocol': proto2, 'transport': trans2}),
'delay': maybe_max('delay', sv, cl, DEFAULT_MAX_DELAY),
'stop_signal': maybe_max('stop_signal', sv, cl, DEFAULT_SIGNAL),
'timeout': maybe_max('timeout', sv, cl, DEFAULT_TIMEOUT),
'protocol': proto,
'transport': trans,

View file

@ -104,7 +104,7 @@ class TestReporter(object):
def _print_bar(self, out=None):
print(
'==========================================================================',
'===============================================================================',
file=(out or self.out))
def _print_exec_time(self):
@ -157,9 +157,14 @@ class ExecReporter(TestReporter):
])),
'client': list(map(re.compile, [
'[Cc]onnection refused',
'Could not connect to localhost',
'Could not connect to',
'Could not open UNIX ', # domain socket (rb)
'ECONNREFUSED',
'econnrefused', # erl
'CONNECTION-REFUSED-ERROR', # cl
'connect ENOENT', # nodejs domain socket
'No such file or directory', # domain socket
'Sockets.TcpClient.Connect', # csharp
])),
}
@ -174,6 +179,7 @@ class ExecReporter(TestReporter):
def match(line):
for expr in exprs:
if expr.search(line):
self._log.info("maybe false positive: %s" % line)
return True
with logfile_open(self.logpath, 'r') as fp:
@ -204,7 +210,7 @@ class ExecReporter(TestReporter):
def _print_footer(self, returncode=None):
self._print_bar()
if returncode is not None:
print('Return code: %d' % returncode, file=self.out)
print('Return code: %d (negative values indicate kill by signal)' % returncode, file=self.out)
else:
print('Process is killed.', file=self.out)
self._print_exec_time()
@ -259,14 +265,15 @@ class SummaryReporter(TestReporter):
name = '%s-%s' % (test.server.name, test.client.name)
trans = '%s-%s' % (test.transport, test.socket)
if not with_result:
return '{:24s}{:13s}{:25s}'.format(name[:23], test.protocol[:12], trans[:24])
return '{:24s}{:18s}{:25s}'.format(name[:23], test.protocol[:17], trans[:24])
else:
return '{:24s}{:13s}{:25s}{:s}\n'.format(name[:23], test.protocol[:12], trans[:24], self._result_string(test))
return '{:24s}{:18s}{:25s}{:s}\n'.format(name[:23], test.protocol[:17],
trans[:24], self._result_string(test))
def _print_test_header(self):
self._print_bar()
print(
'{:24s}{:13s}{:25s}{:s}'.format('server-client:', 'protocol:', 'transport:', 'result:'),
'{:24s}{:18s}{:25s}{:s}'.format('server-client:', 'protocol:', 'transport:', 'result:'),
file=self.out)
def _print_header(self):
@ -332,8 +339,8 @@ class SummaryReporter(TestReporter):
'# then browse:\n',
'# \thttp://localhost:%d/%s/\n' % (8001, self._testdir_rel),
'Full log for each test is here:\n',
'\ttest/log/client_server_protocol_transport_client.log\n',
'\ttest/log/client_server_protocol_transport_server.log\n',
'\ttest/log/server_client_protocol_transport_client.log\n',
'\ttest/log/server_client_protocol_transport_server.log\n',
'%d failed of %d tests in total.\n' % (fail_count, len(self._tests)),
])
self._print_exec_time()

View file

@ -23,19 +23,20 @@ import multiprocessing.managers
import os
import platform
import random
import signal
import socket
import subprocess
import sys
import threading
import time
from .compat import str_join
from .test import TestEntry, domain_socket_path
from .report import ExecReporter, SummaryReporter
from .test import TestEntry
from .util import domain_socket_path
RESULT_TIMEOUT = 128
RESULT_ERROR = 64
RESULT_TIMEOUT = 128
SIGNONE = 0
SIGKILL = 15
# globals
ports = None
@ -43,35 +44,18 @@ stop = None
class ExecutionContext(object):
def __init__(self, cmd, cwd, env, report):
def __init__(self, cmd, cwd, env, stop_signal, is_server, report):
self._log = multiprocessing.get_logger()
self.report = report
self.cmd = cmd
self.cwd = cwd
self.env = env
self.timer = None
self.stop_signal = stop_signal
self.is_server = is_server
self.report = report
self.expired = False
self.killed = False
self.proc = None
def _expire(self):
self._log.info('Timeout')
self.expired = True
self.kill()
def kill(self):
self._log.debug('Killing process : %d' % self.proc.pid)
self.killed = True
if platform.system() != 'Windows':
try:
os.killpg(self.proc.pid, signal.SIGKILL)
except Exception:
self._log.info('Failed to kill process group', exc_info=sys.exc_info())
try:
self.proc.kill()
except Exception:
self._log.info('Failed to kill process', exc_info=sys.exc_info())
def _popen_args(self):
args = {
'cwd': self.cwd,
@ -87,75 +71,125 @@ class ExecutionContext(object):
args.update(preexec_fn=os.setsid)
return args
def start(self, timeout=0):
def start(self):
joined = str_join(' ', self.cmd)
self._log.debug('COMMAND: %s', joined)
self._log.debug('WORKDIR: %s', self.cwd)
self._log.debug('LOGFILE: %s', self.report.logpath)
self.report.begin()
self.proc = subprocess.Popen(self.cmd, **self._popen_args())
if timeout > 0:
self.timer = threading.Timer(timeout, self._expire)
self.timer.start()
self._log.debug(' PID: %d', self.proc.pid)
self._log.debug(' PGID: %d', os.getpgid(self.proc.pid))
return self._scoped()
@contextlib.contextmanager
def _scoped(self):
yield self
self._log.debug('Killing scoped process')
if self.proc.poll() is None:
self.kill()
self.report.killed()
if self.is_server:
# the server is supposed to run until we stop it
if self.returncode is not None:
self.report.died()
else:
if self.stop_signal != SIGNONE:
if self.sigwait(self.stop_signal):
self.report.end(self.returncode)
else:
self.report.killed()
else:
self.sigwait(SIGKILL)
else:
self._log.debug('Process died unexpectedly')
self.report.died()
# the client is supposed to exit normally
if self.returncode is not None:
self.report.end(self.returncode)
else:
self.sigwait(SIGKILL)
self.report.killed()
self._log.debug('[{0}] exited with return code {1}'.format(self.proc.pid, self.returncode))
def wait(self):
self.proc.communicate()
if self.timer:
self.timer.cancel()
self.report.end(self.returncode)
# Send a signal to the process and then wait for it to end
# If the signal requested is SIGNONE, no signal is sent, and
# instead we just wait for the process to end; further if it
# does not end normally with SIGNONE, we mark it as expired.
# If the process fails to end and the signal is not SIGKILL,
# it re-runs with SIGKILL so that a real process kill occurs
# returns True if the process ended, False if it may not have
def sigwait(self, sig=SIGKILL, timeout=2):
try:
if sig != SIGNONE:
self._log.debug('[{0}] send signal {1}'.format(self.proc.pid, sig))
if sig == SIGKILL:
self.killed = True
try:
if platform.system() != 'Windows':
os.killpg(os.getpgid(self.proc.pid), sig)
else:
self.proc.send_signal(sig)
except Exception:
self._log.info('[{0}] Failed to kill process'.format(self.proc.pid), exc_info=sys.exc_info())
self._log.debug('[{0}] wait begin, timeout {1} sec(s)'.format(self.proc.pid, timeout))
self.proc.communicate(timeout=timeout)
self._log.debug('[{0}] process ended with return code {1}'.format(self.proc.pid, self.returncode))
self.report.end(self.returncode)
return True
except subprocess.TimeoutExpired:
self._log.info('[{0}] timeout waiting for process to end'.format(self.proc.pid))
if sig == SIGNONE:
self.expired = True
return False if sig == SIGKILL else self.sigwait(SIGKILL, 1)
# called on the client process to wait for it to end naturally
def wait(self, timeout):
self.sigwait(SIGNONE, timeout)
@property
def returncode(self):
return self.proc.returncode if self.proc else None
def exec_context(port, logdir, test, prog):
def exec_context(port, logdir, test, prog, is_server):
report = ExecReporter(logdir, test, prog)
prog.build_command(port)
return ExecutionContext(prog.command, prog.workdir, prog.env, report)
return ExecutionContext(prog.command, prog.workdir, prog.env, prog.stop_signal, is_server, report)
def run_test(testdir, logdir, test_dict, max_retry, async=True):
logger = multiprocessing.get_logger()
def ensure_socket_open(proc, port, max_delay):
sleeped = 0.1
time.sleep(sleeped)
sleep_step = 0.2
def ensure_socket_open(sv, port, test):
slept = 0.1
time.sleep(slept)
sleep_step = 0.1
while True:
# Create sockets every iteration because refused sockets cannot be
# reused on some systems.
sock4 = socket.socket()
sock6 = socket.socket(family=socket.AF_INET6)
try:
if sock4.connect_ex(('127.0.0.1', port)) == 0 \
or sock6.connect_ex(('::1', port)) == 0:
return True
if proc.poll() is not None:
logger.warn('server process is exited')
return False
if sleeped > max_delay:
logger.warn('sleeped for %f seconds but server port is not open' % sleeped)
return False
time.sleep(sleep_step)
sleeped += sleep_step
finally:
sock4.close()
sock6.close()
logger.debug('waited %f sec for server port open' % sleeped)
return True
if slept > test.delay:
logger.warn('[{0}] slept for {1} seconds but server is not open'.format(sv.proc.pid, slept))
return False
if test.socket == 'domain':
if not os.path.exists(domain_socket_path(port)):
logger.debug('[{0}] domain(unix) socket not available yet. slept for {1} seconds so far'.format(sv.proc.pid, slept))
time.sleep(sleep_step)
slept += sleep_step
elif test.socket == 'abstract':
return True
else:
# Create sockets every iteration because refused sockets cannot be
# reused on some systems.
sock4 = socket.socket()
sock6 = socket.socket(family=socket.AF_INET6)
try:
if sock4.connect_ex(('127.0.0.1', port)) == 0 \
or sock6.connect_ex(('::1', port)) == 0:
return True
if sv.proc.poll() is not None:
logger.warn('[{0}] server process is exited'.format(sv.proc.pid))
return False
logger.debug('[{0}] socket not available yet. slept for {1} seconds so far'.format(sv.proc.pid, slept))
time.sleep(sleep_step)
slept += sleep_step
finally:
sock4.close()
sock6.close()
logger.debug('[{0}] server ready - waited for {1} seconds'.format(sv.proc.pid, slept))
return True
try:
max_bind_retry = 3
@ -169,31 +203,27 @@ def run_test(testdir, logdir, test_dict, max_retry, async=True):
logger.debug('Start')
with PortAllocator.alloc_port_scoped(ports, test.socket) as port:
logger.debug('Start with port %d' % port)
sv = exec_context(port, logdir, test, test.server)
cl = exec_context(port, logdir, test, test.client)
sv = exec_context(port, logdir, test, test.server, True)
cl = exec_context(port, logdir, test, test.client, False)
logger.debug('Starting server')
with sv.start():
if test.socket in ('domain', 'abstract'):
time.sleep(0.1)
port_ok = True
else:
port_ok = ensure_socket_open(sv.proc, port, test.delay)
port_ok = ensure_socket_open(sv, port, test)
if port_ok:
connect_retry_count = 0
max_connect_retry = 3
connect_retry_wait = 0.5
max_connect_retry = 12
connect_retry_wait = 0.25
while True:
if sv.proc.poll() is not None:
logger.info('not starting client because server process is absent')
break
logger.debug('Starting client')
cl.start(test.timeout)
logger.debug('Waiting client')
cl.wait()
cl.start()
logger.debug('Waiting client (up to %d secs)' % test.timeout)
cl.wait(test.timeout)
if not cl.report.maybe_false_positive() or connect_retry_count >= max_connect_retry:
if connect_retry_count > 0 and connect_retry_count < max_connect_retry:
logger.warn('[%s]: Connected after %d retry (%.2f sec each)' % (test.server.name, connect_retry_count, connect_retry_wait))
logger.info('[%s]: Connected after %d retry (%.2f sec each)' % (test.server.name, connect_retry_count, connect_retry_wait))
# Wait for 50ms to see if server does not die at the end.
time.sleep(0.05)
break
@ -205,12 +235,18 @@ def run_test(testdir, logdir, test_dict, max_retry, async=True):
logger.warn('[%s]: Detected socket bind failure, retrying...', test.server.name)
bind_retry_count += 1
else:
if cl.expired:
result = RESULT_TIMEOUT
result = RESULT_TIMEOUT if cl.expired else cl.returncode if (cl.proc and cl.proc.poll()) is not None else RESULT_ERROR
# For servers that handle a controlled shutdown by signal
# if they are killed, or return an error code, that is a
# problem. For servers that are not signal-aware, we simply
# kill them off; if we didn't kill them off, something else
# happened (crashed?)
if test.server.stop_signal != 0:
if sv.killed or sv.returncode > 0:
result |= RESULT_ERROR
else:
result = cl.proc.returncode if cl.proc else RESULT_ERROR
if not sv.killed:
# Server died without being killed.
result |= RESULT_ERROR
if result == 0 or retry_count >= max_retry:

View file

@ -22,22 +22,20 @@ import multiprocessing
import os
import sys
from .compat import path_join
from .util import merge_dict
def domain_socket_path(port):
return '/tmp/ThriftTest.thrift.%d' % port
from .util import merge_dict, domain_socket_path
class TestProgram(object):
def __init__(self, kind, name, protocol, transport, socket, workdir, command, env=None,
def __init__(self, kind, name, protocol, transport, socket, workdir, stop_signal, command, env=None,
extra_args=[], extra_args2=[], join_args=False, **kwargs):
self.kind = kind
self.name = name
self.protocol = protocol
self.transport = transport
self.socket = socket
self.workdir = workdir
self.stop_signal = stop_signal
self.command = None
self._base_command = self._fix_cmd_path(command)
if env:
@ -68,11 +66,19 @@ class TestProgram(object):
'abstract': ['--abstract-namespace', '--domain-socket=%s' % domain_socket_path(port)],
}.get(socket, None)
def _transport_args(self, transport):
return {
'zlib': ['--zlib'],
}.get(transport, None)
def build_command(self, port):
cmd = copy.copy(self._base_command)
args = copy.copy(self._extra_args2)
args.append('--protocol=' + self.protocol)
args.append('--transport=' + self.transport)
transport_args = self._transport_args(self.transport)
if transport_args:
args += transport_args
socket_args = self._socket_args(self.socket, port)
if socket_args:
args += socket_args

View file

@ -20,6 +20,10 @@
import copy
def domain_socket_path(port):
return '/tmp/ThriftTest.thrift.%d' % port
def merge_dict(base, update):
"""Update dict concatenating list values"""
res = copy.deepcopy(base)

View file

@ -85,3 +85,11 @@ check-local: TestClientServer.exe
MONO_PATH=$(LIBDIR) timeout 10 mono TestClientServer.exe server --port=$(TESTPORT) &
sleep 1
MONO_PATH=$(LIBDIR) mono TestClientServer.exe client --port=$(TESTPORT)
EXTRA_DIST = \
Properties/AssemblyInfo.cs \
ThriftTest.csproj \
ThriftTest.sln \
Program.cs \
TestServer.cs \
TestClient.cs

View file

@ -27,9 +27,9 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ThriftTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ThriftTest")]
[assembly: AssemblyCopyright("Copyright © 2009 The Apache Software Foundation")]
[assembly: AssemblyCompany("The Apache Software Foundation")]
[assembly: AssemblyProduct("Thrift")]
[assembly: AssemblyCopyright("The Apache Software Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

View file

@ -33,7 +33,7 @@ namespace Test
{
public class TestClient
{
private class TestParams
public class TestParams
{
public int numIterations = 1;
public string host = "localhost";
@ -44,6 +44,7 @@ namespace Test
public bool framed;
public string protocol;
public bool encrypted = false;
public bool multiplexed = false;
protected bool _isFirstTransport = true;
@ -61,7 +62,9 @@ namespace Test
{
string certPath = "../keys/client.p12";
X509Certificate cert = new X509Certificate2(certPath, "thrift");
trans = new TTLSSocket(host, port, 0, cert, (o, c, chain, errors) => true, null, SslProtocols.Tls);
trans = new TTLSSocket(host, port, 0, cert,
(o, c, chain, errors) => true,
null, SslProtocols.Tls);
}
else
{
@ -105,21 +108,30 @@ namespace Test
private const int ErrorStructs = 2;
private const int ErrorContainers = 4;
private const int ErrorExceptions = 8;
private const int ErrorProtocol = 16;
private const int ErrorUnknown = 64;
private class ClientTest
{
private readonly TestParams param;
private readonly TTransport transport;
private readonly SecondService.Client second;
private readonly ThriftTest.Client client;
private readonly int numIterations;
private bool done;
public int ReturnCode { get; set; }
public ClientTest(TestParams param)
public ClientTest(TestParams paramin)
{
param = paramin;
transport = param.CreateTransport();
client = new ThriftTest.Client(param.CreateProtocol(transport));
TProtocol protocol = param.CreateProtocol(transport);
if (param.multiplexed)
{
second = new SecondService.Client(new TMultiplexedProtocol(protocol, "SecondService"));
}
client = new ThriftTest.Client(protocol);
numIterations = param.numIterations;
}
public void Execute()
@ -148,7 +160,7 @@ namespace Test
try
{
ReturnCode |= ExecuteClientTest(client);
ReturnCode |= ExecuteClientTest(client, second, param);
}
catch (Exception ex)
{
@ -215,12 +227,12 @@ namespace Test
{
numThreads = Convert.ToInt32(args[++i]);
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
else if (args[i] == "--compact" || args[i] == "--protocol=compact" || args[i] == "--protocol=multic")
{
param.protocol = "compact";
Console.WriteLine("Using compact protocol");
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
else if (args[i] == "--json" || args[i] == "--protocol=json" || args[i] == "--protocol=multij")
{
param.protocol = "json";
Console.WriteLine("Using JSON protocol");
@ -230,6 +242,11 @@ namespace Test
param.encrypted = true;
Console.WriteLine("Using encrypted transport");
}
if (args[i].StartsWith("--protocol=multi"))
{
param.multiplexed = true;
}
}
}
catch (Exception ex)
@ -265,10 +282,11 @@ namespace Test
return BitConverter.ToString(data).Replace("-", string.Empty);
}
public static byte[] PrepareTestData(bool randomDist)
public static byte[] PrepareTestData(bool randomDist, bool huge)
{
byte[] retval = new byte[0x100];
int initLen = Math.Min(0x100,retval.Length);
// huge = true tests for THRIFT-4372
byte[] retval = new byte[huge ? 0x12345 : 0x100];
int initLen = retval.Length;
// linear distribution, unless random is requested
if (!randomDist) {
@ -295,7 +313,7 @@ namespace Test
return retval;
}
public static int ExecuteClientTest(ThriftTest.Client client)
public static int ExecuteClientTest(ThriftTest.Client client, SecondService.Client second, TestParams param)
{
int returnCode = 0;
@ -312,6 +330,18 @@ namespace Test
returnCode |= ErrorBaseTypes;
}
if (param.multiplexed)
{
Console.WriteLine("secondTestString(\"Test2\")");
s = second.secondtestString("Test2");
Console.WriteLine(" = \"" + s + "\"");
if ("testString(\"Test2\")" != s)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorProtocol;
}
}
Console.Write("testBool(true)");
bool t = client.testBool((bool)true);
Console.WriteLine(" = " + t);
@ -374,29 +404,33 @@ namespace Test
returnCode |= ErrorBaseTypes;
}
byte[] binOut = PrepareTestData(true);
Console.Write("testBinary(" + BytesToHex(binOut) + ")");
try
for (i32 = 0; i32 < 2; ++i32)
{
byte[] binIn = client.testBinary(binOut);
Console.WriteLine(" = " + BytesToHex(binIn));
if (binIn.Length != binOut.Length)
var huge = (i32 > 0);
byte[] binOut = PrepareTestData(false,huge);
Console.Write("testBinary(" + BytesToHex(binOut) + ")");
try
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs)
if (binIn[ofs] != binOut[ofs])
byte[] binIn = client.testBinary(binOut);
Console.WriteLine(" = " + BytesToHex(binIn));
if (binIn.Length != binOut.Length)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
}
catch (Thrift.TApplicationException ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs)
if (binIn[ofs] != binOut[ofs])
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
}
catch (Thrift.TApplicationException ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
}
// binary equals? only with hashcode option enabled ...

View file

@ -41,27 +41,28 @@ namespace Test
public static int _clientID = -1;
public delegate void TestLogDelegate(string msg, params object[] values);
public class TradeServerEventHandler : TServerEventHandler
{
public int callCount = 0;
public void preServe()
{
callCount++;
}
public Object createContext(Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output)
{
callCount++;
return null;
}
public void deleteContext(Object serverContext, Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output)
{
callCount++;
}
public void processContext(Object serverContext, Thrift.Transport.TTransport transport)
{
callCount++;
}
};
public class TradeServerEventHandler : TServerEventHandler
{
public int callCount = 0;
public void preServe()
{
callCount++;
}
public Object createContext(Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output)
{
callCount++;
return null;
}
public void deleteContext(Object serverContext, Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output)
{
callCount++;
}
public void processContext(Object serverContext, Thrift.Transport.TTransport transport)
{
callCount++;
}
};
public class TestHandler : ThriftTest.Iface, Thrift.TControllingHandler
{
@ -273,39 +274,24 @@ namespace Test
return mapmap;
}
// Insanity
// returns:
// { 1 => { 2 => argument,
// 3 => argument,
// },
// 2 => { 6 => <empty Insanity struct>, },
// }
public Dictionary<long, Dictionary<Numberz, Insanity>> testInsanity(Insanity argument)
{
testLogDelegate.Invoke("testInsanity()");
Xtruct hello = new Xtruct();
hello.String_thing = "Hello2";
hello.Byte_thing = 2;
hello.I32_thing = 2;
hello.I64_thing = 2;
Xtruct goodbye = new Xtruct();
goodbye.String_thing = "Goodbye4";
goodbye.Byte_thing = (sbyte)4;
goodbye.I32_thing = 4;
goodbye.I64_thing = (long)4;
Insanity crazy = new Insanity();
crazy.UserMap = new Dictionary<Numberz, long>();
crazy.UserMap[Numberz.EIGHT] = (long)8;
crazy.Xtructs = new List<Xtruct>();
crazy.Xtructs.Add(goodbye);
Insanity looney = new Insanity();
crazy.UserMap[Numberz.FIVE] = (long)5;
crazy.Xtructs.Add(hello);
Dictionary<Numberz, Insanity> first_map = new Dictionary<Numberz, Insanity>();
Dictionary<Numberz, Insanity> second_map = new Dictionary<Numberz, Insanity>(); ;
first_map[Numberz.TWO] = crazy;
first_map[Numberz.THREE] = crazy;
first_map[Numberz.TWO] = argument;
first_map[Numberz.THREE] = argument;
second_map[Numberz.SIX] = looney;
second_map[Numberz.SIX] = new Insanity();
Dictionary<long, Dictionary<Numberz, Insanity>> insane =
new Dictionary<long, Dictionary<Numberz, Insanity>>();
@ -469,7 +455,9 @@ namespace Test
if (useEncryption)
{
string certPath = "../keys/server.p12";
trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath, "thrift"), null, null, SslProtocols.Tls);
trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath, "thrift"),
null,
null, SslProtocols.Tls);
}
else
{

View file

@ -17,8 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-dart/thrift_test/lib/thrift_test.dart: ../ThriftTest.thrift
$(THRIFT) --gen dart ../ThriftTest.thrift
@ -38,6 +36,7 @@ clean-local:
$(RM) -r gen-dart test_client/.pub
find . -type d -name "packages" | xargs $(RM) -r
find . -type f -name ".packages" | xargs $(RM)
find . -type f -name "pubspec.lock" | xargs $(RM)
client: stubs
${DART} test_client/bin/main.dart

View file

@ -16,7 +16,7 @@
# under the License.
name: thrift_test_client
version: 0.10.0
version: 1.0.0-dev
description: A client integration test for the Dart Thrift library
author: Apache Thrift Developers <dev@thrift.apache.org>
homepage: http://thrift.apache.org

View file

@ -17,8 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
THRIFT_FILES = $(wildcard ../*.thrift)
if ERLANG_OTP16

View file

@ -51,8 +51,9 @@ parse_args([Head | Rest], Opts) ->
ssl:start(),
SslOptions =
{ssloptions, [
{certfile, "../keys/client.crt"}
,{keyfile, "../keys/server.key"}
{cacertfile, "../keys/CA.pem"},
{certfile, "../keys/client.pem"},
{keyfile, "../keys/client.key"}
]},
Opts#options{client_opts = [{ssltransport, true} | [SslOptions | Opts#options.client_opts]]};
"--protocol=" ++ Proto ->
@ -159,12 +160,11 @@ start(Args) ->
ClientS4
end,
%% Use deprecated erlang:now until we start requiring OTP18
%% Started = erlang:monotonic_time(milli_seconds),
{_, StartSec, StartUSec} = erlang:now(),
{_, StartSec, StartUSec} = erlang:timestamp(),
error_logger:info_msg("testOneway"),
{Client20, {ok, ok}} = thrift_client:call(Client19, testOneway, [1]),
{_, EndSec, EndUSec} = erlang:now(),
{_, EndSec, EndUSec} = erlang:timestamp(),
Elapsed = (EndSec - StartSec) * 1000 + (EndUSec - StartUSec) / 1000,
if
Elapsed > 1000 -> exit(1);

View file

@ -51,7 +51,7 @@ parse_args([Head | Rest], Opts) ->
ssl:start(),
SslOptions =
{ssloptions, [
{certfile, "../keys/server.crt"}
{certfile, "../keys/server.pem"}
,{keyfile, "../keys/server.key"}
]},
Opts#options{server_opts = [{ssltransport, true} | [SslOptions | Opts#options.server_opts]]};

View file

@ -22,7 +22,7 @@
{description, "Thrift cross language test"},
% The version of the applicaton
{vsn, "0.10.0"},
{vsn, "1.0.0-dev"},
% All modules used by the application.
{modules, [

View file

@ -21,8 +21,10 @@ EXTRA_DIST = \
index.html \
known_failures_Linux.json \
Makefile.am \
nosslv3.sh \
string_limit.py \
tests.json \
theader_binary.py \
setup.cfg \
tls.sh \
util.py

View file

@ -61,7 +61,7 @@ def main(argv):
print('[OK]: just limit')
try:
test_list(proto, list(range(args.limit + 1)))
except:
except Exception:
print('[OK]: limit + 1')
else:
print('[ERROR]: limit + 1')

View file

@ -1,36 +1,50 @@
[
"c_glib-limit_container_length_binary_buffered-ip",
"c_glib-limit_string_length_binary_buffered-ip",
"csharp-limit_container_length_binary_buffered-ip",
"csharp-limit_container_length_compact_buffered-ip",
"csharp-limit_string_length_binary_buffered-ip",
"csharp-limit_string_length_compact_buffered-ip",
"d-limit_container_length_binary_buffered-ip",
"d-limit_container_length_compact_buffered-ip",
"d-limit_string_length_binary_buffered-ip",
"d-limit_string_length_compact_buffered-ip",
"erl-limit_container_length_binary_buffered-ip",
"erl-limit_container_length_compact_buffered-ip",
"erl-limit_string_length_binary_buffered-ip",
"erl-limit_string_length_compact_buffered-ip",
"go-limit_container_length_binary_buffered-ip",
"go-limit_container_length_compact_buffered-ip",
"go-limit_string_length_binary_buffered-ip",
"go-limit_string_length_compact_buffered-ip",
"hs-limit_container_length_binary_buffered-ip",
"hs-limit_container_length_compact_buffered-ip",
"hs-limit_string_length_binary_buffered-ip",
"hs-limit_string_length_compact_buffered-ip",
"nodejs-limit_container_length_binary_buffered-ip",
"nodejs-limit_container_length_compact_buffered-ip",
"nodejs-limit_string_length_binary_buffered-ip",
"nodejs-limit_string_length_compact_buffered-ip",
"perl-limit_container_length_binary_buffered-ip",
"perl-limit_string_length_binary_buffered-ip",
"rb-limit_container_length_accel-binary_buffered-ip",
"rb-limit_container_length_binary_buffered-ip",
"rb-limit_container_length_compact_buffered-ip",
"rb-limit_string_length_accel-binary_buffered-ip",
"rb-limit_string_length_binary_buffered-ip",
"rb-limit_string_length_compact_buffered-ip"
]
"c_glib-limit_container_length_binary_buffered-ip",
"c_glib-limit_string_length_binary_buffered-ip",
"cl-limit_string_length_binary_buffered-ip",
"cl-limit_container_length_binary_buffered-ip",
"cpp-theader_framed_binary_multih-header_buffered-ip",
"cpp-theader_framed_compact_multih-header_buffered-ip",
"cpp-theader_unframed_binary_multih-header_buffered-ip",
"cpp-theader_unframed_compact_multih-header_buffered-ip",
"csharp-limit_container_length_binary_buffered-ip",
"csharp-limit_container_length_compact_buffered-ip",
"csharp-limit_string_length_binary_buffered-ip",
"csharp-limit_string_length_compact_buffered-ip",
"d-limit_container_length_binary_buffered-ip",
"d-limit_container_length_compact_buffered-ip",
"d-limit_string_length_binary_buffered-ip",
"d-limit_string_length_compact_buffered-ip",
"erl-limit_container_length_binary_buffered-ip",
"erl-limit_container_length_compact_buffered-ip",
"erl-limit_string_length_binary_buffered-ip",
"erl-limit_string_length_compact_buffered-ip",
"go-limit_container_length_binary_buffered-ip",
"go-limit_container_length_compact_buffered-ip",
"go-limit_string_length_binary_buffered-ip",
"go-limit_string_length_compact_buffered-ip",
"hs-limit_container_length_binary_buffered-ip",
"hs-limit_container_length_compact_buffered-ip",
"hs-limit_string_length_binary_buffered-ip",
"hs-limit_string_length_compact_buffered-ip",
"nodejs-limit_container_length_binary_buffered-ip",
"nodejs-limit_container_length_compact_buffered-ip",
"nodejs-limit_string_length_binary_buffered-ip",
"nodejs-limit_string_length_compact_buffered-ip",
"perl-limit_container_length_binary_buffered-ip",
"perl-limit_string_length_binary_buffered-ip",
"rb-limit_container_length_accel-binary_buffered-ip",
"rb-limit_container_length_binary_buffered-ip",
"rb-limit_container_length_compact_buffered-ip",
"rb-limit_string_length_accel-binary_buffered-ip",
"rb-limit_string_length_binary_buffered-ip",
"rb-limit_string_length_compact_buffered-ip",
"rs-limit_container_length_binary_buffered-ip",
"rs-limit_container_length_compact_buffered-ip",
"rs-limit_container_length_multic-compact_buffered-ip",
"rs-limit_string_length_binary_buffered-ip",
"rs-limit_string_length_compact_buffered-ip",
"rs-limit_string_length_multic-compact_buffered-ip",
"netcore-limit_string_length_compact_buffered-ip",
"netcore-limit_container_length_compact_buffered-ip"
]

59
vendor/git.apache.org/thrift.git/test/features/nosslv3.sh generated vendored Executable file
View file

@ -0,0 +1,59 @@
#!/bin/bash
#
# Checks to make sure SSLv3 is not allowed by a server.
#
THRIFTHOST=localhost
THRIFTPORT=9090
while [[ $# -ge 1 ]]; do
arg="$1"
argIN=(${arg//=/ })
case ${argIN[0]} in
-h|--host)
THRIFTHOST=${argIN[1]}
shift # past argument
;;
-p|--port)
THRIFTPORT=${argIN[1]}
shift # past argument
;;
*)
# unknown option ignored
;;
esac
shift # past argument or value
done
function nosslv3
{
local nego
local negodenied
local opensslv
opensslv=$(openssl version | cut -d' ' -f2)
if [[ $opensslv > "1.0" ]]; then
echo "[pass] OpenSSL 1.1 or later - no need to check ssl3"
return 0
fi
# echo "openssl s_client -connect $THRIFTHOST:$THRIFTPORT -CAfile ../keys/CA.pem -ssl3 2>&1 < /dev/null"
nego=$(openssl s_client -connect $THRIFTHOST:$THRIFTPORT -CAfile ../keys/CA.pem -ssl3 2>&1 < /dev/null)
negodenied=$?
if [[ $negodenied -ne 0 ]]; then
echo "[pass] SSLv3 negotiation disabled"
echo $nego
return 0
fi
echo "[fail] SSLv3 negotiation enabled! stdout:"
echo $nego
return 1
}
nosslv3
exit $?

View file

@ -51,11 +51,12 @@ def main(argv):
print('[OK]: just limit')
try:
test_string(proto, 'a' * (args.limit + 1))
except:
except Exception:
print('[OK]: limit + 1')
else:
print('[ERROR]: limit + 1')
assert False
if __name__ == '__main__':
main(sys.argv[1:])

View file

@ -66,7 +66,6 @@
"--string-limit=50"
],
"protocols": [
"binary",
"compact"
],
"transports": ["buffered"],
@ -84,11 +83,32 @@
"--container-limit=50"
],
"protocols": [
"binary",
"compact"
],
"transports": ["buffered"],
"sockets": ["ip"],
"workdir": "features"
},
{
"name": "nosslv3",
"comment": "check to make sure SSLv3 is not supported",
"command": [
"nosslv3.sh"
],
"protocols": ["binary"],
"transports": ["buffered"],
"sockets": ["ip-ssl"],
"workdir": "features"
},
{
"name": "tls",
"comment": "check to make sure TLSv1.0 or later is supported",
"command": [
"tls.sh"
],
"protocols": ["binary"],
"transports": ["buffered"],
"sockets": ["ip-ssl"],
"workdir": "features"
}
]

71
vendor/git.apache.org/thrift.git/test/features/tls.sh generated vendored Executable file
View file

@ -0,0 +1,71 @@
#!/bin/bash
#
# Checks to make sure TLSv1.0 or later is allowed by a server.
#
THRIFTHOST=localhost
THRIFTPORT=9090
while [[ $# -ge 1 ]]; do
arg="$1"
argIN=(${arg//=/ })
case ${argIN[0]} in
-h|--host)
THRIFTHOST=${argIN[1]}
shift # past argument
;;
-p|--port)
THRIFTPORT=${argIN[1]}
shift # past argument
;;
*)
# unknown option ignored
;;
esac
shift # past argument or value
done
declare -A EXPECT_NEGOTIATE
EXPECT_NEGOTIATE[tls1]=1
EXPECT_NEGOTIATE[tls1_1]=1
EXPECT_NEGOTIATE[tls1_2]=1
failures=0
function tls
{
for PROTO in "${!EXPECT_NEGOTIATE[@]}"; do
local nego
local negodenied
local res
echo "openssl s_client -connect $THRIFTHOST:$THRIFTPORT -CAfile ../keys/CA.pem -$PROTO 2>&1 < /dev/null"
nego=$(openssl s_client -connect $THRIFTHOST:$THRIFTPORT -CAfile ../keys/CA.pem -$PROTO 2>&1 < /dev/null)
negodenied=$?
echo "result of command: $negodenied"
res="enabled"; if [[ ${EXPECT_NEGOTIATE[$PROTO]} -eq 0 ]]; then res="disabled"; fi
if [[ $negodenied -ne ${EXPECT_NEGOTIATE[$PROTO]} ]]; then
echo "$PROTO negotiation allowed"
else
echo "[warn] $PROTO negotiation did not work"
echo $nego
((failures++))
fi
done
}
tls
if [[ $failures -eq 3 ]]; then
echo "[fail] At least one of TLSv1.0, TLSv1.1, or TLSv1.2 needs to work, but does not"
exit $failures
fi
echo "[pass] At least one of TLSv1.0, TLSv1.1, or TLSv1.2 worked"
exit 0

View file

@ -19,8 +19,7 @@
BUILT_SOURCES = gopath
THRIFT = $(top_builddir)/compiler/cpp/thrift
THRIFTCMD = $(THRIFT) -out src/gen --gen go:thrift_import=thrift
THRIFTCMD = $(THRIFT) -out src/gen --gen go:thrift_import=thrift$(COMPILER_EXTRAFLAG)
THRIFTTEST = $(top_srcdir)/test/ThriftTest.thrift
precross: bin/testclient bin/testserver
@ -28,13 +27,17 @@ precross: bin/testclient bin/testserver
ThriftTest.thrift: $(THRIFTTEST)
grep -v list.*map.*list.*map $(THRIFTTEST) > ThriftTest.thrift
.PHONY: gopath
# Thrift for GO has problems with complex map keys: THRIFT-2063
gopath: $(THRIFT) ThriftTest.thrift
mkdir -p src/gen
$(THRIFTCMD) ThriftTest.thrift
$(THRIFTCMD) ../StressTest.thrift
ln -nfs ../../../lib/go/thrift src/thrift
GOPATH=`pwd` $(GO) get github.com/golang/mock/gomock || true
sed -i 's/\"context\"/\"golang.org\/x\/net\/context\"/g' src/github.com/golang/mock/gomock/controller.go || true
GOPATH=`pwd` $(GO) get github.com/golang/mock/gomock
ln -nfs ../../../lib/go/thrift src/thrift
touch gopath
bin/testclient: gopath
@ -51,7 +54,7 @@ clean-local:
check_PROGRAMS: bin/testclient bin/testserver bin/stress
check: gopath
check: gopath genmock
GOPATH=`pwd` $(GO) test -v common/...
genmock: gopath

View file

@ -20,6 +20,7 @@
package main
import (
"context"
"flag"
"fmt"
"gen/stress"
@ -219,35 +220,35 @@ func client(protocolFactory thrift.TProtocolFactory) {
type handler struct{}
func (h *handler) EchoVoid() (err error) {
func (h *handler) EchoVoid(ctx context.Context) (err error) {
atomic.AddInt64(&counter, 1)
return nil
}
func (h *handler) EchoByte(arg int8) (r int8, err error) {
func (h *handler) EchoByte(ctx context.Context, arg int8) (r int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoI32(arg int32) (r int32, err error) {
func (h *handler) EchoI32(ctx context.Context, arg int32) (r int32, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoI64(arg int64) (r int64, err error) {
func (h *handler) EchoI64(ctx context.Context, arg int64) (r int64, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoString(arg string) (r string, err error) {
func (h *handler) EchoString(ctx context.Context, arg string) (r string, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoList(arg []int8) (r []int8, err error) {
func (h *handler) EchoList(ctx context.Context, arg []int8) (r []int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoSet(arg map[int8]struct{}) (r map[int8]struct{}, err error) {
func (h *handler) EchoSet(ctx context.Context, arg map[int8]struct{}) (r map[int8]struct{}, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoMap(arg map[int8]int8) (r map[int8]int8, err error) {
func (h *handler) EchoMap(ctx context.Context, arg map[int8]int8) (r map[int8]int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}

View file

@ -21,6 +21,7 @@ package main
import (
"common"
"context"
"flag"
"gen/thrifttest"
t "log"
@ -34,11 +35,12 @@ var domain_socket = flag.String("domain-socket", "", "Domain Socket (e.g. /tmp/t
var transport = flag.String("transport", "buffered", "Transport: buffered, framed, http, zlib")
var protocol = flag.String("protocol", "binary", "Protocol: binary, compact, json")
var ssl = flag.Bool("ssl", false, "Encrypted Transport using SSL")
var zlib = flag.Bool("zlib", false, "Wrapped Transport using Zlib")
var testloops = flag.Int("testloops", 1, "Number of Tests")
func main() {
flag.Parse()
client, err := common.StartClient(*host, *port, *domain_socket, *transport, *protocol, *ssl)
client, _, err := common.StartClient(*host, *port, *domain_socket, *transport, *protocol, *ssl)
if err != nil {
t.Fatalf("Unable to start client: ", err)
}
@ -60,14 +62,15 @@ var xxs = &thrifttest.Xtruct{
}
var xcept = &thrifttest.Xception{ErrorCode: 1001, Message: "Xception"}
var defaultCtx = context.Background()
func callEverything(client *thrifttest.ThriftTestClient) {
var err error
if err = client.TestVoid(); err != nil {
if err = client.TestVoid(defaultCtx); err != nil {
t.Fatalf("Unexpected error in TestVoid() call: ", err)
}
thing, err := client.TestString("thing")
thing, err := client.TestString(defaultCtx, "thing")
if err != nil {
t.Fatalf("Unexpected error in TestString() call: ", err)
}
@ -75,14 +78,14 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestString() result, expected 'thing' got '%s' ", thing)
}
bl, err := client.TestBool(true)
bl, err := client.TestBool(defaultCtx, true)
if err != nil {
t.Fatalf("Unexpected error in TestBool() call: ", err)
}
if !bl {
t.Fatalf("Unexpected TestBool() result expected true, got %f ", bl)
}
bl, err = client.TestBool(false)
bl, err = client.TestBool(defaultCtx, false)
if err != nil {
t.Fatalf("Unexpected error in TestBool() call: ", err)
}
@ -90,7 +93,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestBool() result expected false, got %f ", bl)
}
b, err := client.TestByte(42)
b, err := client.TestByte(defaultCtx, 42)
if err != nil {
t.Fatalf("Unexpected error in TestByte() call: ", err)
}
@ -98,7 +101,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestByte() result expected 42, got %d ", b)
}
i32, err := client.TestI32(4242)
i32, err := client.TestI32(defaultCtx, 4242)
if err != nil {
t.Fatalf("Unexpected error in TestI32() call: ", err)
}
@ -106,7 +109,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestI32() result expected 4242, got %d ", i32)
}
i64, err := client.TestI64(424242)
i64, err := client.TestI64(defaultCtx, 424242)
if err != nil {
t.Fatalf("Unexpected error in TestI64() call: ", err)
}
@ -114,7 +117,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestI64() result expected 424242, got %d ", i64)
}
d, err := client.TestDouble(42.42)
d, err := client.TestDouble(defaultCtx, 42.42)
if err != nil {
t.Fatalf("Unexpected error in TestDouble() call: ", err)
}
@ -126,19 +129,19 @@ func callEverything(client *thrifttest.ThriftTestClient) {
for i := 0; i < 256; i++ {
binout[i] = byte(i)
}
bin, err := client.TestBinary(binout)
bin, err := client.TestBinary(defaultCtx, binout)
for i := 0; i < 256; i++ {
if (binout[i] != bin[i]) {
if binout[i] != bin[i] {
t.Fatalf("Unexpected TestBinary() result expected %d, got %d ", binout[i], bin[i])
}
}
xs := thrifttest.NewXtruct()
xs.StringThing = "thing"
xs.ByteThing = 42
xs.I32Thing = 4242
xs.I64Thing = 424242
xsret, err := client.TestStruct(xs)
xsret, err := client.TestStruct(defaultCtx, xs)
if err != nil {
t.Fatalf("Unexpected error in TestStruct() call: ", err)
}
@ -148,7 +151,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
x2 := thrifttest.NewXtruct2()
x2.StructThing = xs
x2ret, err := client.TestNest(x2)
x2ret, err := client.TestNest(defaultCtx, x2)
if err != nil {
t.Fatalf("Unexpected error in TestNest() call: ", err)
}
@ -157,7 +160,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
}
m := map[int32]int32{1: 2, 3: 4, 5: 42}
mret, err := client.TestMap(m)
mret, err := client.TestMap(defaultCtx, m)
if err != nil {
t.Fatalf("Unexpected error in TestMap() call: ", err)
}
@ -166,7 +169,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
}
sm := map[string]string{"a": "2", "b": "blah", "some": "thing"}
smret, err := client.TestStringMap(sm)
smret, err := client.TestStringMap(defaultCtx, sm)
if err != nil {
t.Fatalf("Unexpected error in TestStringMap() call: ", err)
}
@ -174,25 +177,32 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestStringMap() result expected %#v, got %#v ", sm, smret)
}
s := map[int32]struct{}{1: struct{}{}, 2: struct{}{}, 42: struct{}{}}
sret, err := client.TestSet(s)
s := []int32{1, 2, 42}
sret, err := client.TestSet(defaultCtx, s)
if err != nil {
t.Fatalf("Unexpected error in TestSet() call: ", err)
}
if !reflect.DeepEqual(s, sret) {
t.Fatalf("Unexpected TestSet() result expected %#v, got %#v ", s, sret)
// Sets can be in any order, but Go slices are ordered, so reflect.DeepEqual won't work.
stemp := map[int32]struct{}{}
for _, val := range s {
stemp[val] = struct{}{}
}
for _, val := range sret {
if _, ok := stemp[val]; !ok {
t.Fatalf("Unexpected TestSet() result expected %#v, got %#v ", s, sret)
}
}
l := []int32{1, 2, 42}
lret, err := client.TestList(l)
lret, err := client.TestList(defaultCtx, l)
if err != nil {
t.Fatalf("Unexpected error in TestList() call: ", err)
}
if !reflect.DeepEqual(l, lret) {
t.Fatalf("Unexpected TestSet() result expected %#v, got %#v ", l, lret)
t.Fatalf("Unexpected TestList() result expected %#v, got %#v ", l, lret)
}
eret, err := client.TestEnum(thrifttest.Numberz_TWO)
eret, err := client.TestEnum(defaultCtx, thrifttest.Numberz_TWO)
if err != nil {
t.Fatalf("Unexpected error in TestEnum() call: ", err)
}
@ -200,7 +210,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestEnum() result expected %#v, got %#v ", thrifttest.Numberz_TWO, eret)
}
tret, err := client.TestTypedef(thrifttest.UserId(42))
tret, err := client.TestTypedef(defaultCtx, thrifttest.UserId(42))
if err != nil {
t.Fatalf("Unexpected error in TestTypedef() call: ", err)
}
@ -208,7 +218,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestTypedef() result expected %#v, got %#v ", thrifttest.UserId(42), tret)
}
mapmap, err := client.TestMapMap(42)
mapmap, err := client.TestMapMap(defaultCtx, 42)
if err != nil {
t.Fatalf("Unexpected error in TestMapMap() call: ", err)
}
@ -217,44 +227,44 @@ func callEverything(client *thrifttest.ThriftTestClient) {
}
crazy := thrifttest.NewInsanity()
crazy.UserMap = map[thrifttest.Numberz]thrifttest.UserId {
thrifttest.Numberz_FIVE: 5,
crazy.UserMap = map[thrifttest.Numberz]thrifttest.UserId{
thrifttest.Numberz_FIVE: 5,
thrifttest.Numberz_EIGHT: 8,
}
truck1 := thrifttest.NewXtruct()
truck1.StringThing = "Goodbye4"
truck1.ByteThing = 4;
truck1.I32Thing = 4;
truck1.I64Thing = 4;
truck1.ByteThing = 4
truck1.I32Thing = 4
truck1.I64Thing = 4
truck2 := thrifttest.NewXtruct()
truck2.StringThing = "Hello2"
truck2.ByteThing = 2;
truck2.I32Thing = 2;
truck2.I64Thing = 2;
crazy.Xtructs = []*thrifttest.Xtruct {
truck2.ByteThing = 2
truck2.I32Thing = 2
truck2.I64Thing = 2
crazy.Xtructs = []*thrifttest.Xtruct{
truck1,
truck2,
}
insanity, err := client.TestInsanity(crazy)
insanity, err := client.TestInsanity(defaultCtx, crazy)
if err != nil {
t.Fatalf("Unexpected error in TestInsanity() call: ", err)
}
if !reflect.DeepEqual(crazy, insanity[1][2]) {
t.Fatalf("Unexpected TestInsanity() first result expected %#v, got %#v ",
crazy,
insanity[1][2])
crazy,
insanity[1][2])
}
if !reflect.DeepEqual(crazy, insanity[1][3]) {
t.Fatalf("Unexpected TestInsanity() second result expected %#v, got %#v ",
crazy,
insanity[1][3])
crazy,
insanity[1][3])
}
if len(insanity[2][6].UserMap) > 0 || len(insanity[2][6].Xtructs) > 0 {
t.Fatalf("Unexpected TestInsanity() non-empty result got %#v ",
insanity[2][6])
insanity[2][6])
}
xxsret, err := client.TestMulti(42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24))
xxsret, err := client.TestMulti(defaultCtx, 42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24))
if err != nil {
t.Fatalf("Unexpected error in TestMulti() call: ", err)
}
@ -262,7 +272,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestMulti() result expected %#v, got %#v ", xxs, xxsret)
}
err = client.TestException("Xception")
err = client.TestException(defaultCtx, "Xception")
if err == nil {
t.Fatalf("Expecting exception in TestException() call")
}
@ -270,13 +280,13 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestException() result expected %#v, got %#v ", xcept, err)
}
err = client.TestException("TException")
err = client.TestException(defaultCtx, "TException")
_, ok := err.(thrift.TApplicationException)
if err == nil || !ok {
t.Fatalf("Unexpected TestException() result expected ApplicationError, got %#v ", err)
}
ign, err := client.TestMultiException("Xception", "ignoreme")
ign, err := client.TestMultiException(defaultCtx, "Xception", "ignoreme")
if ign != nil || err == nil {
t.Fatalf("Expecting exception in TestMultiException() call")
}
@ -284,7 +294,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestMultiException() %#v ", err)
}
ign, err = client.TestMultiException("Xception2", "ignoreme")
ign, err = client.TestMultiException(defaultCtx, "Xception2", "ignoreme")
if ign != nil || err == nil {
t.Fatalf("Expecting exception in TestMultiException() call")
}
@ -294,13 +304,13 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestMultiException() %#v ", err)
}
err = client.TestOneway(2)
err = client.TestOneway(defaultCtx, 2)
if err != nil {
t.Fatalf("Unexpected error in TestOneway() call: ", err)
}
//Make sure the connection still alive
if err = client.TestVoid(); err != nil {
if err = client.TestVoid(defaultCtx); err != nil {
t.Fatalf("Unexpected error in TestVoid() call: ", err)
}
}

View file

@ -34,6 +34,7 @@ var domain_socket = flag.String("domain-socket", "", "Domain Socket (e.g. /tmp/T
var transport = flag.String("transport", "buffered", "Transport: buffered, framed, http, zlib")
var protocol = flag.String("protocol", "binary", "Protocol: binary, compact, json")
var ssl = flag.Bool("ssl", false, "Encrypted Transport using SSL")
var zlib = flag.Bool("zlib", false, "Wrapped Transport using Zlib")
var certPath = flag.String("certPath", "keys", "Directory that contains SSL certificates")
func main() {

View file

@ -41,7 +41,7 @@ func StartClient(
domain_socket string,
transport string,
protocol string,
ssl bool) (client *thrifttest.ThriftTestClient, err error) {
ssl bool) (client *thrifttest.ThriftTestClient, trans thrift.TTransport, err error) {
hostPort := fmt.Sprintf("%s:%d", host, port)
@ -56,12 +56,11 @@ func StartClient(
case "binary":
protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
default:
return nil, fmt.Errorf("Invalid protocol specified %s", protocol)
return nil, nil, fmt.Errorf("Invalid protocol specified %s", protocol)
}
if debugClientProtocol {
protocolFactory = thrift.NewTDebugProtocolFactory(protocolFactory, "client:")
}
var trans thrift.TTransport
if ssl {
trans, err = thrift.NewTSSLSocket(hostPort, &tls.Config{InsecureSkipVerify: true})
} else {
@ -72,7 +71,7 @@ func StartClient(
}
}
if err != nil {
return nil, err
return nil, nil, err
}
switch transport {
case "http":
@ -86,29 +85,25 @@ func StartClient(
} else {
trans, err = thrift.NewTHttpPostClient(fmt.Sprintf("http://%s/", hostPort))
}
if err != nil {
return nil, err
}
case "framed":
trans = thrift.NewTFramedTransport(trans)
case "buffered":
trans = thrift.NewTBufferedTransport(trans, 8192)
case "zlib":
trans, err = thrift.NewTZlibTransport(trans, zlib.BestCompression)
if err != nil {
return nil, err
}
case "":
trans = trans
default:
return nil, fmt.Errorf("Invalid transport specified %s", transport)
return nil, nil, fmt.Errorf("Invalid transport specified %s", transport)
}
if err != nil {
return nil, nil, err
}
if err = trans.Open(); err != nil {
return nil, err
return nil, nil, err
}
client = thrifttest.NewThriftTestClientFactory(trans, protocolFactory)
iprot := protocolFactory.GetProtocol(trans)
oprot := protocolFactory.GetProtocol(trans)
client = thrifttest.NewThriftTestClient(thrift.NewTStandardClient(iprot, oprot))
return
}

View file

@ -20,9 +20,11 @@
package common
import (
"context"
"errors"
"gen/thrifttest"
"reflect"
"sync"
"testing"
"thrift"
@ -47,10 +49,15 @@ var units = []test_unit{
func TestAllConnection(t *testing.T) {
certPath = "../../../keys"
wg := &sync.WaitGroup{}
wg.Add(len(units))
for _, unit := range units {
t.Logf("%#v", unit)
doUnit(t, &unit)
go func(u test_unit) {
defer wg.Done()
doUnit(t, &u)
}(unit)
}
wg.Wait()
}
func doUnit(t *testing.T, unit *test_unit) {
@ -62,17 +69,17 @@ func doUnit(t *testing.T, unit *test_unit) {
server := thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory)
if err = server.Listen(); err != nil {
t.Errorf("Unable to start server", err)
t.FailNow()
t.Errorf("Unable to start server: %v", err)
return
}
go server.AcceptLoop()
defer server.Stop()
client, err := StartClient(unit.host, unit.port, unit.domain_socket, unit.transport, unit.protocol, unit.ssl)
client, trans, err := StartClient(unit.host, unit.port, unit.domain_socket, unit.transport, unit.protocol, unit.ssl)
if err != nil {
t.Errorf("Unable to start client", err)
t.FailNow()
t.Errorf("Unable to start client: %v", err)
return
}
defer client.Transport.Close()
defer trans.Close()
callEverythingWithMock(t, client, handler)
}
@ -89,91 +96,92 @@ var xxs = &thrifttest.Xtruct{
}
var xcept = &thrifttest.Xception{ErrorCode: 1001, Message: "some"}
var defaultCtx = context.Background()
func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, handler *MockThriftTest) {
gomock.InOrder(
handler.EXPECT().TestVoid(),
handler.EXPECT().TestString("thing").Return("thing", nil),
handler.EXPECT().TestBool(true).Return(true, nil),
handler.EXPECT().TestBool(false).Return(false, nil),
handler.EXPECT().TestByte(int8(42)).Return(int8(42), nil),
handler.EXPECT().TestI32(int32(4242)).Return(int32(4242), nil),
handler.EXPECT().TestI64(int64(424242)).Return(int64(424242), nil),
handler.EXPECT().TestVoid(gomock.Any()),
handler.EXPECT().TestString(gomock.Any(), "thing").Return("thing", nil),
handler.EXPECT().TestBool(gomock.Any(), true).Return(true, nil),
handler.EXPECT().TestBool(gomock.Any(), false).Return(false, nil),
handler.EXPECT().TestByte(gomock.Any(), int8(42)).Return(int8(42), nil),
handler.EXPECT().TestI32(gomock.Any(), int32(4242)).Return(int32(4242), nil),
handler.EXPECT().TestI64(gomock.Any(), int64(424242)).Return(int64(424242), nil),
// TODO: add TestBinary()
handler.EXPECT().TestDouble(float64(42.42)).Return(float64(42.42), nil),
handler.EXPECT().TestStruct(&thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}).Return(&thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}, nil),
handler.EXPECT().TestNest(&thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}).Return(&thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}, nil),
handler.EXPECT().TestMap(map[int32]int32{1: 2, 3: 4, 5: 42}).Return(map[int32]int32{1: 2, 3: 4, 5: 42}, nil),
handler.EXPECT().TestStringMap(map[string]string{"a": "2", "b": "blah", "some": "thing"}).Return(map[string]string{"a": "2", "b": "blah", "some": "thing"}, nil),
handler.EXPECT().TestSet(map[int32]struct{}{1: struct{}{}, 2: struct{}{}, 42: struct{}{}}).Return(map[int32]struct{}{1: struct{}{}, 2: struct{}{}, 42: struct{}{}}, nil),
handler.EXPECT().TestList([]int32{1, 2, 42}).Return([]int32{1, 2, 42}, nil),
handler.EXPECT().TestEnum(thrifttest.Numberz_TWO).Return(thrifttest.Numberz_TWO, nil),
handler.EXPECT().TestTypedef(thrifttest.UserId(42)).Return(thrifttest.UserId(42), nil),
handler.EXPECT().TestMapMap(int32(42)).Return(rmapmap, nil),
handler.EXPECT().TestDouble(gomock.Any(), float64(42.42)).Return(float64(42.42), nil),
handler.EXPECT().TestStruct(gomock.Any(), &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}).Return(&thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}, nil),
handler.EXPECT().TestNest(gomock.Any(), &thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}).Return(&thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}, nil),
handler.EXPECT().TestMap(gomock.Any(), map[int32]int32{1: 2, 3: 4, 5: 42}).Return(map[int32]int32{1: 2, 3: 4, 5: 42}, nil),
handler.EXPECT().TestStringMap(gomock.Any(), map[string]string{"a": "2", "b": "blah", "some": "thing"}).Return(map[string]string{"a": "2", "b": "blah", "some": "thing"}, nil),
handler.EXPECT().TestSet(gomock.Any(), []int32{1, 2, 42}).Return([]int32{1, 2, 42}, nil),
handler.EXPECT().TestList(gomock.Any(), []int32{1, 2, 42}).Return([]int32{1, 2, 42}, nil),
handler.EXPECT().TestEnum(gomock.Any(), thrifttest.Numberz_TWO).Return(thrifttest.Numberz_TWO, nil),
handler.EXPECT().TestTypedef(gomock.Any(), thrifttest.UserId(42)).Return(thrifttest.UserId(42), nil),
handler.EXPECT().TestMapMap(gomock.Any(), int32(42)).Return(rmapmap, nil),
// TODO: not testing insanity
handler.EXPECT().TestMulti(int8(42), int32(4242), int64(424242), map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24)).Return(xxs, nil),
handler.EXPECT().TestException("some").Return(xcept),
handler.EXPECT().TestException("TException").Return(errors.New("Just random exception")),
handler.EXPECT().TestMultiException("Xception", "ignoreme").Return(nil, &thrifttest.Xception{ErrorCode: 1001, Message: "This is an Xception"}),
handler.EXPECT().TestMultiException("Xception2", "ignoreme").Return(nil, &thrifttest.Xception2{ErrorCode: 2002, StructThing: &thrifttest.Xtruct{StringThing: "This is an Xception2"}}),
handler.EXPECT().TestOneway(int32(2)).Return(nil),
handler.EXPECT().TestVoid(),
handler.EXPECT().TestMulti(gomock.Any(), int8(42), int32(4242), int64(424242), map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24)).Return(xxs, nil),
handler.EXPECT().TestException(gomock.Any(), "some").Return(xcept),
handler.EXPECT().TestException(gomock.Any(), "TException").Return(errors.New("Just random exception")),
handler.EXPECT().TestMultiException(gomock.Any(), "Xception", "ignoreme").Return(nil, &thrifttest.Xception{ErrorCode: 1001, Message: "This is an Xception"}),
handler.EXPECT().TestMultiException(gomock.Any(), "Xception2", "ignoreme").Return(nil, &thrifttest.Xception2{ErrorCode: 2002, StructThing: &thrifttest.Xtruct{StringThing: "This is an Xception2"}}),
handler.EXPECT().TestOneway(gomock.Any(), int32(2)).Return(nil),
handler.EXPECT().TestVoid(gomock.Any()),
)
var err error
if err = client.TestVoid(); err != nil {
t.Errorf("Unexpected error in TestVoid() call: ", err)
if err = client.TestVoid(defaultCtx); err != nil {
t.Errorf("Unexpected error in TestVoid() call: %s", err)
}
thing, err := client.TestString("thing")
thing, err := client.TestString(defaultCtx, "thing")
if err != nil {
t.Errorf("Unexpected error in TestString() call: ", err)
t.Errorf("Unexpected error in TestString() call: %s", err)
}
if thing != "thing" {
t.Errorf("Unexpected TestString() result, expected 'thing' got '%s' ", thing)
}
bl, err := client.TestBool(true)
bl, err := client.TestBool(defaultCtx, true)
if err != nil {
t.Errorf("Unexpected error in TestBool() call: ", err)
t.Errorf("Unexpected error in TestBool() call: %s", err)
}
if !bl {
t.Errorf("Unexpected TestBool() result expected true, got %f ", bl)
t.Errorf("Unexpected TestBool() result expected true, got %v ", bl)
}
bl, err = client.TestBool(false)
bl, err = client.TestBool(defaultCtx, false)
if err != nil {
t.Errorf("Unexpected error in TestBool() call: ", err)
t.Errorf("Unexpected error in TestBool() call: %s", err)
}
if bl {
t.Errorf("Unexpected TestBool() result expected false, got %f ", bl)
t.Errorf("Unexpected TestBool() result expected false, got %v ", bl)
}
b, err := client.TestByte(42)
b, err := client.TestByte(defaultCtx, 42)
if err != nil {
t.Errorf("Unexpected error in TestByte() call: ", err)
t.Errorf("Unexpected error in TestByte() call: %s", err)
}
if b != 42 {
t.Errorf("Unexpected TestByte() result expected 42, got %d ", b)
}
i32, err := client.TestI32(4242)
i32, err := client.TestI32(defaultCtx, 4242)
if err != nil {
t.Errorf("Unexpected error in TestI32() call: ", err)
t.Errorf("Unexpected error in TestI32() call: %s", err)
}
if i32 != 4242 {
t.Errorf("Unexpected TestI32() result expected 4242, got %d ", i32)
}
i64, err := client.TestI64(424242)
i64, err := client.TestI64(defaultCtx, 424242)
if err != nil {
t.Errorf("Unexpected error in TestI64() call: ", err)
t.Errorf("Unexpected error in TestI64() call: %s", err)
}
if i64 != 424242 {
t.Errorf("Unexpected TestI64() result expected 424242, got %d ", i64)
}
d, err := client.TestDouble(42.42)
d, err := client.TestDouble(defaultCtx, 42.42)
if err != nil {
t.Errorf("Unexpected error in TestDouble() call: ", err)
t.Errorf("Unexpected error in TestDouble() call: %s", err)
}
if d != 42.42 {
t.Errorf("Unexpected TestDouble() result expected 42.42, got %f ", d)
@ -186,9 +194,9 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
xs.ByteThing = 42
xs.I32Thing = 4242
xs.I64Thing = 424242
xsret, err := client.TestStruct(xs)
xsret, err := client.TestStruct(defaultCtx, xs)
if err != nil {
t.Errorf("Unexpected error in TestStruct() call: ", err)
t.Errorf("Unexpected error in TestStruct() call: %s", err)
}
if *xs != *xsret {
t.Errorf("Unexpected TestStruct() result expected %#v, got %#v ", xs, xsret)
@ -196,83 +204,90 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
x2 := thrifttest.NewXtruct2()
x2.StructThing = xs
x2ret, err := client.TestNest(x2)
x2ret, err := client.TestNest(defaultCtx, x2)
if err != nil {
t.Errorf("Unexpected error in TestNest() call: ", err)
t.Errorf("Unexpected error in TestNest() call: %s", err)
}
if !reflect.DeepEqual(x2, x2ret) {
t.Errorf("Unexpected TestNest() result expected %#v, got %#v ", x2, x2ret)
}
m := map[int32]int32{1: 2, 3: 4, 5: 42}
mret, err := client.TestMap(m)
mret, err := client.TestMap(defaultCtx, m)
if err != nil {
t.Errorf("Unexpected error in TestMap() call: ", err)
t.Errorf("Unexpected error in TestMap() call: %s", err)
}
if !reflect.DeepEqual(m, mret) {
t.Errorf("Unexpected TestMap() result expected %#v, got %#v ", m, mret)
}
sm := map[string]string{"a": "2", "b": "blah", "some": "thing"}
smret, err := client.TestStringMap(sm)
smret, err := client.TestStringMap(defaultCtx, sm)
if err != nil {
t.Errorf("Unexpected error in TestStringMap() call: ", err)
t.Errorf("Unexpected error in TestStringMap() call: %s", err)
}
if !reflect.DeepEqual(sm, smret) {
t.Errorf("Unexpected TestStringMap() result expected %#v, got %#v ", sm, smret)
}
s := map[int32]struct{}{1: struct{}{}, 2: struct{}{}, 42: struct{}{}}
sret, err := client.TestSet(s)
s := []int32{1, 2, 42}
sret, err := client.TestSet(defaultCtx, s)
if err != nil {
t.Errorf("Unexpected error in TestSet() call: ", err)
t.Errorf("Unexpected error in TestSet() call: %s", err)
}
if !reflect.DeepEqual(s, sret) {
t.Errorf("Unexpected TestSet() result expected %#v, got %#v ", s, sret)
// Sets can be in any order, but Go slices are ordered, so reflect.DeepEqual won't work.
stemp := map[int32]struct{}{}
for _, val := range s {
stemp[val] = struct{}{}
}
for _, val := range sret {
if _, ok := stemp[val]; !ok {
t.Fatalf("Unexpected TestSet() result expected %#v, got %#v ", s, sret)
}
}
l := []int32{1, 2, 42}
lret, err := client.TestList(l)
lret, err := client.TestList(defaultCtx, l)
if err != nil {
t.Errorf("Unexpected error in TestList() call: ", err)
t.Errorf("Unexpected error in TestList() call: %s", err)
}
if !reflect.DeepEqual(l, lret) {
t.Errorf("Unexpected TestSet() result expected %#v, got %#v ", l, lret)
t.Errorf("Unexpected TestList() result expected %#v, got %#v ", l, lret)
}
eret, err := client.TestEnum(thrifttest.Numberz_TWO)
eret, err := client.TestEnum(defaultCtx, thrifttest.Numberz_TWO)
if err != nil {
t.Errorf("Unexpected error in TestEnum() call: ", err)
t.Errorf("Unexpected error in TestEnum() call: %s", err)
}
if eret != thrifttest.Numberz_TWO {
t.Errorf("Unexpected TestEnum() result expected %#v, got %#v ", thrifttest.Numberz_TWO, eret)
}
tret, err := client.TestTypedef(thrifttest.UserId(42))
tret, err := client.TestTypedef(defaultCtx, thrifttest.UserId(42))
if err != nil {
t.Errorf("Unexpected error in TestTypedef() call: ", err)
t.Errorf("Unexpected error in TestTypedef() call: %s", err)
}
if tret != thrifttest.UserId(42) {
t.Errorf("Unexpected TestTypedef() result expected %#v, got %#v ", thrifttest.UserId(42), tret)
}
mapmap, err := client.TestMapMap(42)
mapmap, err := client.TestMapMap(defaultCtx, 42)
if err != nil {
t.Errorf("Unexpected error in TestMapmap() call: ", err)
t.Errorf("Unexpected error in TestMapmap() call: %s", err)
}
if !reflect.DeepEqual(mapmap, rmapmap) {
t.Errorf("Unexpected TestMapmap() result expected %#v, got %#v ", rmapmap, mapmap)
}
xxsret, err := client.TestMulti(42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24))
xxsret, err := client.TestMulti(defaultCtx, 42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24))
if err != nil {
t.Errorf("Unexpected error in TestMulti() call: ", err)
t.Errorf("Unexpected error in TestMulti() call: %s", err)
}
if !reflect.DeepEqual(xxs, xxsret) {
t.Errorf("Unexpected TestMulti() result expected %#v, got %#v ", xxs, xxsret)
}
err = client.TestException("some")
err = client.TestException(defaultCtx, "some")
if err == nil {
t.Errorf("Expecting exception in TestException() call")
}
@ -281,13 +296,16 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
}
// TODO: connection is being closed on this
err = client.TestException("TException")
tex, ok := err.(thrift.TApplicationException)
if err == nil || !ok || tex.TypeId() != thrift.INTERNAL_ERROR {
t.Errorf("Unexpected TestException() result expected ApplicationError, got %#v ", err)
err = client.TestException(defaultCtx, "TException")
if err == nil {
t.Error("expected exception got nil")
} else if tex, ok := err.(thrift.TApplicationException); !ok {
t.Errorf("Unexpected TestException() result expected ApplicationError, got %T ", err)
} else if tex.TypeId() != thrift.INTERNAL_ERROR {
t.Errorf("expected internal_error got %v", tex.TypeId())
}
ign, err := client.TestMultiException("Xception", "ignoreme")
ign, err := client.TestMultiException(defaultCtx, "Xception", "ignoreme")
if ign != nil || err == nil {
t.Errorf("Expecting exception in TestMultiException() call")
}
@ -295,7 +313,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestMultiException() %#v ", err)
}
ign, err = client.TestMultiException("Xception2", "ignoreme")
ign, err = client.TestMultiException(defaultCtx, "Xception2", "ignoreme")
if ign != nil || err == nil {
t.Errorf("Expecting exception in TestMultiException() call")
}
@ -305,13 +323,13 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestMultiException() %#v ", err)
}
err = client.TestOneway(2)
err = client.TestOneway(defaultCtx, 2)
if err != nil {
t.Errorf("Unexpected error in TestOneway() call: ", err)
t.Errorf("Unexpected error in TestOneway() call: %s", err)
}
//Make sure the connection still alive
if err = client.TestVoid(); err != nil {
t.Errorf("Unexpected error in TestVoid() call: ", err)
if err = client.TestVoid(defaultCtx); err != nil {
t.Errorf("Unexpected error in TestVoid() call: %s", err)
}
}

View file

@ -0,0 +1,98 @@
/*
* 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.
*/
package common
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"os"
"syscall"
"testing"
"thrift"
"time"
)
type slowHttpHandler struct{}
func (slowHttpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
time.Sleep(1 * time.Second)
}
func TestHttpContextTimeout(t *testing.T) {
certPath = "../../../keys"
unit := test_unit{"127.0.0.1", 9096, "", "http", "binary", false}
server := &http.Server{Addr: unit.host + fmt.Sprintf(":%d", unit.port), Handler: slowHttpHandler{}}
go server.ListenAndServe()
client, trans, err := StartClient(unit.host, unit.port, unit.domain_socket, unit.transport, unit.protocol, unit.ssl)
if err != nil {
t.Errorf("Unable to start client: %v", err)
return
}
defer trans.Close()
unwrapErr := func(err error) error {
for {
switch err.(type) {
case thrift.TTransportException:
err = err.(thrift.TTransportException).Err()
case *url.Error:
err = err.(*url.Error).Err
case *net.OpError:
err = err.(*net.OpError).Err
case *os.SyscallError:
err = err.(*os.SyscallError).Err
default:
return err
}
}
}
serverStartupDeadline := time.Now().Add(5 * time.Second)
for {
ctx, _ := context.WithTimeout(context.Background(), 50*time.Millisecond)
err = client.TestVoid(ctx)
err = unwrapErr(err)
if err != syscall.ECONNREFUSED || time.Now().After(serverStartupDeadline) {
break
}
time.Sleep(time.Millisecond)
}
if err == nil {
t.Errorf("Request completed (should have timed out)")
return
}
// We've got to switch on `err.Error()` here since go1.7 doesn't properly return
// `context.DeadlineExceeded` error and `http.errRequestCanceled` is not exported.
// See https://github.com/golang/go/issues/17711
switch err.Error() {
case context.DeadlineExceeded.Error(), "net/http: request canceled":
// Expected error
default:
t.Errorf("Unexpected error: %s", err)
}
}

View file

@ -1,289 +0,0 @@
/*
* 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.
*/
// Automatically generated by MockGen. DO NOT EDIT!
// Source: gen/thrifttest (interfaces: ThriftTest)
package common
import (
gomock "github.com/golang/mock/gomock"
thrifttest "gen/thrifttest"
)
// Mock of ThriftTest interface
type MockThriftTest struct {
ctrl *gomock.Controller
recorder *_MockThriftTestRecorder
}
// Recorder for MockThriftTest (not exported)
type _MockThriftTestRecorder struct {
mock *MockThriftTest
}
func NewMockThriftTest(ctrl *gomock.Controller) *MockThriftTest {
mock := &MockThriftTest{ctrl: ctrl}
mock.recorder = &_MockThriftTestRecorder{mock}
return mock
}
func (_m *MockThriftTest) EXPECT() *_MockThriftTestRecorder {
return _m.recorder
}
func (_m *MockThriftTest) TestBool(_param0 bool) (bool, error) {
ret := _m.ctrl.Call(_m, "TestBool", _param0)
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestBool(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestBool", arg0)
}
func (_m *MockThriftTest) TestByte(_param0 int8) (int8, error) {
ret := _m.ctrl.Call(_m, "TestByte", _param0)
ret0, _ := ret[0].(int8)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestByte(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestByte", arg0)
}
func (_m *MockThriftTest) TestDouble(_param0 float64) (float64, error) {
ret := _m.ctrl.Call(_m, "TestDouble", _param0)
ret0, _ := ret[0].(float64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestDouble(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestDouble", arg0)
}
func (_m *MockThriftTest) TestBinary(_param0 []byte) ([]byte, error) {
ret := _m.ctrl.Call(_m, "TestBinary", _param0)
ret0, _ := ret[0].([]byte)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestBinary(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestBinary", arg0)
}
func (_m *MockThriftTest) TestEnum(_param0 thrifttest.Numberz) (thrifttest.Numberz, error) {
ret := _m.ctrl.Call(_m, "TestEnum", _param0)
ret0, _ := ret[0].(thrifttest.Numberz)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestEnum(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestEnum", arg0)
}
func (_m *MockThriftTest) TestException(_param0 string) error {
ret := _m.ctrl.Call(_m, "TestException", _param0)
ret0, _ := ret[0].(error)
return ret0
}
func (_mr *_MockThriftTestRecorder) TestException(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestException", arg0)
}
func (_m *MockThriftTest) TestI32(_param0 int32) (int32, error) {
ret := _m.ctrl.Call(_m, "TestI32", _param0)
ret0, _ := ret[0].(int32)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestI32(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestI32", arg0)
}
func (_m *MockThriftTest) TestI64(_param0 int64) (int64, error) {
ret := _m.ctrl.Call(_m, "TestI64", _param0)
ret0, _ := ret[0].(int64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestI64(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestI64", arg0)
}
func (_m *MockThriftTest) TestInsanity(_param0 *thrifttest.Insanity) (map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity, error) {
ret := _m.ctrl.Call(_m, "TestInsanity", _param0)
ret0, _ := ret[0].(map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestInsanity(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestInsanity", arg0)
}
func (_m *MockThriftTest) TestList(_param0 []int32) ([]int32, error) {
ret := _m.ctrl.Call(_m, "TestList", _param0)
ret0, _ := ret[0].([]int32)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestList(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestList", arg0)
}
func (_m *MockThriftTest) TestMap(_param0 map[int32]int32) (map[int32]int32, error) {
ret := _m.ctrl.Call(_m, "TestMap", _param0)
ret0, _ := ret[0].(map[int32]int32)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestMap(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMap", arg0)
}
func (_m *MockThriftTest) TestMapMap(_param0 int32) (map[int32]map[int32]int32, error) {
ret := _m.ctrl.Call(_m, "TestMapMap", _param0)
ret0, _ := ret[0].(map[int32]map[int32]int32)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestMapMap(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMapMap", arg0)
}
func (_m *MockThriftTest) TestMulti(_param0 int8, _param1 int32, _param2 int64, _param3 map[int16]string, _param4 thrifttest.Numberz, _param5 thrifttest.UserId) (*thrifttest.Xtruct, error) {
ret := _m.ctrl.Call(_m, "TestMulti", _param0, _param1, _param2, _param3, _param4, _param5)
ret0, _ := ret[0].(*thrifttest.Xtruct)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestMulti(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMulti", arg0, arg1, arg2, arg3, arg4, arg5)
}
func (_m *MockThriftTest) TestMultiException(_param0 string, _param1 string) (*thrifttest.Xtruct, error) {
ret := _m.ctrl.Call(_m, "TestMultiException", _param0, _param1)
ret0, _ := ret[0].(*thrifttest.Xtruct)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestMultiException(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMultiException", arg0, arg1)
}
func (_m *MockThriftTest) TestNest(_param0 *thrifttest.Xtruct2) (*thrifttest.Xtruct2, error) {
ret := _m.ctrl.Call(_m, "TestNest", _param0)
ret0, _ := ret[0].(*thrifttest.Xtruct2)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestNest(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestNest", arg0)
}
func (_m *MockThriftTest) TestOneway(_param0 int32) error {
ret := _m.ctrl.Call(_m, "TestOneway", _param0)
ret0, _ := ret[0].(error)
return ret0
}
func (_mr *_MockThriftTestRecorder) TestOneway(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestOneway", arg0)
}
func (_m *MockThriftTest) TestSet(_param0 map[int32]struct{}) (map[int32]struct{}, error) {
ret := _m.ctrl.Call(_m, "TestSet", _param0)
ret0, _ := ret[0].(map[int32]struct{})
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestSet(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestSet", arg0)
}
func (_m *MockThriftTest) TestString(_param0 string) (string, error) {
ret := _m.ctrl.Call(_m, "TestString", _param0)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestString(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestString", arg0)
}
func (_m *MockThriftTest) TestStringMap(_param0 map[string]string) (map[string]string, error) {
ret := _m.ctrl.Call(_m, "TestStringMap", _param0)
ret0, _ := ret[0].(map[string]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestStringMap(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestStringMap", arg0)
}
func (_m *MockThriftTest) TestStruct(_param0 *thrifttest.Xtruct) (*thrifttest.Xtruct, error) {
ret := _m.ctrl.Call(_m, "TestStruct", _param0)
ret0, _ := ret[0].(*thrifttest.Xtruct)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestStruct(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestStruct", arg0)
}
func (_m *MockThriftTest) TestTypedef(_param0 thrifttest.UserId) (thrifttest.UserId, error) {
ret := _m.ctrl.Call(_m, "TestTypedef", _param0)
ret0, _ := ret[0].(thrifttest.UserId)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestTypedef(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestTypedef", arg0)
}
func (_m *MockThriftTest) TestVoid() error {
ret := _m.ctrl.Call(_m, "TestVoid")
ret0, _ := ret[0].(error)
return ret0
}
func (_mr *_MockThriftTestRecorder) TestVoid() *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestVoid")
}

View file

@ -20,9 +20,10 @@
package common
import (
"context"
"encoding/hex"
"errors"
"fmt"
"encoding/hex"
. "gen/thrifttest"
"time"
)
@ -32,7 +33,7 @@ var PrintingHandler = &printingHandler{}
type printingHandler struct{}
// Prints "testVoid()" and returns nothing.
func (p *printingHandler) TestVoid() (err error) {
func (p *printingHandler) TestVoid(ctx context.Context) (err error) {
fmt.Println("testVoid()")
return nil
}
@ -43,7 +44,7 @@ func (p *printingHandler) TestVoid() (err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestString(thing string) (r string, err error) {
func (p *printingHandler) TestString(ctx context.Context, thing string) (r string, err error) {
fmt.Printf("testString(\"%s\")\n", thing)
return thing, nil
}
@ -54,7 +55,7 @@ func (p *printingHandler) TestString(thing string) (r string, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestBool(thing bool) (r bool, err error) {
func (p *printingHandler) TestBool(ctx context.Context, thing bool) (r bool, err error) {
fmt.Printf("testBool(%t)\n", thing)
return thing, nil
}
@ -65,7 +66,7 @@ func (p *printingHandler) TestBool(thing bool) (r bool, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestByte(thing int8) (r int8, err error) {
func (p *printingHandler) TestByte(ctx context.Context, thing int8) (r int8, err error) {
fmt.Printf("testByte(%d)\n", thing)
return thing, nil
}
@ -76,7 +77,7 @@ func (p *printingHandler) TestByte(thing int8) (r int8, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestI32(thing int32) (r int32, err error) {
func (p *printingHandler) TestI32(ctx context.Context, thing int32) (r int32, err error) {
fmt.Printf("testI32(%d)\n", thing)
return thing, nil
}
@ -87,7 +88,7 @@ func (p *printingHandler) TestI32(thing int32) (r int32, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestI64(thing int64) (r int64, err error) {
func (p *printingHandler) TestI64(ctx context.Context, thing int64) (r int64, err error) {
fmt.Printf("testI64(%d)\n", thing)
return thing, nil
}
@ -98,7 +99,7 @@ func (p *printingHandler) TestI64(thing int64) (r int64, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestDouble(thing float64) (r float64, err error) {
func (p *printingHandler) TestDouble(ctx context.Context, thing float64) (r float64, err error) {
fmt.Printf("testDouble(%f)\n", thing)
return thing, nil
}
@ -109,7 +110,7 @@ func (p *printingHandler) TestDouble(thing float64) (r float64, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestBinary(thing []byte) (r []byte, err error) {
func (p *printingHandler) TestBinary(ctx context.Context, thing []byte) (r []byte, err error) {
fmt.Printf("testBinary(%s)\n", hex.EncodeToString(thing))
return thing, nil
}
@ -120,7 +121,7 @@ func (p *printingHandler) TestBinary(thing []byte) (r []byte, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestStruct(thing *Xtruct) (r *Xtruct, err error) {
func (p *printingHandler) TestStruct(ctx context.Context, thing *Xtruct) (r *Xtruct, err error) {
fmt.Printf("testStruct({\"%s\", %d, %d, %d})\n", thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing)
return thing, err
}
@ -131,7 +132,7 @@ func (p *printingHandler) TestStruct(thing *Xtruct) (r *Xtruct, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestNest(nest *Xtruct2) (r *Xtruct2, err error) {
func (p *printingHandler) TestNest(ctx context.Context, nest *Xtruct2) (r *Xtruct2, err error) {
thing := nest.StructThing
fmt.Printf("testNest({%d, {\"%s\", %d, %d, %d}, %d})\n", nest.ByteThing, thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing, nest.I32Thing)
return nest, nil
@ -144,7 +145,7 @@ func (p *printingHandler) TestNest(nest *Xtruct2) (r *Xtruct2, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestMap(thing map[int32]int32) (r map[int32]int32, err error) {
func (p *printingHandler) TestMap(ctx context.Context, thing map[int32]int32) (r map[int32]int32, err error) {
fmt.Printf("testMap({")
first := true
for k, v := range thing {
@ -166,7 +167,7 @@ func (p *printingHandler) TestMap(thing map[int32]int32) (r map[int32]int32, err
//
// Parameters:
// - Thing
func (p *printingHandler) TestStringMap(thing map[string]string) (r map[string]string, err error) {
func (p *printingHandler) TestStringMap(ctx context.Context, thing map[string]string) (r map[string]string, err error) {
fmt.Printf("testStringMap({")
first := true
for k, v := range thing {
@ -188,7 +189,7 @@ func (p *printingHandler) TestStringMap(thing map[string]string) (r map[string]s
//
// Parameters:
// - Thing
func (p *printingHandler) TestSet(thing map[int32]struct{}) (r map[int32]struct{}, err error) {
func (p *printingHandler) TestSet(ctx context.Context, thing []int32) (r []int32, err error) {
fmt.Printf("testSet({")
first := true
for k, _ := range thing {
@ -210,7 +211,7 @@ func (p *printingHandler) TestSet(thing map[int32]struct{}) (r map[int32]struct{
//
// Parameters:
// - Thing
func (p *printingHandler) TestList(thing []int32) (r []int32, err error) {
func (p *printingHandler) TestList(ctx context.Context, thing []int32) (r []int32, err error) {
fmt.Printf("testList({")
for i, v := range thing {
if i != 0 {
@ -228,7 +229,7 @@ func (p *printingHandler) TestList(thing []int32) (r []int32, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestEnum(thing Numberz) (r Numberz, err error) {
func (p *printingHandler) TestEnum(ctx context.Context, thing Numberz) (r Numberz, err error) {
fmt.Printf("testEnum(%d)\n", thing)
return thing, nil
}
@ -239,7 +240,7 @@ func (p *printingHandler) TestEnum(thing Numberz) (r Numberz, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestTypedef(thing UserId) (r UserId, err error) {
func (p *printingHandler) TestTypedef(ctx context.Context, thing UserId) (r UserId, err error) {
fmt.Printf("testTypedef(%d)\n", thing)
return thing, nil
}
@ -251,7 +252,7 @@ func (p *printingHandler) TestTypedef(thing UserId) (r UserId, err error) {
//
// Parameters:
// - Hello
func (p *printingHandler) TestMapMap(hello int32) (r map[int32]map[int32]int32, err error) {
func (p *printingHandler) TestMapMap(ctx context.Context, hello int32) (r map[int32]map[int32]int32, err error) {
fmt.Printf("testMapMap(%d)\n", hello)
r = map[int32]map[int32]int32{
@ -273,14 +274,14 @@ func (p *printingHandler) TestMapMap(hello int32) (r map[int32]map[int32]int32,
//
// Parameters:
// - Argument
func (p *printingHandler) TestInsanity(argument *Insanity) (r map[UserId]map[Numberz]*Insanity, err error) {
func (p *printingHandler) TestInsanity(ctx context.Context, argument *Insanity) (r map[UserId]map[Numberz]*Insanity, err error) {
fmt.Printf("testInsanity()\n")
r = make(map[UserId]map[Numberz]*Insanity)
r[1] = map[Numberz]*Insanity {
r[1] = map[Numberz]*Insanity{
2: argument,
3: argument,
}
r[2] = map[Numberz]*Insanity {
r[2] = map[Numberz]*Insanity{
6: NewInsanity(),
}
return
@ -303,7 +304,7 @@ func (p *printingHandler) TestInsanity(argument *Insanity) (r map[UserId]map[Num
// - Arg3
// - Arg4
// - Arg5
func (p *printingHandler) TestMulti(arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 Numberz, arg5 UserId) (r *Xtruct, err error) {
func (p *printingHandler) TestMulti(ctx context.Context, arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 Numberz, arg5 UserId) (r *Xtruct, err error) {
fmt.Printf("testMulti()\n")
r = NewXtruct()
@ -322,7 +323,7 @@ func (p *printingHandler) TestMulti(arg0 int8, arg1 int32, arg2 int64, arg3 map[
//
// Parameters:
// - Arg
func (p *printingHandler) TestException(arg string) (err error) {
func (p *printingHandler) TestException(ctx context.Context, arg string) (err error) {
fmt.Printf("testException(%s)\n", arg)
switch arg {
case "Xception":
@ -346,7 +347,7 @@ func (p *printingHandler) TestException(arg string) (err error) {
// Parameters:
// - Arg0
// - Arg1
func (p *printingHandler) TestMultiException(arg0 string, arg1 string) (r *Xtruct, err error) {
func (p *printingHandler) TestMultiException(ctx context.Context, arg0 string, arg1 string) (r *Xtruct, err error) {
fmt.Printf("testMultiException(%s, %s)\n", arg0, arg1)
switch arg0 {
@ -375,7 +376,7 @@ func (p *printingHandler) TestMultiException(arg0 string, arg1 string) (r *Xtruc
//
// Parameters:
// - SecondsToSleep
func (p *printingHandler) TestOneway(secondsToSleep int32) (err error) {
func (p *printingHandler) TestOneway(ctx context.Context, secondsToSleep int32) (err error) {
fmt.Printf("testOneway(%d): Sleeping...\n", secondsToSleep)
time.Sleep(time.Second * time.Duration(secondsToSleep))
fmt.Printf("testOneway(%d): done sleeping!\n", secondsToSleep)

View file

@ -77,7 +77,7 @@ func (p *simpleHandler) TestStringMap(thing map[string]string) (r map[string]str
return thing, nil
}
func (p *simpleHandler) TestSet(thing map[int32]struct{}) (r map[int32]struct{}, err error) {
func (p *simpleHandler) TestSet(thing []int32) (r []int32, err error) {
return thing, nil
}

View file

@ -17,7 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
THRIFTCMD = $(THRIFT) --gen haxe -r
THRIFTTEST = $(top_srcdir)/test/ThriftTest.thrift
@ -88,16 +87,18 @@ check_php_web: $(BIN_PHP_WEB) $(BIN_CPP)
EXTRA_DIST = \
src \
cpp.hxml \
csharp.hxml \
flash.hxml \
java.hxml \
javascript.hxml \
neko.hxml \
php.hxml \
python.hxml \
project.hide \
TestClientServer.hxproj \
make_all.bat \
make_all.sh
src \
cpp.hxml \
csharp.hxml \
flash.hxml \
java.hxml \
javascript.hxml \
neko.hxml \
php.hxml \
python.hxml \
router.php \
project.hide \
php-web-server.hxml \
TestClientServer.hxproj \
make_all.bat \
make_all.sh

2
vendor/git.apache.org/thrift.git/test/haxe/make_all.sh generated vendored Normal file → Executable file
View file

@ -19,7 +19,7 @@
#
# invoke Thrift comnpiler
thrift -r -gen haxe ../ThriftTest.thrift
../../compiler/cpp/thrift -r -gen haxe ../ThriftTest.thrift
# output folder
if [ ! -d bin ]; then

View file

@ -444,6 +444,10 @@ class TestClient {
rslt.Expect( e.message == "Xception", 'testException("Xception") - e.message == "Xception"');
rslt.Expect( e.errorCode == 1001, 'testException("Xception") - e.errorCode == 1001');
}
catch (e : TException)
{
rslt.Expect( false, 'testException("Xception") - ${e} : ${e.errorMsg}');
}
catch (e : Dynamic)
{
rslt.Expect( false, 'testException("Xception") - $e');
@ -457,7 +461,7 @@ class TestClient {
}
catch (e : TException)
{
rslt.Expect( true, 'testException("TException") - $e');
rslt.Expect( true, 'testException("TException") - $e : ${e.errorMsg}');
}
catch (e : Dynamic)
{
@ -475,6 +479,10 @@ class TestClient {
client.testException("bla");
rslt.Expect( true, 'testException("bla") should not throw');
}
catch (e : TException)
{
rslt.Expect( false, 'testException("bla") - ${e} : ${e.errorMsg}');
}
catch (e : Dynamic)
{
rslt.Expect( false, 'testException("bla") - $e');
@ -846,6 +854,18 @@ class TestClient {
trace("}");
/**
* So you think you've got this all worked, out eh?
*
* Creates a the returned map with these values and prints it out:
* { 1 => { 2 => argument,
* 3 => argument,
* },
* 2 => { 6 => <empty Insanity struct>, },
* }
* @return map<UserId, map<Numberz,Insanity>> - a map with the above values
*/
var first_map = whoa.get(Int64.make(0,1));
var second_map = whoa.get(Int64.make(0,2));
rslt.Expect( (first_map != null) && (second_map != null), "(first_map != null) && (second_map != null)");
@ -857,42 +877,27 @@ class TestClient {
rslt.Expect( (crazy2 != null) && (crazy3 != null) && (looney != null),
"(crazy2 != null) && (crazy3 != null) && (looney != null)");
rslt.Expect( Int64.compare( crazy2.userMap.get(Numberz.EIGHT), Int64.make(0,8)) == 0,
"crazy2.UserMap.get(Numberz.EIGHT) == 8");
rslt.Expect( Int64.compare( crazy3.userMap.get(Numberz.EIGHT), Int64.make(0,8)) == 0,
"crazy3.UserMap.get(Numberz.EIGHT) == 8");
rslt.Expect( Int64.compare( crazy2.userMap.get(Numberz.FIVE), Int64.make(0,5)) == 0,
"crazy2.UserMap.get(Numberz.FIVE) == 5");
rslt.Expect( Int64.compare( crazy3.userMap.get(Numberz.FIVE), Int64.make(0,5)) == 0,
"crazy3.UserMap.get(Numberz.FIVE) == 5");
var crz2iter = crazy2.xtructs.iterator();
var crz3iter = crazy3.xtructs.iterator();
rslt.Expect( crz2iter.hasNext() && crz3iter.hasNext(), "crz2iter.hasNext() && crz3iter.hasNext()");
var goodbye2 = crz2iter.next();
var goodbye3 = crz3iter.next();
rslt.Expect( crz2iter.hasNext() && crz3iter.hasNext(), "crz2iter.hasNext() && crz3iter.hasNext()");
var hello2 = crz2iter.next();
var hello3 = crz3iter.next();
rslt.Expect( ! (crz2iter.hasNext() || crz3iter.hasNext()), "! (crz2iter.hasNext() || crz3iter.hasNext())");
rslt.Expect( hello2.string_thing == "Hello2", 'hello2.String_thing == "Hello2"');
rslt.Expect( hello2.byte_thing == 2, 'hello2.Byte_thing == 2');
rslt.Expect( hello2.i32_thing == 2, 'hello2.I32_thing == 2');
rslt.Expect( Int64.compare( hello2.i64_thing, Int64.make(0,2)) == 0, 'hello2.I64_thing == 2');
rslt.Expect( hello3.string_thing == "Hello2", 'hello3.String_thing == "Hello2"');
rslt.Expect( hello3.byte_thing == 2, 'hello3.Byte_thing == 2');
rslt.Expect( hello3.i32_thing == 2, 'hello3.I32_thing == 2');
rslt.Expect( Int64.compare( hello3.i64_thing, Int64.make(0,2)) == 0, 'hello3.I64_thing == 2');
rslt.Expect( Int64.compare( crazy2.userMap.get(Numberz.FIVE), insane.userMap.get(Numberz.FIVE)) == 0, "crazy2.userMap[5] == insane.userMap[5]");
rslt.Expect( truck.string_thing == goodbye2.string_thing, "truck.string_thing == goodbye2.string_thing");
rslt.Expect( truck.byte_thing == goodbye2.byte_thing, "truck.byte_thing == goodbye2.byte_thing");
rslt.Expect( truck.i32_thing == goodbye2.i32_thing, "truck.i32_thing == goodbye2.i32_thing");
rslt.Expect( Int64.compare( truck.i64_thing, goodbye2.i64_thing) == 0, "truck.i64_thing == goodbye2.i64_thing");
rslt.Expect( goodbye2.string_thing == "Goodbye4", 'goodbye2.String_thing == "Goodbye4"');
rslt.Expect( goodbye2.byte_thing == 4, 'goodbye2.Byte_thing == 4');
rslt.Expect( goodbye2.i32_thing == 4, 'goodbye2.I32_thing == 4');
rslt.Expect( Int64.compare( goodbye2.i64_thing, Int64.make(0,4)) == 0, 'goodbye2.I64_thing == 4');
rslt.Expect( goodbye3.string_thing == "Goodbye4", 'goodbye3.String_thing == "Goodbye4"');
rslt.Expect( goodbye3.byte_thing == 4, 'goodbye3.Byte_thing == 4');
rslt.Expect( goodbye3.i32_thing == 4, 'goodbye3.I32_thing == 4');
rslt.Expect( Int64.compare( goodbye3.i64_thing, Int64.make(0,4)) == 0, 'goodbye3.I64_thing == 4');
rslt.Expect( Int64.compare( crazy3.userMap.get(Numberz.FIVE), insane.userMap.get(Numberz.FIVE)) == 0, "crazy3.userMap[5] == insane.userMap[5]");
rslt.Expect( truck.string_thing == goodbye3.string_thing, "truck.string_thing == goodbye3.string_thing");
rslt.Expect( truck.byte_thing == goodbye3.byte_thing, "truck.byte_thing == goodbye3.byte_thing");
rslt.Expect( truck.i32_thing == goodbye3.i32_thing, "truck.i32_thing == goodbye3.i32_thing");
rslt.Expect( Int64.compare( truck.i64_thing, goodbye3.i64_thing) == 0, "truck.i64_thing == goodbye3.i64_thing");
rslt.Expect( ! looney.isSet(1), "! looney.isSet(1)");
rslt.Expect( ! looney.isSet(2), "! looney.isSet(2)");
}
var arg0 = 1;

View file

@ -352,33 +352,12 @@ class TestServerHandler implements ThriftTest {
{
trace("testInsanity()");
var hello = new Xtruct();
hello.string_thing = "Hello2";
hello.byte_thing = 2;
hello.i32_thing = 2;
hello.i64_thing = Int64.make(0, 2);
var goodbye = new Xtruct();
goodbye.string_thing = "Goodbye4";
goodbye.byte_thing = 4;
goodbye.i32_thing = 4;
goodbye.i64_thing = Int64.make(0, 4);
var crazy = new Insanity();
crazy.userMap = new IntMap< haxe.Int64>();
crazy.userMap.set(Numberz.EIGHT, Int64.make(0,8));
crazy.xtructs = new List<Xtruct>();
crazy.xtructs.add(goodbye);
var looney = new Insanity();
crazy.userMap.set(Numberz.FIVE, Int64.make(0,5));
crazy.xtructs.add(hello);
var first_map = new IntMap< Insanity>();
first_map.set(Numberz.TWO, crazy);
first_map.set(Numberz.THREE, crazy);
first_map.set(Numberz.TWO, argument);
first_map.set(Numberz.THREE, argument);
var second_map = new IntMap< Insanity>();
var looney = new Insanity();
second_map.set(Numberz.SIX, looney);
var insane = new Int64Map< IntMap< Insanity>>();

View file

@ -17,8 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
stubs: $(THRIFT) ../ConstantsDemo.thrift ../DebugProtoTest.thrift ../ThriftTest.thrift ../Include.thrift
$(THRIFT) --gen hs ../ConstantsDemo.thrift
$(THRIFT) --gen hs ../DebugProtoTest.thrift

View file

@ -46,6 +46,7 @@ import Thrift.Transport.HttpClient
import Thrift.Protocol
import Thrift.Protocol.Binary
import Thrift.Protocol.Compact
import Thrift.Protocol.Header
import Thrift.Protocol.JSON
data Options = Options
@ -85,12 +86,14 @@ getTransport t host port = do return (NoTransport $ "Unsupported transport: " ++
data ProtocolType = Binary
| Compact
| JSON
| Header
deriving (Show, Eq)
getProtocol :: String -> ProtocolType
getProtocol "binary" = Binary
getProtocol "compact" = Compact
getProtocol "json" = JSON
getProtocol "header" = Header
getProtocol p = error $ "Unsupported Protocol: " ++ p
defaultOptions :: Options
@ -104,7 +107,7 @@ defaultOptions = Options
, testLoops = 1
}
runClient :: (Protocol p, Transport t) => p t -> IO ()
runClient :: Protocol p => p -> IO ()
runClient p = do
let prot = (p,p)
putStrLn "Starting Tests"
@ -266,6 +269,7 @@ main = do
Binary -> runClient $ BinaryProtocol t
Compact -> runClient $ CompactProtocol t
JSON -> runClient $ JSONProtocol t
Header -> createHeaderProtocol t t >>= runClient
runTest loops p t = do
let client = makeClient p t
replicateM_ loops client

View file

@ -48,6 +48,7 @@ import Thrift.Transport.Framed
import Thrift.Transport.Handle
import Thrift.Protocol.Binary
import Thrift.Protocol.Compact
import Thrift.Protocol.Header
import Thrift.Protocol.JSON
data Options = Options
@ -90,11 +91,13 @@ getTransport t = NoTransport $ "Unsupported transport: " ++ t
data ProtocolType = Binary
| Compact
| JSON
| Header
getProtocol :: String -> ProtocolType
getProtocol "binary" = Binary
getProtocol "compact" = Compact
getProtocol "json" = JSON
getProtocol "header" = Header
getProtocol p = error $"Unsupported Protocol: " ++ p
defaultOptions :: Options
@ -261,13 +264,19 @@ main = do
t <- f socket
return (p t, p t)
headerAcceptor f socket = do
t <- f socket
p <- createHeaderProtocol1 t
return (p, p)
doRunServer p f = do
runThreadedServer (acceptor p f) TestHandler ThriftTest.process . PortNumber . fromIntegral
runServer p f port = case p of
Binary -> do doRunServer BinaryProtocol f port
Compact -> do doRunServer CompactProtocol f port
JSON -> do doRunServer JSONProtocol f port
Binary -> doRunServer BinaryProtocol f port
Compact -> doRunServer CompactProtocol f port
JSON -> doRunServer JSONProtocol f port
Header -> runThreadedServer (headerAcceptor f) TestHandler ThriftTest.process (PortNumber $ fromIntegral port)
parseFlags :: [String] -> Options -> Maybe Options
parseFlags (flag : flags) opts = do

View file

@ -1,88 +1,162 @@
[
"cpp-cpp_binary_buffered-ip-ssl",
"cpp-cpp_binary_framed-ip-ssl",
"cpp-cpp_binary_http-domain",
"cpp-cpp_binary_http-ip",
"cpp-cpp_binary_http-ip-ssl",
"cpp-cpp_compact_buffered-ip-ssl",
"cpp-cpp_compact_framed-ip-ssl",
"cpp-cpp_compact_http-domain",
"cpp-cpp_compact_http-ip",
"cpp-cpp_compact_http-ip-ssl",
"cpp-cpp_header_buffered-ip-ssl",
"cpp-cpp_header_framed-ip-ssl",
"cpp-cpp_header_http-ip-ssl",
"cpp-cpp_json_buffered-ip-ssl",
"cpp-cpp_json_framed-ip",
"cpp-cpp_json_framed-ip-ssl",
"cpp-cpp_json_http-domain",
"cpp-cpp_json_http-ip",
"cpp-cpp_json_http-ip-ssl",
"c_glib-rs_multi_buffered-ip",
"c_glib-rs_multi_framed-ip",
"c_glib-rs_multic_buffered-ip",
"c_glib-rs_multic_framed-ip",
"cl-c_glib_binary_buffered-ip",
"cl-c_glib_binary_framed-ip",
"cl-c_glib_multi-binary_buffered-ip",
"cl-c_glib_multi-binary_framed-ip",
"cl-c_glib_multi_buffered-ip",
"cl-c_glib_multi_framed-ip",
"cl-go_binary_buffered-ip",
"cl-go_binary_framed-ip",
"cl-rb_binary-accel_buffered-ip",
"cl-rb_binary-accel_framed-ip",
"cl-rb_binary_buffered-ip",
"cl-rb_binary_framed-ip",
"cl-rs_binary_buffered-ip",
"cl-rs_binary_framed-ip",
"cl-rs_multi-binary_buffered-ip",
"cl-rs_multi-binary_framed-ip",
"cl-rs_multi_buffered-ip",
"cl-rs_multi_framed-ip",
"cpp-dart_binary_http-ip",
"cpp-dart_compact_http-ip",
"cpp-dart_json_http-ip",
"cpp-dart_multi-binary_http-ip",
"cpp-dart_multic-compact_http-ip",
"cpp-dart_multij-json_http-ip",
"cpp-go_binary_http-ip",
"cpp-go_binary_http-ip-ssl",
"cpp-go_compact_http-ip",
"cpp-go_compact_http-ip-ssl",
"cpp-go_json_http-ip",
"cpp-go_json_http-ip-ssl",
"cpp-go_multi-binary_http-ip",
"cpp-go_multi-binary_http-ip-ssl",
"cpp-go_multic-compact_http-ip",
"cpp-go_multic-compact_http-ip-ssl",
"cpp-go_multij-json_http-ip",
"cpp-go_multij-json_http-ip-ssl",
"cpp-java_binary_http-ip",
"cpp-java_binary_http-ip-ssl",
"cpp-java_compact_http-ip",
"cpp-java_compact_http-ip-ssl",
"cpp-java_json_http-ip",
"cpp-java_json_http-ip-ssl",
"cpp-perl_binary_buffered-ip-ssl",
"cpp-perl_binary_framed-ip-ssl",
"cpp-py_binary-accel_framed-ip-ssl",
"csharp-cpp_binary_buffered-ip-ssl",
"csharp-cpp_binary_framed-ip-ssl",
"csharp-cpp_compact_buffered-ip-ssl",
"csharp-cpp_compact_framed-ip-ssl",
"csharp-cpp_json_buffered-ip-ssl",
"csharp-cpp_json_framed-ip-ssl",
"csharp-d_binary_buffered-ip-ssl",
"csharp-d_compact_buffered-ip-ssl",
"csharp-d_json_buffered-ip-ssl",
"csharp-erl_binary_buffered-ip-ssl",
"csharp-erl_binary_framed-ip-ssl",
"csharp-erl_compact_buffered-ip-ssl",
"csharp-erl_compact_framed-ip-ssl",
"csharp-go_binary_buffered-ip-ssl",
"csharp-go_binary_framed-ip-ssl",
"csharp-go_compact_buffered-ip-ssl",
"csharp-go_compact_framed-ip-ssl",
"csharp-go_json_buffered-ip-ssl",
"csharp-go_json_framed-ip-ssl",
"csharp-nodejs_binary_buffered-ip-ssl",
"csharp-nodejs_binary_framed-ip-ssl",
"csharp-nodejs_compact_buffered-ip-ssl",
"csharp-nodejs_compact_framed-ip-ssl",
"csharp-nodejs_json_buffered-ip-ssl",
"csharp-nodejs_json_framed-ip-ssl",
"csharp-perl_binary_buffered-ip-ssl",
"csharp-perl_binary_framed-ip-ssl",
"csharp-py3_binary-accel_buffered-ip-ssl",
"csharp-py3_binary-accel_framed-ip-ssl",
"csharp-py3_binary_buffered-ip-ssl",
"csharp-py3_binary_framed-ip-ssl",
"csharp-py3_compact-accelc_buffered-ip-ssl",
"csharp-py3_compact-accelc_framed-ip-ssl",
"csharp-py3_compact_buffered-ip-ssl",
"csharp-py3_compact_framed-ip-ssl",
"csharp-py3_json_buffered-ip-ssl",
"csharp-py3_json_framed-ip-ssl",
"csharp-py_binary-accel_buffered-ip-ssl",
"csharp-py_binary-accel_framed-ip-ssl",
"csharp-py_binary_buffered-ip-ssl",
"csharp-py_binary_framed-ip-ssl",
"csharp-py_compact-accelc_buffered-ip-ssl",
"csharp-py_compact-accelc_framed-ip-ssl",
"csharp-py_compact_buffered-ip-ssl",
"csharp-py_compact_framed-ip-ssl",
"csharp-py_json_buffered-ip-ssl",
"csharp-py_json_framed-ip-ssl",
"cpp-java_multi-binary_http-ip",
"cpp-java_multi-binary_http-ip-ssl",
"cpp-java_multi_http-ip",
"cpp-java_multi_http-ip-ssl",
"cpp-java_multic-compact_http-ip",
"cpp-java_multic-compact_http-ip-ssl",
"cpp-java_multic_http-ip",
"cpp-java_multic_http-ip-ssl",
"cpp-java_multij-json_http-ip",
"cpp-java_multij-json_http-ip-ssl",
"cpp-java_multij_http-ip",
"cpp-java_multij_http-ip-ssl",
"cpp-nodejs_binary_http-domain",
"cpp-nodejs_binary_http-ip",
"cpp-nodejs_binary_http-ip-ssl",
"cpp-nodejs_compact_http-domain",
"cpp-nodejs_compact_http-ip",
"cpp-nodejs_compact_http-ip-ssl",
"cpp-nodejs_json_http-domain",
"cpp-nodejs_json_http-ip",
"cpp-nodejs_json_http-ip-ssl",
"cpp-nodejs_multi-binary_http-domain",
"cpp-nodejs_multi-binary_http-ip",
"cpp-nodejs_multi-binary_http-ip-ssl",
"cpp-nodejs_multic-compact_http-domain",
"cpp-nodejs_multic-compact_http-ip",
"cpp-nodejs_multic-compact_http-ip-ssl",
"cpp-nodejs_multij-json_http-domain",
"cpp-nodejs_multij-json_http-ip",
"cpp-nodejs_multij-json_http-ip-ssl",
"cpp-py3_binary-accel_http-ip",
"cpp-py3_binary-accel_http-ip-ssl",
"cpp-py3_binary_http-ip",
"cpp-py3_binary_http-ip-ssl",
"cpp-py3_compact-accelc_http-ip",
"cpp-py3_compact-accelc_http-ip-ssl",
"cpp-py3_compact_http-ip",
"cpp-py3_compact_http-ip-ssl",
"cpp-py3_header_http-ip",
"cpp-py3_header_http-ip-ssl",
"cpp-py3_json_http-ip",
"cpp-py3_json_http-ip-ssl",
"cpp-py3_multi-accel_http-ip",
"cpp-py3_multi-accel_http-ip-ssl",
"cpp-py3_multi-binary_http-ip",
"cpp-py3_multi-binary_http-ip-ssl",
"cpp-py3_multi-multia_http-ip",
"cpp-py3_multi-multia_http-ip-ssl",
"cpp-py3_multi_http-ip",
"cpp-py3_multi_http-ip-ssl",
"cpp-py3_multic-accelc_http-ip",
"cpp-py3_multic-accelc_http-ip-ssl",
"cpp-py3_multic-compact_http-ip",
"cpp-py3_multic-compact_http-ip-ssl",
"cpp-py3_multic-multiac_http-ip",
"cpp-py3_multic-multiac_http-ip-ssl",
"cpp-py3_multic_http-ip",
"cpp-py3_multic_http-ip-ssl",
"cpp-py3_multih-header_http-ip",
"cpp-py3_multih-header_http-ip-ssl",
"cpp-py3_multij-json_http-ip",
"cpp-py3_multij-json_http-ip-ssl",
"cpp-py3_multij_http-ip",
"cpp-py3_multij_http-ip-ssl",
"cpp-py_binary-accel_http-ip",
"cpp-py_binary-accel_http-ip-ssl",
"cpp-py_binary_http-ip",
"cpp-py_binary_http-ip-ssl",
"cpp-py_compact-accelc_http-ip",
"cpp-py_compact-accelc_http-ip-ssl",
"cpp-py_compact_http-ip",
"cpp-py_compact_http-ip-ssl",
"cpp-py_header_http-ip",
"cpp-py_header_http-ip-ssl",
"cpp-py_json_http-ip",
"cpp-py_json_http-ip-ssl",
"cpp-py_multi-accel_http-ip",
"cpp-py_multi-accel_http-ip-ssl",
"cpp-py_multi-binary_http-ip",
"cpp-py_multi-binary_http-ip-ssl",
"cpp-py_multi-multia_http-ip",
"cpp-py_multi-multia_http-ip-ssl",
"cpp-py_multi_http-ip",
"cpp-py_multi_http-ip-ssl",
"cpp-py_multic-accelc_http-ip",
"cpp-py_multic-accelc_http-ip-ssl",
"cpp-py_multic-compact_http-ip",
"cpp-py_multic-compact_http-ip-ssl",
"cpp-py_multic-multiac_http-ip",
"cpp-py_multic-multiac_http-ip-ssl",
"cpp-py_multic_http-ip",
"cpp-py_multic_http-ip-ssl",
"cpp-py_multih-header_http-ip",
"cpp-py_multih-header_http-ip-ssl",
"cpp-py_multij-json_http-ip",
"cpp-py_multij-json_http-ip-ssl",
"cpp-py_multij_http-ip",
"cpp-py_multij_http-ip-ssl",
"cpp-rs_multi_buffered-ip",
"cpp-rs_multi_framed-ip",
"cpp-rs_multic_buffered-ip",
"cpp-rs_multic_framed-ip",
"csharp-rb_binary-accel_buffered-ip-ssl",
"csharp-rb_binary-accel_framed-ip-ssl",
"csharp-rb_binary_buffered-ip-ssl",
"csharp-rb_binary_framed-ip-ssl",
"csharp-rb_compact_buffered-ip-ssl",
"csharp-rb_compact_framed-ip-ssl",
"csharp-rb_json_buffered-ip-ssl",
"csharp-rb_json_framed-ip-ssl",
"d-cl_binary_buffered-ip",
"d-cl_binary_framed-ip",
"d-cpp_binary_buffered-ip",
"d-cpp_binary_buffered-ip-ssl",
"d-cpp_binary_framed-ip",
@ -101,11 +175,11 @@
"d-cpp_json_framed-ip-ssl",
"d-cpp_json_http-ip",
"d-cpp_json_http-ip-ssl",
"d-dart_binary_framed-ip",
"d-d_binary_http-ip",
"d-d_compact_http-ip",
"d-d_json_http-ip",
"d-dart_binary_http-ip",
"d-dart_compact_framed-ip",
"d-dart_compact_http-ip",
"d-dart_json_framed-ip",
"d-dart_json_http-ip",
"d-go_binary_http-ip",
"d-go_binary_http-ip-ssl",
@ -120,72 +194,102 @@
"d-java_json_http-ip",
"d-java_json_http-ip-ssl",
"d-js_json_http-ip",
"d-lua_json_buffered-ip",
"d-lua_json_framed-ip",
"d-nodejs_binary_buffered-ip",
"d-nodejs_binary_buffered-ip-ssl",
"d-nodejs_binary_framed-ip",
"d-nodejs_binary_framed-ip-ssl",
"d-nodejs_binary_http-ip",
"d-nodejs_binary_http-ip-ssl",
"d-nodejs_compact_buffered-ip",
"d-nodejs_compact_buffered-ip-ssl",
"d-nodejs_compact_framed-ip",
"d-nodejs_compact_framed-ip-ssl",
"d-nodejs_compact_http-ip",
"d-nodejs_compact_http-ip-ssl",
"d-nodejs_json_buffered-ip",
"d-nodejs_json_buffered-ip-ssl",
"d-nodejs_json_framed-ip",
"d-nodejs_json_framed-ip-ssl",
"d-perl_binary_buffered-ip-ssl",
"d-perl_binary_framed-ip-ssl",
"d-nodejs_json_http-ip",
"d-nodejs_json_http-ip-ssl",
"d-py3_binary-accel_buffered-ip",
"d-py3_binary-accel_buffered-ip-ssl",
"d-py3_binary-accel_framed-ip",
"d-py3_binary-accel_framed-ip-ssl",
"d-py3_binary-accel_http-ip",
"d-py3_binary-accel_http-ip-ssl",
"d-py3_binary_buffered-ip",
"d-py3_binary_buffered-ip-ssl",
"d-py3_binary_framed-ip",
"d-py3_binary_framed-ip-ssl",
"d-py3_binary_http-ip",
"d-py3_binary_http-ip-ssl",
"d-py3_compact-accelc_buffered-ip",
"d-py3_compact-accelc_buffered-ip-ssl",
"d-py3_compact-accelc_framed-ip",
"d-py3_compact-accelc_framed-ip-ssl",
"d-py3_compact-accelc_http-ip",
"d-py3_compact-accelc_http-ip-ssl",
"d-py3_compact_buffered-ip",
"d-py3_compact_buffered-ip-ssl",
"d-py3_compact_framed-ip",
"d-py3_compact_framed-ip-ssl",
"d-py3_compact_http-ip",
"d-py3_compact_http-ip-ssl",
"d-py3_json_buffered-ip",
"d-py3_json_buffered-ip-ssl",
"d-py3_json_framed-ip",
"d-py3_json_framed-ip-ssl",
"d-py3_json_http-ip",
"d-py3_json_http-ip-ssl",
"d-py_binary-accel_buffered-ip",
"d-py_binary-accel_buffered-ip-ssl",
"d-py_binary-accel_framed-ip",
"d-py_binary-accel_framed-ip-ssl",
"d-py_binary-accel_http-ip",
"d-py_binary-accel_http-ip-ssl",
"d-py_binary_buffered-ip",
"d-py_binary_buffered-ip-ssl",
"d-py_binary_framed-ip",
"d-py_binary_framed-ip-ssl",
"d-py_binary_http-ip",
"d-py_binary_http-ip-ssl",
"d-py_compact-accelc_buffered-ip",
"d-py_compact-accelc_buffered-ip-ssl",
"d-py_compact-accelc_framed-ip",
"d-py_compact-accelc_framed-ip-ssl",
"d-py_compact-accelc_http-ip",
"d-py_compact-accelc_http-ip-ssl",
"d-py_compact_buffered-ip",
"d-py_compact_buffered-ip-ssl",
"d-py_compact_framed-ip",
"d-py_compact_framed-ip-ssl",
"d-py_compact_http-ip",
"d-py_compact_http-ip-ssl",
"d-py_json_buffered-ip",
"d-py_json_buffered-ip-ssl",
"d-py_json_framed-ip",
"d-py_json_framed-ip-ssl",
"d-py_json_http-ip",
"d-py_json_http-ip-ssl",
"erl-cpp_binary_buffered-ip",
"erl-cpp_compact_buffered-ip",
"erl-csharp_binary_buffered-ip",
"erl-csharp_compact_buffered-ip",
"erl-nodejs_binary_buffered-ip",
"erl-nodejs_compact_buffered-ip",
"erl-perl_binary_buffered-ip-ssl",
"erl-perl_binary_framed-ip-ssl",
"erl-rb_binary-accel_buffered-ip",
"erl-rb_binary-accel_buffered-ip-ssl",
"erl-rb_binary-accel_framed-ip",
"erl-rb_binary-accel_framed-ip-ssl",
"erl-rb_binary_buffered-ip",
"erl-rb_binary_buffered-ip-ssl",
"erl-rb_binary_framed-ip",
"erl-rb_binary_framed-ip-ssl",
"erl-rb_compact_buffered-ip",
"erl-rb_compact_buffered-ip-ssl",
"erl-rb_compact_framed-ip",
"erl-rb_compact_framed-ip-ssl",
"go-cpp_binary_http-ip",
"go-cpp_binary_http-ip-ssl",
"go-cpp_compact_http-ip",
@ -198,10 +302,8 @@
"go-d_compact_http-ip-ssl",
"go-d_json_http-ip",
"go-d_json_http-ip-ssl",
"go-dart_binary_framed-ip",
"go-dart_binary_http-ip",
"go-dart_compact_http-ip",
"go-dart_json_framed-ip",
"go-dart_json_http-ip",
"go-java_binary_http-ip",
"go-java_binary_http-ip-ssl",
@ -209,37 +311,182 @@
"go-java_compact_http-ip-ssl",
"go-java_json_http-ip",
"go-java_json_http-ip-ssl",
"go-nodejs_json_framed-ip",
"go-perl_binary_buffered-ip-ssl",
"go-perl_binary_framed-ip-ssl",
"go-py3_binary-accel_zlib-ip-ssl",
"go-py3_compact-accelc_zlib-ip-ssl",
"go-py_binary-accel_zlib-ip-ssl",
"go-py_compact-accelc_zlib-ip-ssl",
"hs-csharp_binary_buffered-ip",
"hs-csharp_binary_framed-ip",
"hs-csharp_compact_buffered-ip",
"hs-csharp_compact_framed-ip",
"hs-csharp_json_framed-ip",
"hs-dart_binary_framed-ip",
"hs-dart_compact_framed-ip",
"hs-dart_json_framed-ip",
"hs-py3_json_buffered-ip",
"hs-py3_json_framed-ip",
"hs-py_json_buffered-ip",
"hs-py_json_framed-ip",
"java-d_compact_buffered-ip",
"java-d_compact_buffered-ip-ssl",
"java-d_compact_framed-ip",
"java-perl_binary_buffered-ip-ssl",
"java-perl_binary_fastframed-framed-ip-ssl",
"java-perl_binary_framed-ip-ssl",
"nodejs-perl_binary_buffered-ip-ssl",
"nodejs-perl_binary_framed-ip-ssl",
"perl-perl_binary_buffered-ip-ssl",
"perl-perl_binary_framed-ip-ssl",
"perl-php_binary_framed-ip",
"py-cpp_compact_buffered-ip",
"py-perl_accel-binary_buffered-ip-ssl",
"py-perl_accel-binary_framed-ip-ssl",
"py-perl_binary_buffered-ip-ssl",
"py-perl_binary_framed-ip-ssl",
"py3-perl_accel-binary_buffered-ip-ssl",
"py3-perl_accel-binary_framed-ip-ssl",
"py3-perl_binary_buffered-ip-ssl",
"py3-perl_binary_framed-ip-ssl"
]
"nodejs-cpp_binary_http-domain",
"nodejs-cpp_binary_http-ip",
"nodejs-cpp_binary_http-ip-ssl",
"nodejs-cpp_compact_http-domain",
"nodejs-cpp_compact_http-ip",
"nodejs-cpp_compact_http-ip-ssl",
"nodejs-cpp_json_buffered-ip-ssl",
"nodejs-cpp_json_http-domain",
"nodejs-cpp_json_http-ip",
"nodejs-cpp_json_http-ip-ssl",
"nodejs-d_binary_http-ip",
"nodejs-d_binary_http-ip-ssl",
"nodejs-d_compact_http-ip",
"nodejs-d_compact_http-ip-ssl",
"nodejs-d_json_http-ip",
"nodejs-d_json_http-ip-ssl",
"nodejs-dart_binary_http-ip",
"nodejs-dart_compact_http-ip",
"nodejs-dart_json_http-ip",
"nodejs-go_binary_http-ip",
"nodejs-go_binary_http-ip-ssl",
"nodejs-go_compact_http-ip",
"nodejs-go_compact_http-ip-ssl",
"nodejs-go_json_http-ip",
"nodejs-go_json_http-ip-ssl",
"nodejs-hs_binary_http-ip",
"nodejs-hs_compact_http-ip",
"nodejs-hs_json_http-ip",
"nodejs-java_binary_http-ip",
"nodejs-java_binary_http-ip-ssl",
"nodejs-java_compact_http-ip",
"nodejs-java_compact_http-ip-ssl",
"nodejs-java_json_http-ip",
"nodejs-java_json_http-ip-ssl",
"nodejs-js_json_http-ip",
"nodejs-lua_binary_http-ip",
"nodejs-lua_compact_http-ip",
"nodejs-lua_json_http-ip",
"nodejs-py3_binary-accel_http-ip",
"nodejs-py3_binary-accel_http-ip-ssl",
"nodejs-py3_binary_http-ip",
"nodejs-py3_binary_http-ip-ssl",
"nodejs-py3_compact-accelc_http-ip",
"nodejs-py3_compact-accelc_http-ip-ssl",
"nodejs-py3_compact_http-ip",
"nodejs-py3_compact_http-ip-ssl",
"nodejs-py3_json_http-ip",
"nodejs-py3_json_http-ip-ssl",
"nodejs-py_binary-accel_http-ip",
"nodejs-py_binary-accel_http-ip-ssl",
"nodejs-py_binary_http-ip",
"nodejs-py_binary_http-ip-ssl",
"nodejs-py_compact-accelc_http-ip",
"nodejs-py_compact-accelc_http-ip-ssl",
"nodejs-py_compact_http-ip",
"nodejs-py_compact_http-ip-ssl",
"nodejs-py_json_http-ip",
"nodejs-py_json_http-ip-ssl",
"perl-rs_multi_buffered-ip",
"perl-rs_multi_framed-ip",
"py-cpp_accel-binary_http-ip",
"py-cpp_accel-binary_http-ip-ssl",
"py-cpp_accel-binary_zlib-ip",
"py-cpp_accel-binary_zlib-ip-ssl",
"py-cpp_accelc-compact_http-ip",
"py-cpp_accelc-compact_http-ip-ssl",
"py-cpp_accelc-compact_zlib-ip",
"py-cpp_accelc-compact_zlib-ip-ssl",
"py-cpp_binary_http-ip",
"py-cpp_binary_http-ip-ssl",
"py-cpp_compact_http-ip",
"py-cpp_compact_http-ip-ssl",
"py-cpp_header_http-ip",
"py-cpp_header_http-ip-ssl",
"py-cpp_json_http-ip",
"py-cpp_json_http-ip-ssl",
"py-d_accel-binary_http-ip",
"py-d_accel-binary_http-ip-ssl",
"py-d_accelc-compact_http-ip",
"py-d_accelc-compact_http-ip-ssl",
"py-d_binary_http-ip",
"py-d_binary_http-ip-ssl",
"py-d_compact_http-ip",
"py-d_compact_http-ip-ssl",
"py-d_json_http-ip",
"py-d_json_http-ip-ssl",
"py-dart_accel-binary_http-ip",
"py-dart_accelc-compact_http-ip",
"py-dart_binary_http-ip",
"py-dart_compact_http-ip",
"py-dart_json_http-ip",
"py-hs_accel-binary_http-ip",
"py-hs_accelc-compact_http-ip",
"py-hs_binary_http-ip",
"py-hs_compact_http-ip",
"py-hs_header_http-ip",
"py-hs_json_http-ip",
"py-java_accel-binary_http-ip",
"py-java_accel-binary_http-ip-ssl",
"py-java_accelc-compact_http-ip",
"py-java_accelc-compact_http-ip-ssl",
"py-java_binary_http-ip",
"py-java_binary_http-ip-ssl",
"py-java_compact_http-ip",
"py-java_compact_http-ip-ssl",
"py-java_json_http-ip",
"py-java_json_http-ip-ssl",
"py-lua_accel-binary_http-ip",
"py-lua_accelc-compact_http-ip",
"py-lua_binary_http-ip",
"py-lua_compact_http-ip",
"py-lua_json_http-ip",
"py3-cpp_accel-binary_http-ip",
"py3-cpp_accel-binary_http-ip-ssl",
"py3-cpp_accel-binary_zlib-ip",
"py3-cpp_accel-binary_zlib-ip-ssl",
"py3-cpp_accelc-compact_http-ip",
"py3-cpp_accelc-compact_http-ip-ssl",
"py3-cpp_accelc-compact_zlib-ip",
"py3-cpp_accelc-compact_zlib-ip-ssl",
"py3-cpp_binary_http-ip",
"py3-cpp_binary_http-ip-ssl",
"py3-cpp_compact_http-ip",
"py3-cpp_compact_http-ip-ssl",
"py3-cpp_header_http-ip",
"py3-cpp_header_http-ip-ssl",
"py3-cpp_json_http-ip",
"py3-cpp_json_http-ip-ssl",
"py3-d_accel-binary_http-ip",
"py3-d_accel-binary_http-ip-ssl",
"py3-d_accelc-compact_http-ip",
"py3-d_accelc-compact_http-ip-ssl",
"py3-d_binary_http-ip",
"py3-d_binary_http-ip-ssl",
"py3-d_compact_http-ip",
"py3-d_compact_http-ip-ssl",
"py3-d_json_http-ip",
"py3-d_json_http-ip-ssl",
"py3-dart_accel-binary_http-ip",
"py3-dart_accelc-compact_http-ip",
"py3-dart_binary_http-ip",
"py3-dart_compact_http-ip",
"py3-dart_json_http-ip",
"py3-hs_accel-binary_http-ip",
"py3-hs_accelc-compact_http-ip",
"py3-hs_binary_http-ip",
"py3-hs_compact_http-ip",
"py3-hs_header_http-ip",
"py3-hs_json_http-ip",
"py3-java_accel-binary_http-ip",
"py3-java_accel-binary_http-ip-ssl",
"py3-java_accelc-compact_http-ip",
"py3-java_accelc-compact_http-ip-ssl",
"py3-java_binary_http-ip",
"py3-java_binary_http-ip-ssl",
"py3-java_compact_http-ip",
"py3-java_compact_http-ip-ssl",
"py3-java_json_http-ip",
"py3-java_json_http-ip-ssl",
"py3-lua_accel-binary_http-ip",
"py3-lua_accelc-compact_http-ip",
"py3-lua_binary_http-ip",
"py3-lua_compact_http-ip",
"py3-lua_json_http-ip",
"rb-cpp_json_buffered-domain",
"rb-cpp_json_buffered-ip",
"rb-cpp_json_buffered-ip-ssl",
"rb-cpp_json_framed-domain",
"rb-cpp_json_framed-ip",
"rb-cpp_json_framed-ip-ssl"
]

View file

@ -0,0 +1,2 @@
# ignore for autogenerated files
/ThriftTest

View file

@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<AssemblyName>Client</AssemblyName>
<PackageId>Client</PackageId>
<OutputType>Exe</OutputType>
<GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
<GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Net.Http.WinHttpHandler" Version="[4.4,)" />
<PackageReference Include="System.Runtime.Serialization.Primitives" Version="[4.3,)" />
<PackageReference Include="System.ServiceModel.Primitives" Version="[4.4,)" />
<PackageReference Include="System.Threading" Version="[4.3,)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\lib\netcore\Thrift\Thrift.csproj" />
</ItemGroup>
<Target Name="PreBuild" BeforeTargets="_GenerateRestoreProjectSpec;Restore;Compile">
<Exec Condition="'$(OS)' == 'Windows_NT'" Command="where thrift" ConsoleToMSBuild="true">
<Output TaskParameter="ConsoleOutput" PropertyName="PathToThrift" />
</Exec>
<Exec Condition="Exists('$(PathToThrift)')" Command="&quot;$(PathToThrift)&quot; -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
<Exec Condition="Exists('thrift')" Command="thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
<Exec Condition="Exists('$(ProjectDir)/../../../compiler/cpp/thrift')" Command="$(ProjectDir)/../../../compiler/cpp/thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
</Target>
</Project>

View file

@ -0,0 +1,72 @@
// 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.
using System;
using System.Collections.Generic;
using ThriftTest;
namespace Client
{
public class Program
{
public static int Main(string[] args)
{
try
{
Console.SetBufferSize(Console.BufferWidth, 4096);
}
catch (Exception)
{
Console.WriteLine("Failed to grow scroll-back buffer");
}
// split mode and options
var subArgs = new List<string>(args);
var firstArg = string.Empty;
if (subArgs.Count > 0)
{
firstArg = subArgs[0];
subArgs.RemoveAt(0);
}
// run whatever mode is choosen
switch(firstArg)
{
case "client":
return TestClient.Execute(subArgs);
case "--help":
PrintHelp();
return 0;
default:
PrintHelp();
return -1;
}
}
private static void PrintHelp()
{
Console.WriteLine("Usage:");
Console.WriteLine(" Client client [options]'");
Console.WriteLine(" Client --help");
Console.WriteLine("");
TestClient.PrintOptionsHelp();
}
}
}

View file

@ -0,0 +1,43 @@
// 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.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Apache Software Foundation")]
[assembly: AssemblyProduct("Thrift")]
[assembly: AssemblyCopyright("The Apache Software Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("B0C13DA0-3117-4844-8AE8-B1775E46223D")]

View file

@ -0,0 +1,943 @@
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Collections;
using Thrift.Protocols;
using Thrift.Transports;
using Thrift.Transports.Client;
namespace ThriftTest
{
public class TestClient
{
private class TestParams
{
public int numIterations = 1;
public IPAddress host = IPAddress.Any;
public int port = 9090;
public int numThreads = 1;
public string url;
public string pipe;
public bool buffered;
public bool framed;
public string protocol;
public bool encrypted = false;
internal void Parse( List<string> args)
{
for (var i = 0; i < args.Count; ++i)
{
if (args[i] == "-u")
{
url = args[++i];
}
else if (args[i] == "-n")
{
numIterations = Convert.ToInt32(args[++i]);
}
else if (args[i].StartsWith("--pipe="))
{
pipe = args[i].Substring(args[i].IndexOf("=") + 1);
Console.WriteLine("Using named pipes transport");
}
else if (args[i].StartsWith("--host="))
{
// check there for ipaddress
host = new IPAddress(Encoding.Unicode.GetBytes(args[i].Substring(args[i].IndexOf("=") + 1)));
}
else if (args[i].StartsWith("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
buffered = true;
Console.WriteLine("Using buffered sockets");
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
framed = true;
Console.WriteLine("Using framed transport");
}
else if (args[i] == "-t")
{
numThreads = Convert.ToInt32(args[++i]);
}
else if (args[i] == "--binary" || args[i] == "--protocol=binary")
{
protocol = "binary";
Console.WriteLine("Using binary protocol");
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
protocol = "compact";
Console.WriteLine("Using compact protocol");
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
protocol = "json";
Console.WriteLine("Using JSON protocol");
}
else if (args[i] == "--ssl")
{
encrypted = true;
Console.WriteLine("Using encrypted transport");
}
else
{
//throw new ArgumentException(args[i]);
}
}
}
private static X509Certificate2 GetClientCert()
{
var clientCertName = "client.p12";
var possiblePaths = new List<string>
{
"../../../keys/",
"../../keys/",
"../keys/",
"keys/",
};
string existingPath = null;
foreach (var possiblePath in possiblePaths)
{
var path = Path.GetFullPath(possiblePath + clientCertName);
if (File.Exists(path))
{
existingPath = path;
break;
}
}
if (string.IsNullOrEmpty(existingPath))
{
throw new FileNotFoundException($"Cannot find file: {clientCertName}");
}
var cert = new X509Certificate2(existingPath, "thrift");
return cert;
}
public TClientTransport CreateTransport()
{
if (url == null)
{
// endpoint transport
TClientTransport trans = null;
if (pipe != null)
{
trans = new TNamedPipeClientTransport(pipe);
}
else
{
if (encrypted)
{
var cert = GetClientCert();
if (cert == null || !cert.HasPrivateKey)
{
throw new InvalidOperationException("Certificate doesn't contain private key");
}
trans = new TTlsSocketClientTransport(host, port, 0, cert,
(sender, certificate, chain, errors) => true,
null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
}
else
{
trans = new TSocketClientTransport(host, port);
}
}
// layered transport
if (buffered)
{
trans = new TBufferedClientTransport(trans);
}
if (framed)
{
trans = new TFramedClientTransport(trans);
}
return trans;
}
return new THttpClientTransport(new Uri(url), null);
}
public TProtocol CreateProtocol(TClientTransport transport)
{
if (protocol == "compact")
{
return new TCompactProtocol(transport);
}
if (protocol == "json")
{
return new TJsonProtocol(transport);
}
return new TBinaryProtocol(transport);
}
}
private const int ErrorBaseTypes = 1;
private const int ErrorStructs = 2;
private const int ErrorContainers = 4;
private const int ErrorExceptions = 8;
private const int ErrorUnknown = 64;
private class ClientTest
{
private readonly TClientTransport transport;
private readonly ThriftTest.Client client;
private readonly int numIterations;
private bool done;
public int ReturnCode { get; set; }
public ClientTest(TestParams param)
{
transport = param.CreateTransport();
client = new ThriftTest.Client(param.CreateProtocol(transport));
numIterations = param.numIterations;
}
public void Execute()
{
var token = CancellationToken.None;
if (done)
{
Console.WriteLine("Execute called more than once");
throw new InvalidOperationException();
}
for (var i = 0; i < numIterations; i++)
{
try
{
if (!transport.IsOpen)
{
transport.OpenAsync(token).GetAwaiter().GetResult();
}
}
catch (TTransportException ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Connect failed: " + ex.Message);
ReturnCode |= ErrorUnknown;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
continue;
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Connect failed: " + ex.Message);
ReturnCode |= ErrorUnknown;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
continue;
}
try
{
ReturnCode |= ExecuteClientTestAsync(client).GetAwaiter().GetResult(); ;
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
ReturnCode |= ErrorUnknown;
}
}
try
{
transport.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error while closing transport");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
done = true;
}
}
internal static void PrintOptionsHelp()
{
Console.WriteLine("Client options:");
Console.WriteLine(" -u <URL>");
Console.WriteLine(" -t <# of threads to run> default = 1");
Console.WriteLine(" -n <# of iterations> per thread");
Console.WriteLine(" --pipe=<pipe name>");
Console.WriteLine(" --host=<IP address>");
Console.WriteLine(" --port=<port number>");
Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)");
Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)");
Console.WriteLine(" --ssl");
Console.WriteLine();
}
public static int Execute(List<string> args)
{
try
{
var param = new TestParams();
try
{
param.Parse(args);
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Error while parsing arguments");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
return ErrorUnknown;
}
var tests = Enumerable.Range(0, param.numThreads).Select(_ => new ClientTest(param)).ToArray();
//issue tests on separate threads simultaneously
var threads = tests.Select(test => new Task(test.Execute)).ToArray();
var start = DateTime.Now;
foreach (var t in threads)
{
t.Start();
}
Task.WaitAll(threads);
Console.WriteLine("Total time: " + (DateTime.Now - start));
Console.WriteLine();
return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2);
}
catch (Exception outerEx)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Unexpected error");
Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
return ErrorUnknown;
}
}
public static string BytesToHex(byte[] data)
{
return BitConverter.ToString(data).Replace("-", string.Empty);
}
public static byte[] PrepareTestData(bool randomDist)
{
var retval = new byte[0x100];
var initLen = Math.Min(0x100, retval.Length);
// linear distribution, unless random is requested
if (!randomDist)
{
for (var i = 0; i < initLen; ++i)
{
retval[i] = (byte)i;
}
return retval;
}
// random distribution
for (var i = 0; i < initLen; ++i)
{
retval[i] = (byte)0;
}
var rnd = new Random();
for (var i = 1; i < initLen; ++i)
{
while (true)
{
var nextPos = rnd.Next() % initLen;
if (retval[nextPos] == 0)
{
retval[nextPos] = (byte)i;
break;
}
}
}
return retval;
}
public static async Task<int> ExecuteClientTestAsync(ThriftTest.Client client)
{
var token = CancellationToken.None;
var returnCode = 0;
Console.Write("testVoid()");
await client.testVoidAsync(token);
Console.WriteLine(" = void");
Console.Write("testString(\"Test\")");
var s = await client.testStringAsync("Test", token);
Console.WriteLine(" = \"" + s + "\"");
if ("Test" != s)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testBool(true)");
var t = await client.testBoolAsync((bool)true, token);
Console.WriteLine(" = " + t);
if (!t)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testBool(false)");
var f = await client.testBoolAsync((bool)false, token);
Console.WriteLine(" = " + f);
if (f)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testByte(1)");
var i8 = await client.testByteAsync((sbyte)1, token);
Console.WriteLine(" = " + i8);
if (1 != i8)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testI32(-1)");
var i32 = await client.testI32Async(-1, token);
Console.WriteLine(" = " + i32);
if (-1 != i32)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testI64(-34359738368)");
var i64 = await client.testI64Async(-34359738368, token);
Console.WriteLine(" = " + i64);
if (-34359738368 != i64)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
// TODO: Validate received message
Console.Write("testDouble(5.325098235)");
var dub = await client.testDoubleAsync(5.325098235, token);
Console.WriteLine(" = " + dub);
if (5.325098235 != dub)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testDouble(-0.000341012439638598279)");
dub = await client.testDoubleAsync(-0.000341012439638598279, token);
Console.WriteLine(" = " + dub);
if (-0.000341012439638598279 != dub)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
var binOut = PrepareTestData(true);
Console.Write("testBinary(" + BytesToHex(binOut) + ")");
try
{
var binIn = await client.testBinaryAsync(binOut, token);
Console.WriteLine(" = " + BytesToHex(binIn));
if (binIn.Length != binOut.Length)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
for (var ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs)
if (binIn[ofs] != binOut[ofs])
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
}
catch (Thrift.TApplicationException ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
// binary equals? only with hashcode option enabled ...
Console.WriteLine("Test CrazyNesting");
var one = new CrazyNesting();
var two = new CrazyNesting();
one.String_field = "crazy";
two.String_field = "crazy";
one.Binary_field = new byte[] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
if (typeof(CrazyNesting).GetMethod("Equals")?.DeclaringType == typeof(CrazyNesting))
{
if (!one.Equals(two))
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorContainers;
throw new Exception("CrazyNesting.Equals failed");
}
}
// TODO: Validate received message
Console.Write("testStruct({\"Zero\", 1, -3, -5})");
var o = new Xtruct();
o.String_thing = "Zero";
o.Byte_thing = (sbyte)1;
o.I32_thing = -3;
o.I64_thing = -5;
var i = await client.testStructAsync(o, token);
Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}");
// TODO: Validate received message
Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})");
var o2 = new Xtruct2();
o2.Byte_thing = (sbyte)1;
o2.Struct_thing = o;
o2.I32_thing = 5;
var i2 = await client.testNestAsync(o2, token);
i = i2.Struct_thing;
Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}");
var mapout = new Dictionary<int, int>();
for (var j = 0; j < 5; j++)
{
mapout[j] = j - 10;
}
Console.Write("testMap({");
var first = true;
foreach (var key in mapout.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapout[key]);
}
Console.Write("})");
var mapin = await client.testMapAsync(mapout, token);
Console.Write(" = {");
first = true;
foreach (var key in mapin.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapin[key]);
}
Console.WriteLine("}");
// TODO: Validate received message
var listout = new List<int>();
for (var j = -2; j < 3; j++)
{
listout.Add(j);
}
Console.Write("testList({");
first = true;
foreach (var j in listout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
var listin = await client.testListAsync(listout, token);
Console.Write(" = {");
first = true;
foreach (var j in listin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
//set
// TODO: Validate received message
var setout = new THashSet<int>();
for (var j = -2; j < 3; j++)
{
setout.Add(j);
}
Console.Write("testSet({");
first = true;
foreach (int j in setout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
var setin = await client.testSetAsync(setout, token);
Console.Write(" = {");
first = true;
foreach (int j in setin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
Console.Write("testEnum(ONE)");
var ret = await client.testEnumAsync(Numberz.ONE, token);
Console.WriteLine(" = " + ret);
if (Numberz.ONE != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(TWO)");
ret = await client.testEnumAsync(Numberz.TWO, token);
Console.WriteLine(" = " + ret);
if (Numberz.TWO != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(THREE)");
ret = await client.testEnumAsync(Numberz.THREE, token);
Console.WriteLine(" = " + ret);
if (Numberz.THREE != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(FIVE)");
ret = await client.testEnumAsync(Numberz.FIVE, token);
Console.WriteLine(" = " + ret);
if (Numberz.FIVE != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(EIGHT)");
ret = await client.testEnumAsync(Numberz.EIGHT, token);
Console.WriteLine(" = " + ret);
if (Numberz.EIGHT != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testTypedef(309858235082523)");
var uid = await client.testTypedefAsync(309858235082523L, token);
Console.WriteLine(" = " + uid);
if (309858235082523L != uid)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
// TODO: Validate received message
Console.Write("testMapMap(1)");
var mm = await client.testMapMapAsync(1, token);
Console.Write(" = {");
foreach (var key in mm.Keys)
{
Console.Write(key + " => {");
var m2 = mm[key];
foreach (var k2 in m2.Keys)
{
Console.Write(k2 + " => " + m2[k2] + ", ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
// TODO: Validate received message
var insane = new Insanity();
insane.UserMap = new Dictionary<Numberz, long>();
insane.UserMap[Numberz.FIVE] = 5000L;
var truck = new Xtruct();
truck.String_thing = "Truck";
truck.Byte_thing = (sbyte)8;
truck.I32_thing = 8;
truck.I64_thing = 8;
insane.Xtructs = new List<Xtruct>();
insane.Xtructs.Add(truck);
Console.Write("testInsanity()");
var whoa = await client.testInsanityAsync(insane, token);
Console.Write(" = {");
foreach (var key in whoa.Keys)
{
var val = whoa[key];
Console.Write(key + " => {");
foreach (var k2 in val.Keys)
{
var v2 = val[k2];
Console.Write(k2 + " => {");
var userMap = v2.UserMap;
Console.Write("{");
if (userMap != null)
{
foreach (var k3 in userMap.Keys)
{
Console.Write(k3 + " => " + userMap[k3] + ", ");
}
}
else
{
Console.Write("null");
}
Console.Write("}, ");
var xtructs = v2.Xtructs;
Console.Write("{");
if (xtructs != null)
{
foreach (var x in xtructs)
{
Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, ");
}
}
else
{
Console.Write("null");
}
Console.Write("}");
Console.Write("}, ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
sbyte arg0 = 1;
var arg1 = 2;
var arg2 = long.MaxValue;
var multiDict = new Dictionary<short, string>();
multiDict[1] = "one";
var tmpMultiDict = new List<string>();
foreach (var pair in multiDict)
tmpMultiDict.Add(pair.Key +" => "+ pair.Value);
var arg4 = Numberz.FIVE;
long arg5 = 5000000;
Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + ",{" + string.Join(",", tmpMultiDict) + "}," + arg4 + "," + arg5 + ")");
var multiResponse = await client.testMultiAsync(arg0, arg1, arg2, multiDict, arg4, arg5, token);
Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing
+ ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n");
try
{
Console.WriteLine("testException(\"Xception\")");
await client.testExceptionAsync("Xception", token);
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Xception ex)
{
if (ex.ErrorCode != 1001 || ex.Message != "Xception")
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testException(\"TException\")");
await client.testExceptionAsync("TException", token);
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Thrift.TException)
{
// OK
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testException(\"ok\")");
await client.testExceptionAsync("ok", token);
// OK
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testMultiException(\"Xception\", ...)");
await client.testMultiExceptionAsync("Xception", "ignore", token);
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Xception ex)
{
if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception")
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testMultiException(\"Xception2\", ...)");
await client.testMultiExceptionAsync("Xception2", "ignore", token);
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Xception2 ex)
{
if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2")
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testMultiException(\"success\", \"OK\")");
if ("OK" != (await client.testMultiExceptionAsync("success", "OK", token)).String_thing)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
var sw = new Stopwatch();
sw.Start();
Console.WriteLine("Test Oneway(1)");
await client.testOnewayAsync(1, token);
sw.Stop();
if (sw.ElapsedMilliseconds > 1000)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("Test Calltime()");
var times = 50;
sw.Reset();
sw.Start();
for (var k = 0; k < times; ++k)
await client.testVoidAsync(token);
sw.Stop();
Console.WriteLine(" = {0} ms a testVoid() call", sw.ElapsedMilliseconds / times);
return returnCode;
}
}
}

View file

@ -0,0 +1,41 @@
#
# 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.
#
SUBDIRS = .
all-local:
$(DOTNETCORE) build
precross:
$(DOTNETCORE) build
clean-local:
$(RM) -r Client/bin
$(RM) -r Server/bin
$(RM) -r Client/obj
$(RM) -r Server/obj
$(RM) -r ThriftTest/ThriftTest
EXTRA_DIST = \
Client \
README.md \
Server \
ThriftTest.sln \
build.cmd \
build.sh

View file

@ -0,0 +1,20 @@
# Apache Thrift net-core-lib tests
Tests for Thrift client library ported to Microsoft .Net Core
# Content
- ThriftTest - tests for Thrift library
# Reused components
- NET Core Standard 1.6 (SDK 2.0.0)
# How to build on Windows
- Get Thrift IDL compiler executable, add to some folder and add path to this folder into PATH variable
- Open ThriftTest.sln in Visual Studio and build
or
- Build with scripts
# How to build on Unix
- Ensure you have .NET Core 2.0.0 SDK installed or use the Ubuntu Xenial docker image
- Follow common build practice for Thrift: bootstrap, configure, and make precross

View file

@ -0,0 +1,2 @@
# ignore for autogenerated files
/ThriftTest

View file

@ -0,0 +1,72 @@
// 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.
using System;
using System.Collections.Generic;
using ThriftTest;
namespace Server
{
public class Program
{
public static int Main(string[] args)
{
try
{
Console.SetBufferSize(Console.BufferWidth, 4096);
}
catch (Exception)
{
Console.WriteLine("Failed to grow scroll-back buffer");
}
// split mode and options
var subArgs = new List<string>(args);
var firstArg = string.Empty;
if (subArgs.Count > 0)
{
firstArg = subArgs[0];
subArgs.RemoveAt(0);
}
// run whatever mode is choosen
switch(firstArg)
{
case "server":
return TestServer.Execute(subArgs);
case "--help":
PrintHelp();
return 0;
default:
PrintHelp();
return -1;
}
}
private static void PrintHelp()
{
Console.WriteLine("Usage:");
Console.WriteLine(" Server server [options]'");
Console.WriteLine(" Server --help");
Console.WriteLine("");
TestServer.PrintOptionsHelp();
}
}
}

View file

@ -0,0 +1,43 @@
// 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.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Apache Software Foundation")]
[assembly: AssemblyProduct("Thrift")]
[assembly: AssemblyCopyright("The Apache Software Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("B0C13DA0-3117-4844-8AE8-B1775E46223D")]

View file

@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<AssemblyName>Server</AssemblyName>
<PackageId>Server</PackageId>
<OutputType>Exe</OutputType>
<GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
<GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Net.Http.WinHttpHandler" Version="[4.4,)" />
<PackageReference Include="System.Runtime.Serialization.Primitives" Version="[4.3,)" />
<PackageReference Include="System.ServiceModel.Primitives" Version="[4.4,)" />
<PackageReference Include="System.Threading" Version="[4.3,)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\lib\netcore\Thrift\Thrift.csproj" />
</ItemGroup>
<Target Name="PreBuild" BeforeTargets="_GenerateRestoreProjectSpec;Restore;Compile">
<Exec Condition="'$(OS)' == 'Windows_NT'" Command="where thrift" ConsoleToMSBuild="true">
<Output TaskParameter="ConsoleOutput" PropertyName="PathToThrift" />
</Exec>
<Exec Condition="Exists('$(PathToThrift)')" Command="&quot;$(PathToThrift)&quot; -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
<Exec Condition="Exists('thrift')" Command="thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
<Exec Condition="Exists('$(ProjectDir)/../../../compiler/cpp/thrift')" Command="$(ProjectDir)/../../../compiler/cpp/thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
</Target>
</Project>

View file

@ -0,0 +1,594 @@
// 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.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Collections;
using Thrift.Protocols;
using Thrift.Server;
using Thrift.Transports;
using Thrift.Transports.Server;
namespace ThriftTest
{
internal class ServerParam
{
internal bool useBufferedSockets = false;
internal bool useFramed = false;
internal bool useEncryption = false;
internal bool compact = false;
internal bool json = false;
internal int port = 9090;
internal string pipe = null;
internal void Parse(List<string> args)
{
for (var i = 0; i < args.Count; i++)
{
if (args[i].StartsWith("--pipe="))
{
pipe = args[i].Substring(args[i].IndexOf("=") + 1);
}
else if (args[i].StartsWith("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
useBufferedSockets = true;
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
useFramed = true;
}
else if (args[i] == "--binary" || args[i] == "--protocol=binary")
{
// nothing needed
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
compact = true;
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
json = true;
}
else if (args[i] == "--threaded" || args[i] == "--server-type=threaded")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--prototype" || args[i] == "--processor=prototype")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--ssl")
{
useEncryption = true;
}
else
{
//throw new ArgumentException(args[i]);
}
}
}
}
public class TestServer
{
public static int _clientID = -1;
public delegate void TestLogDelegate(string msg, params object[] values);
public class MyServerEventHandler : TServerEventHandler
{
public int callCount = 0;
public Task PreServeAsync(CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
public Task<object> CreateContextAsync(TProtocol input, TProtocol output, CancellationToken cancellationToken)
{
callCount++;
return Task.FromResult<object>(null);
}
public Task DeleteContextAsync(object serverContext, TProtocol input, TProtocol output, CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
public Task ProcessContextAsync(object serverContext, TClientTransport transport, CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
}
public class TestHandlerAsync : ThriftTest.IAsync
{
public TBaseServer server { get; set; }
private int handlerID;
private StringBuilder sb = new StringBuilder();
private TestLogDelegate logger;
public TestHandlerAsync()
{
handlerID = Interlocked.Increment(ref _clientID);
logger += testConsoleLogger;
logger.Invoke("New TestHandler instance created");
}
public void testConsoleLogger(string msg, params object[] values)
{
sb.Clear();
sb.AppendFormat("handler{0:D3}:", handlerID);
sb.AppendFormat(msg, values);
sb.AppendLine();
Console.Write(sb.ToString());
}
public Task testVoidAsync(CancellationToken cancellationToken)
{
logger.Invoke("testVoid()");
return Task.CompletedTask;
}
public Task<string> testStringAsync(string thing, CancellationToken cancellationToken)
{
logger.Invoke("testString({0})", thing);
return Task.FromResult(thing);
}
public Task<bool> testBoolAsync(bool thing, CancellationToken cancellationToken)
{
logger.Invoke("testBool({0})", thing);
return Task.FromResult(thing);
}
public Task<sbyte> testByteAsync(sbyte thing, CancellationToken cancellationToken)
{
logger.Invoke("testByte({0})", thing);
return Task.FromResult(thing);
}
public Task<int> testI32Async(int thing, CancellationToken cancellationToken)
{
logger.Invoke("testI32({0})", thing);
return Task.FromResult(thing);
}
public Task<long> testI64Async(long thing, CancellationToken cancellationToken)
{
logger.Invoke("testI64({0})", thing);
return Task.FromResult(thing);
}
public Task<double> testDoubleAsync(double thing, CancellationToken cancellationToken)
{
logger.Invoke("testDouble({0})", thing);
return Task.FromResult(thing);
}
public Task<byte[]> testBinaryAsync(byte[] thing, CancellationToken cancellationToken)
{
var hex = BitConverter.ToString(thing).Replace("-", string.Empty);
logger.Invoke("testBinary({0:X})", hex);
return Task.FromResult(thing);
}
public Task<Xtruct> testStructAsync(Xtruct thing, CancellationToken cancellationToken)
{
logger.Invoke("testStruct({{\"{0}\", {1}, {2}, {3}}})", thing.String_thing, thing.Byte_thing, thing.I32_thing, thing.I64_thing);
return Task.FromResult(thing);
}
public Task<Xtruct2> testNestAsync(Xtruct2 nest, CancellationToken cancellationToken)
{
var thing = nest.Struct_thing;
logger.Invoke("testNest({{{0}, {{\"{1}\", {2}, {3}, {4}, {5}}}}})",
nest.Byte_thing,
thing.String_thing,
thing.Byte_thing,
thing.I32_thing,
thing.I64_thing,
nest.I32_thing);
return Task.FromResult(nest);
}
public Task<Dictionary<int, int>> testMapAsync(Dictionary<int, int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testMap({{");
var first = true;
foreach (var key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0} => {1}", key, thing[key]);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<Dictionary<string, string>> testStringMapAsync(Dictionary<string, string> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testStringMap({{");
var first = true;
foreach (var key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0} => {1}", key, thing[key]);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<THashSet<int>> testSetAsync(THashSet<int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testSet({{");
var first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0}", elem);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<List<int>> testListAsync(List<int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testList({{");
var first = true;
foreach (var elem in thing)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0}", elem);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<Numberz> testEnumAsync(Numberz thing, CancellationToken cancellationToken)
{
logger.Invoke("testEnum({0})", thing);
return Task.FromResult(thing);
}
public Task<long> testTypedefAsync(long thing, CancellationToken cancellationToken)
{
logger.Invoke("testTypedef({0})", thing);
return Task.FromResult(thing);
}
public Task<Dictionary<int, Dictionary<int, int>>> testMapMapAsync(int hello, CancellationToken cancellationToken)
{
logger.Invoke("testMapMap({0})", hello);
var mapmap = new Dictionary<int, Dictionary<int, int>>();
var pos = new Dictionary<int, int>();
var neg = new Dictionary<int, int>();
for (var i = 1; i < 5; i++)
{
pos[i] = i;
neg[-i] = -i;
}
mapmap[4] = pos;
mapmap[-4] = neg;
return Task.FromResult(mapmap);
}
public Task<Dictionary<long, Dictionary<Numberz, Insanity>>> testInsanityAsync(Insanity argument, CancellationToken cancellationToken)
{
logger.Invoke("testInsanity()");
/** from ThriftTest.thrift:
* So you think you've got this all worked, out eh?
*
* Creates a the returned map with these values and prints it out:
* { 1 => { 2 => argument,
* 3 => argument,
* },
* 2 => { 6 => <empty Insanity struct>, },
* }
* @return map<UserId, map<Numberz,Insanity>> - a map with the above values
*/
var first_map = new Dictionary<Numberz, Insanity>();
var second_map = new Dictionary<Numberz, Insanity>(); ;
first_map[Numberz.TWO] = argument;
first_map[Numberz.THREE] = argument;
second_map[Numberz.SIX] = new Insanity();
var insane = new Dictionary<long, Dictionary<Numberz, Insanity>>
{
[1] = first_map,
[2] = second_map
};
return Task.FromResult(insane);
}
public Task<Xtruct> testMultiAsync(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5,
CancellationToken cancellationToken)
{
logger.Invoke("testMulti()");
var hello = new Xtruct(); ;
hello.String_thing = "Hello2";
hello.Byte_thing = arg0;
hello.I32_thing = arg1;
hello.I64_thing = arg2;
return Task.FromResult(hello);
}
public Task testExceptionAsync(string arg, CancellationToken cancellationToken)
{
logger.Invoke("testException({0})", arg);
if (arg == "Xception")
{
var x = new Xception
{
ErrorCode = 1001,
Message = arg
};
throw x;
}
if (arg == "TException")
{
throw new TException();
}
return Task.CompletedTask;
}
public Task<Xtruct> testMultiExceptionAsync(string arg0, string arg1, CancellationToken cancellationToken)
{
logger.Invoke("testMultiException({0}, {1})", arg0, arg1);
if (arg0 == "Xception")
{
var x = new Xception
{
ErrorCode = 1001,
Message = "This is an Xception"
};
throw x;
}
if (arg0 == "Xception2")
{
var x = new Xception2
{
ErrorCode = 2002,
Struct_thing = new Xtruct { String_thing = "This is an Xception2" }
};
throw x;
}
var result = new Xtruct { String_thing = arg1 };
return Task.FromResult(result);
}
public Task testOnewayAsync(int secondsToSleep, CancellationToken cancellationToken)
{
logger.Invoke("testOneway({0}), sleeping...", secondsToSleep);
Task.Delay(secondsToSleep * 1000, cancellationToken).GetAwaiter().GetResult();
logger.Invoke("testOneway finished");
return Task.CompletedTask;
}
}
internal static void PrintOptionsHelp()
{
Console.WriteLine("Server options:");
Console.WriteLine(" --pipe=<pipe name>");
Console.WriteLine(" --port=<port number>");
Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)");
Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)");
Console.WriteLine(" --server-type=<type> one of threaded,threadpool (defaults to simple)");
Console.WriteLine(" --processor=<prototype>");
Console.WriteLine(" --ssl");
Console.WriteLine();
}
private static X509Certificate2 GetServerCert()
{
var serverCertName = "server.p12";
var possiblePaths = new List<string>
{
"../../../keys/",
"../../keys/",
"../keys/",
"keys/",
};
string existingPath = null;
foreach (var possiblePath in possiblePaths)
{
var path = Path.GetFullPath(possiblePath + serverCertName);
if (File.Exists(path))
{
existingPath = path;
break;
}
}
if (string.IsNullOrEmpty(existingPath))
{
throw new FileNotFoundException($"Cannot find file: {serverCertName}");
}
var cert = new X509Certificate2(existingPath, "thrift");
return cert;
}
public static int Execute(List<string> args)
{
var loggerFactory = new LoggerFactory();//.AddConsole().AddDebug();
var logger = new LoggerFactory().CreateLogger("Test");
try
{
var param = new ServerParam();
try
{
param.Parse(args);
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Error while parsing arguments");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
return 1;
}
// Transport
TServerTransport trans;
if (param.pipe != null)
{
trans = new TNamedPipeServerTransport(param.pipe);
}
// else if (param.useFramed)
// {
// trans = new TServerFramedTransport(param.port);
// }
else
{
if (param.useEncryption)
{
var cert = GetServerCert();
if (cert == null || !cert.HasPrivateKey)
{
throw new InvalidOperationException("Certificate doesn't contain private key");
}
trans = new TTlsServerSocketTransport(param.port, param.useBufferedSockets, param.useFramed, cert,
(sender, certificate, chain, errors) => true,
null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
}
else
{
trans = new TServerSocketTransport(param.port, 0, param.useBufferedSockets, param.useFramed);
}
}
ITProtocolFactory proto;
if (param.compact)
proto = new TCompactProtocol.Factory();
else if (param.json)
proto = new TJsonProtocol.Factory();
else
proto = new TBinaryProtocol.Factory();
ITProcessorFactory processorFactory;
// Processor
var testHandler = new TestHandlerAsync();
var testProcessor = new ThriftTest.AsyncProcessor(testHandler);
processorFactory = new SingletonTProcessorFactory(testProcessor);
TTransportFactory transFactory = new TTransportFactory();
TBaseServer serverEngine = new AsyncBaseServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger);
//Server event handler
var serverEvents = new MyServerEventHandler();
serverEngine.SetEventHandler(serverEvents);
// Run it
var where = (! string.IsNullOrEmpty(param.pipe)) ? "on pipe " + param.pipe : "on port " + param.port;
Console.WriteLine("Starting the AsyncBaseServer " + where +
" with processor TPrototypeProcessorFactory prototype factory " +
(param.useBufferedSockets ? " with buffered socket" : "") +
(param.useFramed ? " with framed transport" : "") +
(param.useEncryption ? " with encryption" : "") +
(param.compact ? " with compact protocol" : "") +
(param.json ? " with json protocol" : "") +
"...");
serverEngine.ServeAsync(CancellationToken.None).GetAwaiter().GetResult();
Console.ReadLine();
}
catch (Exception x)
{
Console.Error.Write(x);
return 1;
}
Console.WriteLine("done.");
return 0;
}
}
}

View file

@ -0,0 +1,64 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift", "..\..\lib\netcore\Thrift\Thrift.csproj", "{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client", "Client\Client.csproj", "{21039F25-6ED7-4E80-A545-EBC93472EBD1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "Server\Server.csproj", "{0C6E8685-F191-4479-9842-882A38961127}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.ActiveCfg = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.Build.0 = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x86.ActiveCfg = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x86.Build.0 = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|Any CPU.Build.0 = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.ActiveCfg = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.Build.0 = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.ActiveCfg = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.Build.0 = Release|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x64.ActiveCfg = Debug|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x64.Build.0 = Debug|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x86.ActiveCfg = Debug|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x86.Build.0 = Debug|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|Any CPU.Build.0 = Release|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x64.ActiveCfg = Release|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x64.Build.0 = Release|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x86.ActiveCfg = Release|Any CPU
{21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x86.Build.0 = Release|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Debug|x64.ActiveCfg = Debug|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Debug|x64.Build.0 = Debug|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Debug|x86.ActiveCfg = Debug|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Debug|x86.Build.0 = Debug|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Release|Any CPU.Build.0 = Release|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Release|x64.ActiveCfg = Release|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Release|x64.Build.0 = Release|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Release|x86.ActiveCfg = Release|Any CPU
{0C6E8685-F191-4479-9842-882A38961127}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {52CE9A12-F6CB-4F0C-BB42-0105612F5FF4}
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,25 @@
@echo off
rem /*
rem * Licensed to the Apache Software Foundation (ASF) under one
rem * or more contributor license agreements. See the NOTICE file
rem * distributed with this work for additional information
rem * regarding copyright ownership. The ASF licenses this file
rem * to you under the Apache License, Version 2.0 (the
rem * "License"); you may not use this file except in compliance
rem * with the License. You may obtain a copy of the License at
rem *
rem * http://www.apache.org/licenses/LICENSE-2.0
rem *
rem * Unless required by applicable law or agreed to in writing,
rem * software distributed under the License is distributed on an
rem * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
rem * KIND, either express or implied. See the License for the
rem * specific language governing permissions and limitations
rem * under the License.
rem */
setlocal
dotnet --info
dotnet build
:eof

26
vendor/git.apache.org/thrift.git/test/netcore/build.sh generated vendored Executable file
View file

@ -0,0 +1,26 @@
#!/usr/bin/env bash
#
# 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.
#
#exit if any command fails
set -e
dotnet --info
dotnet build

View file

@ -17,8 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
stubs: ../ThriftTest.thrift
$(THRIFT) --gen perl ../ThriftTest.thrift

View file

@ -19,7 +19,7 @@
# under the License.
#
require 5.6.0;
use 5.10.0;
use strict;
use warnings;
use Data::Dumper;
@ -33,10 +33,12 @@ use Thrift;
use Thrift::BinaryProtocol;
use Thrift::BufferedTransport;
use Thrift::FramedTransport;
use Thrift::MultiplexedProtocol;
use Thrift::SSLSocket;
use Thrift::Socket;
use Thrift::UnixSocket;
use ThriftTest::SecondService;
use ThriftTest::ThriftTest;
use ThriftTest::Types;
@ -47,15 +49,19 @@ sub usage {
Usage: $0 [OPTIONS]
Options: (default)
--ca CA to validate server with.
--cert Certificate to use.
Required if using --ssl.
--ciphers Acceptable cipher list.
--domain-socket <file> Use a unix domain socket.
--help Show usage.
--key Certificate key.
Required if using --ssl.
--port <portnum> 9090 Port to use.
--protocol {binary} binary Protocol to use.
--ssl If present, use SSL.
--transport {buffered|framed} buffered Transport to use.
EOF
}
@ -66,7 +72,10 @@ my %opts = (
);
GetOptions(\%opts, qw (
ca=s
cert=s
ciphers=s
key=s
domain-socket=s
help
host=s
@ -81,18 +90,13 @@ if ($opts{help}) {
exit 0;
}
if ($opts{ssl} and not defined $opts{cert}) {
usage();
exit 1;
}
my $socket = undef;
if ($opts{"domain-socket"}) {
$socket = new Thrift::UnixSocket($opts{"domain-socket"});
} elsif ($opts{ssl}) {
$socket = new Thrift::SSLSocket($opts{host}, $opts{port});
$socket = new Thrift::SSLSocket(\%opts);
} else {
$socket = new Thrift::Socket($opts{host}, $opts{port});
$socket = new Thrift::Socket($opts{host}, $opts{port});
}
my $transport;
@ -106,21 +110,37 @@ if ($opts{transport} eq 'buffered') {
}
my $protocol;
if ($opts{protocol} eq 'binary') {
my $protocol2;
if ($opts{protocol} eq 'binary' || $opts{protocol} eq 'multi') {
$protocol = new Thrift::BinaryProtocol($transport);
} else {
usage();
exit 1;
}
my $secondService = undef;
if (index($opts{protocol}, 'multi') == 0) {
$protocol2 = new Thrift::MultiplexedProtocol($protocol, "SecondService");
$protocol = new Thrift::MultiplexedProtocol($protocol, "ThriftTest");
$secondService = new ThriftTest::SecondServiceClient($protocol2);
}
my $testClient = new ThriftTest::ThriftTestClient($protocol);
eval {
$transport->open();
};
};
if($@){
die(Dumper($@));
}
use constant ERR_BASETYPES => 1;
use constant ERR_STRUCTS => 2;
use constant ERR_CONTAINERS => 4;
use constant ERR_EXCEPTIONS => 8;
use constant ERR_PROTOCOL => 16;
use constant ERR_UNKNOWN => 64;
my $start = gettimeofday();
#
@ -136,6 +156,17 @@ print(" = void\n");
print("testString(\"Test\")");
my $s = $testClient->testString("Test");
print(" = \"$s\"\n");
exit(ERR_BASETYPES) if ($s ne 'Test');
#
# MULTIPLEXED TEST
#
if (index($opts{protocol}, 'multi') == 0) {
print("secondtestString(\"Test2\")");
$s = $secondService->secondtestString("Test2");
print(" = \"$s\"\n");
exit(ERR_PROTOCOL) if ($s ne 'testString("Test2")');
}
#
# BOOL TEST
@ -143,9 +174,11 @@ print(" = \"$s\"\n");
print("testBool(1)");
my $t = $testClient->testBool(1);
print(" = $t\n");
exit(ERR_BASETYPES) if ($t ne 1);
print("testBool(0)");
my $f = $testClient->testBool(0);
print(" = $f\n");
exit(ERR_BASETYPES) if ($f ne "");
#
@ -161,13 +194,15 @@ print(" = $u8\n");
print("testI32(-1)");
my $i32 = $testClient->testI32(-1);
print(" = $i32\n");
exit(ERR_BASETYPES) if ($i32 ne -1);
#
#I64 TEST
# I64 TEST
#
print("testI64(-34359738368)");
my $i64 = $testClient->testI64(-34359738368);
print(" = $i64\n");
exit(ERR_BASETYPES) if ($i64 ne -34359738368);
#
# DOUBLE TEST
@ -175,6 +210,7 @@ print(" = $i64\n");
print("testDouble(-852.234234234)");
my $dub = $testClient->testDouble(-852.234234234);
print(" = $dub\n");
exit(ERR_BASETYPES) if ($dub ne -852.234234234);
#
# BINARY TEST --- TODO

View file

@ -19,13 +19,15 @@
# under the License.
#
require 5.6.0;
use 5.10.0;
use strict;
use warnings;
use Data::Dumper;
use Getopt::Long qw(GetOptions);
use Time::HiRes qw(gettimeofday);
$SIG{INT} = \&sigint_handler;
use lib '../../lib/perl/lib';
use lib 'gen-perl';
@ -33,11 +35,13 @@ use Thrift;
use Thrift::BinaryProtocol;
use Thrift::BufferedTransport;
use Thrift::FramedTransport;
use Thrift::MultiplexedProcessor;
use Thrift::SSLServerSocket;
use Thrift::ServerSocket;
use Thrift::Server;
use Thrift::UnixServerSocket;
use ThriftTest::SecondService;
use ThriftTest::ThriftTest;
use ThriftTest::Types;
@ -50,7 +54,8 @@ Usage: $0 [OPTIONS]
Options: (default)
--ca Certificate authority file (optional).
--cert Certificate file.
Required if using --ssl.
Required if using --ssl.
--ciphers Acceptable cipher list.
--domain-socket <file> Use a unix domain socket.
--help Show usage.
--key Private key file for certificate.
@ -60,7 +65,7 @@ Options: (default)
--protocol {binary} binary Protocol to use.
--ssl If present, use SSL/TLS.
--transport {buffered|framed} buffered Transport to use.
EOF
}
@ -73,6 +78,7 @@ my %opts = (
GetOptions(\%opts, qw (
ca=s
cert=s
ciphers=s
domain-socket=s
help
host=s
@ -94,7 +100,9 @@ if ($opts{ssl} and not defined $opts{cert}) {
}
my $handler = new ThriftTestHandler();
my $handler2 = new SecondServiceHandler();
my $processor = new ThriftTest::ThriftTestProcessor($handler);
my $processor2 = new ThriftTest::SecondServiceProcessor($handler2);
my $serversocket;
if ($opts{"domain-socket"}) {
unlink($opts{"domain-socket"});
@ -114,13 +122,21 @@ if ($opts{transport} eq 'buffered') {
exit 1;
}
my $protocol;
if ($opts{protocol} eq 'binary') {
if ($opts{protocol} eq 'binary' || $opts{protocol} eq 'multi') {
$protocol = new Thrift::BinaryProtocolFactory();
} else {
usage();
exit 1;
}
if (index($opts{protocol}, 'multi') == 0) {
my $newProcessor = new Thrift::MultiplexedProcessor($protocol);
$newProcessor->defaultProcessor($processor);
$newProcessor->registerProcessor("ThriftTest", $processor);
$newProcessor->registerProcessor("SecondService", $processor2);
$processor = $newProcessor;
}
my $ssltag = '';
if ($opts{ssl}) {
$ssltag = "(SSL)";
@ -132,8 +148,14 @@ if ($opts{"domain-socket"}) {
my $server = new Thrift::SimpleServer($processor, $serversocket, $transport, $protocol);
print "Starting \"simple\" server ($opts{transport}/$opts{protocol}) listen on: $listening_on\n";
$server->serve();
print "done.\n";
###
sub sigint_handler {
print "received SIGINT, stopping...\n";
$server->stop();
}
###
### Test server implementation
###
@ -148,7 +170,7 @@ sub new {
}
sub testVoid() {
print("testVoid()\n");
print("testVoid()\n");
}
sub testString() {
@ -280,7 +302,7 @@ sub testSet() {
print(", ");
}
print("$key");
push($result, $key);
push(@arr, $key);
}
print("})\n");
return $result;
@ -320,7 +342,7 @@ sub testTypedef() {
sub testMapMap() {
my $self = shift;
my $hello = shift;
printf("testMapMap(%d)\n", $hello);
my $result = { 4 => { 1 => 1, 2 => 2, 3 => 3, 4 => 4 }, -4 => { -1 => -1, -2 => -2, -3 => -3, -4 => -4 } };
return $result;
@ -352,7 +374,7 @@ sub testMulti() {
my $arg3 = shift;
my $arg4 = shift;
my $arg5 = shift;
print("testMulti()\n");
return new ThriftTest::Xtruct({string_thing => "Hello2", byte_thing => $arg0, i32_thing => $arg1, i64_thing => $arg2});
}
@ -388,11 +410,29 @@ sub testMultiException() {
sub testOneway() {
my $self = shift;
my $sleepFor = shift;
print("testOneway($sleepFor): Sleeping...\n");
sleep $sleepFor;
print("testOneway($sleepFor): done sleeping!\n");
my $num = shift;
print("testOneway($num): received\n");
}
###
### Test server implementation
###
package SecondServiceHandler;
use base qw( ThriftTest::SecondServiceIf );
sub new {
my $classname = shift;
my $self = {};
return bless($self, $classname);
}
sub secondtestString() {
my $self = shift;
my $thing = shift;
print("testString($thing)\n");
return "testString(\"" . $thing . "\")";
}
1;

View file

@ -17,20 +17,23 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
stubs: ../ThriftTest.thrift
$(THRIFT) --gen php ../ThriftTest.thrift
$(THRIFT) --gen php:inlined ../ThriftTest.thrift
$(MKDIR_P) gen-php-psr4
$(THRIFT) -out gen-php-psr4 --gen php:psr4 ../ThriftTest.thrift
$(MKDIR_P) gen-php-classmap
$(THRIFT) -out gen-php-classmap --gen php ../ThriftTest.thrift
precross: stubs
php_ext_dir:
mkdir -p php_ext_dir
ln -s ../../../lib/php/src/ext/thrift_protocol/modules/thrift_protocol.so php_ext_dir/
ln -s "$$(php-config --extension-dir)/sockets.so" php_ext_dir/
check: stubs
precross: stubs php_ext_dir
check: stubs php_ext_dir
clean-local:
$(RM) -r gen-php gen-phpi gen-php-psr4
$(RM) -r gen-php gen-phpi gen-php-classmap php_ext_dir
client: stubs
client: stubs php_ext_dir
php TestClient.php

View file

@ -18,6 +18,6 @@
*/
<?php
$GEN_DIR = 'gen-php-psr4';
$GEN_DIR = 'gen-php-classmap';
include_once('TestClient.php');
?>

View file

@ -2,7 +2,8 @@
namespace test\php;
require_once __DIR__.'/../../lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php';
/** @var \Composer\Autoload\ClassLoader $loader */
$loader = require __DIR__ . '/../../vendor/autoload.php';
use Thrift\ClassLoader\ThriftClassLoader;
@ -13,14 +14,14 @@ if (!isset($MODE)) {
$MODE = 'normal';
}
$loader = new ThriftClassLoader();
$loader->registerNamespace('Thrift', __DIR__ . '/../../lib/php/lib');
if ($GEN_DIR === 'gen-php-psr4') {
$loader->registerNamespace('ThriftTest', $GEN_DIR);
if ($GEN_DIR == 'gen-php') {
$loader->addPsr4('', $GEN_DIR);
} else {
$loader = new ThriftClassLoader();
$loader->registerDefinition('ThriftTest', $GEN_DIR);
$loader->register();
}
$loader->register();
/*
* Licensed to the Apache Software Foundation (ASF) under one
@ -94,7 +95,7 @@ foreach ($argv as $arg) {
$MODE = substr($arg, 12);
} else if (substr($arg, 0, 11) == '--protocol=') {
$PROTO = substr($arg, 11);
}
}
}
$hosts = array('localhost');
@ -266,6 +267,39 @@ if ($mapin != $mapout) {
$exitcode |= ERR_CONTAINERS;
}
$mapout = array();
for ($i = 0; $i < 10; $i++) {
$mapout["key$i"] = "val$i";
}
print_r('testStringMap({');
$first = true;
foreach ($mapout as $key => $val) {
if ($first) {
$first = false;
} else {
print_r(", ");
}
print_r("\"$key\" => \"$val\"");
}
print_r("})");
$mapin = $testClient->testStringMap($mapout);
print_r(" = {");
$first = true;
foreach ($mapin as $key => $val) {
if ($first) {
$first = false;
} else {
print_r(", ");
}
print_r("\"$key\" => \"$val\"");
}
print_r("}\n");
ksort($mapin);
if ($mapin != $mapout) {
echo "**FAILED**\n";
$exitcode |= ERR_CONTAINERS;
}
/**
* SET TEST
*/
@ -459,6 +493,24 @@ try {
print_r(' caught xception '.$x->errorCode.': '.$x->message."\n");
}
// Regression test for THRIFT-4263
print_r("testBinarySerializer_Deserialize('foo')");
try {
\Thrift\Serializer\TBinarySerializer::deserialize(base64_decode('foo'), \ThriftTest\Xtruct2::class);
echo "**FAILED**\n";
$exitcode |= ERR_STRUCTS;
} catch (\Thrift\Exception\TTransportException $happy_exception) {
// We expected this due to binary data of base64_decode('foo') is less then 4
// bytes and it tries to find thrift version number in the transport by
// reading i32() at the beginning. Casting to string validates that
// exception is still accessible in memory and not corrupted. Without patch,
// PHP will error log that the exception doesn't have any tostring method,
// which is a lie due to corrupted memory.
for($i=99; $i > 0; $i--) {
(string)$happy_exception;
}
print_r(" SUCCESS\n");
}
/**
* Normal tests done.
@ -472,6 +524,19 @@ print_r("Total time: $elp ms\n");
* Extraneous "I don't trust PHP to pack/unpack integer" tests
*/
if ($protocol instanceof TBinaryProtocolAccelerated) {
// Regression check: check that method name is not double-freed
// Method name should not be an interned string.
$method_name = "Void";
$method_name = "test$method_name";
$seqid = 0;
$args = new \ThriftTest\ThriftTest_testVoid_args();
thrift_protocol_write_binary($protocol, $method_name, \Thrift\Type\TMessageType::CALL, $args, $seqid, $protocol->isStrictWrite());
$testClient->recv_testVoid();
}
// Max I32
$num = pow(2, 30) + (pow(2, 30) - 1);
roundtrip($testClient, 'testI32', $num);

View file

@ -0,0 +1,2 @@
extension=thrift_protocol.so
extension=sockets.so

View file

@ -21,8 +21,8 @@
import datetime
import glob
import sys
import os
import sys
import time
import unittest
@ -40,8 +40,8 @@ from tornado import gen
from tornado.testing import AsyncTestCase, get_unused_port, gen_test
from thrift import TTornado
from thrift.Thrift import TApplicationException
from thrift.protocol import TBinaryProtocol
from thrift.transport.TTransport import TTransportException
from ThriftTest import ThriftTest
from ThriftTest.ttypes import Xception, Xtruct
@ -55,6 +55,8 @@ class TestHandler(object):
pass
def testString(self, s):
if s == 'unexpected_error':
raise Exception(s)
return s
def testByte(self, b):
@ -85,7 +87,7 @@ class TestHandler(object):
x.message = s
raise x
elif s == 'throw_undeclared':
raise ValueError("foo")
raise ValueError('testing undeclared exception')
def testOneway(self, seconds):
start = time.time()
@ -97,6 +99,7 @@ class TestHandler(object):
self.test_instance.io_loop.add_timeout(
datetime.timedelta(seconds=seconds),
fire_oneway)
raise Exception('testing exception in oneway method')
def testNest(self, thing):
return thing
@ -187,10 +190,11 @@ class ThriftTestCase(AsyncTestCase):
self.assertEqual(y.i32_thing, -3)
self.assertEqual(y.i64_thing, -5)
@gen_test
def test_oneway(self):
self.client.testOneway(0)
start, end, seconds = self.wait(timeout=1)
self.assertAlmostEqual(seconds, (end - start), places=3)
self.client.testOneway(1)
v = yield self.client.testI32(-1)
self.assertEqual(v, -1)
@gen_test
def test_map(self):
@ -203,8 +207,6 @@ class ThriftTestCase(AsyncTestCase):
@gen_test
def test_exception(self):
yield self.client.testException('Safe')
try:
yield self.client.testException('Xception')
except Xception as ex:
@ -214,11 +216,13 @@ class ThriftTestCase(AsyncTestCase):
self.fail("should have gotten exception")
try:
yield self.client.testException('throw_undeclared')
except TTransportException as ex:
except TApplicationException:
pass
else:
self.fail("should have gotten exception")
yield self.client.testException('Safe')
def suite():
suite = unittest.TestSuite()

View file

@ -17,7 +17,6 @@
# under the License.
#
THRIFT = $(top_builddir)/compiler/cpp/thrift
TRIAL ?= trial
stubs: ../ThriftTest.thrift ../SmallTest.thrift

View file

@ -19,14 +19,17 @@
# under the License.
#
import sys
import os
import glob
import os
import sys
import time
basepath = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(basepath, 'gen-py.twisted'))
sys.path.insert(0, glob.glob(os.path.join(basepath, '../../lib/py/build/lib.*'))[0])
from thrift.Thrift import TApplicationException
from ThriftTest import ThriftTest
from ThriftTest.ttypes import Xception, Xtruct
from thrift.transport import TTwisted
@ -36,12 +39,11 @@ from twisted.trial import unittest
from twisted.internet import defer, reactor
from twisted.internet.protocol import ClientCreator
from zope.interface import implements
from zope.interface import implementer
@implementer(ThriftTest.Iface)
class TestHandler:
implements(ThriftTest.Iface)
def __init__(self):
self.onewaysQueue = defer.DeferredQueue()
@ -85,6 +87,7 @@ class TestHandler:
def fireOneway(t):
self.onewaysQueue.put((t, time.time(), seconds))
reactor.callLater(seconds, fireOneway, time.time())
raise Exception('')
def testNest(self, thing):
return thing
@ -172,7 +175,6 @@ class ThriftTestCase(unittest.TestCase):
@defer.inlineCallbacks
def testException(self):
yield self.client.testException('Safe')
try:
yield self.client.testException('Xception')
self.fail("should have gotten exception")
@ -182,12 +184,15 @@ class ThriftTestCase(unittest.TestCase):
try:
yield self.client.testException("throw_undeclared")
self.fail("should have thrown exception")
except Exception: # type is undefined
self.fail("should have gotten exception")
except TApplicationException:
pass
yield self.client.testException('Safe')
@defer.inlineCallbacks
def testOneway(self):
yield self.client.testOneway(1)
start, end, seconds = yield self.handler.onewaysQueue.get()
self.assertAlmostEquals(seconds, (end - start), places=1)
self.assertEquals((yield self.client.testI32(-1)), -1)

View file

@ -50,6 +50,7 @@ class TDevNullTransport(TTransport.TTransportBase):
def isOpen(self):
return True
ooe1 = OneOfEach()
ooe1.im_true = True
ooe1.im_false = False
@ -85,6 +86,10 @@ hm.big[1].a_bite = 0x22
hm.contain.add(("and a one", "and a two"))
hm.contain.add(("then a one, two", "three!", "FOUR!"))
if sys.version_info[0] == 2 and os.environ.get('THRIFT_TEST_PY_NO_UTF8STRINGS'):
hm.contain.add((u"\xd7\n\a\t".encode('utf8'),))
else:
hm.contain.add((u"\xd7\n\a\t",))
hm.contain.add(())
hm.bonks["nothing"] = []

View file

@ -18,25 +18,38 @@
#
AUTOMAKE_OPTIONS = serial-tests
THRIFT = $(top_builddir)/compiler/cpp/thrift
py_unit_tests = RunClientServer.py
thrift_gen = \
gen-py/ThriftTest/__init__.py \
gen-py/DebugProtoTest/__init__.py \
gen-py/DoubleConstantsTest/__init__.py \
gen-py/Recursive/__init__.py \
gen-py-default/ThriftTest/__init__.py \
gen-py-default/DebugProtoTest/__init__.py \
gen-py-default/DoubleConstantsTest/__init__.py \
gen-py-default/Recursive/__init__.py \
gen-py-slots/ThriftTest/__init__.py \
gen-py-slots/DebugProtoTest/__init__.py \
gen-py-slots/DoubleConstantsTest/__init__.py \
gen-py-slots/Recursive/__init__.py \
gen-py-oldstyle/ThriftTest/__init__.py \
gen-py-oldstyle/DebugProtoTest/__init__.py \
gen-py-oldstyle/DoubleConstantsTest/__init__.py \
gen-py-oldstyle/Recursive/__init__.py \
gen-py-no_utf8strings/ThriftTest/__init__.py \
gen-py-no_utf8strings/DebugProtoTest/__init__.py \
gen-py-no_utf8strings/DoubleConstantsTest/__init__.py \
gen-py-no_utf8strings/Recursive/__init__.py \
gen-py-dynamic/ThriftTest/__init__.py \
gen-py-dynamic/DebugProtoTest/__init__.py \
gen-py-dynamic/DoubleConstantsTest/__init__.py \
gen-py-dynamic/Recursive/__init__.py \
gen-py-dynamicslots/ThriftTest/__init__.py \
gen-py-dynamicslots/DebugProtoTest/__init__.py
gen-py-dynamicslots/DebugProtoTest/__init__.py \
gen-py-dynamicslots/DoubleConstantsTest/__init__.py \
gen-py-dynamicslots/Recursive/__init__.py
precross: $(thrift_gen)
BUILT_SOURCES = $(thrift_gen)

View file

@ -38,6 +38,7 @@ SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
SCRIPTS = [
'FastbinaryTest.py',
'TestFrozen.py',
'TestRenderedDoubleConstants.py',
'TSimpleJSONProtocolTest.py',
'SerializationTest.py',
'TestEof.py',
@ -46,7 +47,7 @@ SCRIPTS = [
]
FRAMED = ["TNonblockingServer"]
SKIP_ZLIB = ['TNonblockingServer', 'THttpServer']
SKIP_SSL = ['TNonblockingServer', 'THttpServer']
SKIP_SSL = ['THttpServer']
EXTRA_DELAY = dict(TProcessPoolServer=5.5)
PROTOS = [
@ -55,6 +56,7 @@ PROTOS = [
'binary',
'compact',
'json',
'header',
]

View file

@ -35,6 +35,11 @@ from ThriftTest.ttypes import (
Xtruct2,
)
from Recursive.ttypes import RecTree
from Recursive.ttypes import RecList
from Recursive.ttypes import CoRec
from Recursive.ttypes import CoRec2
from Recursive.ttypes import VectorTest
from DebugProtoTest.ttypes import CompactProtoTestStruct, Empty
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TCompactProtocol, TJSONProtocol
@ -285,6 +290,67 @@ class AbstractTest(unittest.TestCase):
for value in bad_values:
self.assertRaises(Exception, self._serialize, value)
def testRecTree(self):
"""Ensure recursive tree node can be created."""
children = []
for idx in range(1, 5):
node = RecTree(item=idx, children=None)
children.append(node)
parent = RecTree(item=0, children=children)
serde_parent = self._deserialize(RecTree, self._serialize(parent))
self.assertEquals(0, serde_parent.item)
self.assertEquals(4, len(serde_parent.children))
for child in serde_parent.children:
# Cannot use assertIsInstance in python 2.6?
self.assertTrue(isinstance(child, RecTree))
def _buildLinkedList(self):
head = cur = RecList(item=0)
for idx in range(1, 5):
node = RecList(item=idx)
cur.nextitem = node
cur = node
return head
def _collapseLinkedList(self, head):
out_list = []
cur = head
while cur is not None:
out_list.append(cur.item)
cur = cur.nextitem
return out_list
def testRecList(self):
"""Ensure recursive linked list can be created."""
rec_list = self._buildLinkedList()
serde_list = self._deserialize(RecList, self._serialize(rec_list))
out_list = self._collapseLinkedList(serde_list)
self.assertEquals([0, 1, 2, 3, 4], out_list)
def testCoRec(self):
"""Ensure co-recursive structures can be created."""
item1 = CoRec()
item2 = CoRec2()
item1.other = item2
item2.other = item1
# NOTE [econner724,2017-06-21]: These objects cannot be serialized as serialization
# results in an infinite loop. fbthrift also suffers from this
# problem.
def testRecVector(self):
"""Ensure a list of recursive nodes can be created."""
mylist = [self._buildLinkedList(), self._buildLinkedList()]
myvec = VectorTest(lister=mylist)
serde_vec = self._deserialize(VectorTest, self._serialize(myvec))
golden_list = [0, 1, 2, 3, 4]
for cur_list in serde_vec.lister:
out_list = self._collapseLinkedList(cur_list)
self.assertEqual(golden_list, out_list)
class NormalBinaryTest(AbstractTest):
protocol_factory = TBinaryProtocol.TBinaryProtocolFactory()
@ -386,5 +452,6 @@ def suite():
suite.addTest(loader.loadTestsFromTestCase(SerializersTest))
return suite
if __name__ == "__main__":
unittest.main(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=2))

View file

@ -32,8 +32,18 @@ SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
class AbstractTest(unittest.TestCase):
def setUp(self):
if options.http_path:
self.transport = THttpClient.THttpClient(options.host, port=options.port, path=options.http_path)
if options.trans == 'http':
uri = '{0}://{1}:{2}{3}'.format(('https' if options.ssl else 'http'),
options.host,
options.port,
(options.http_path if options.http_path else '/'))
if options.ssl:
__cafile = os.path.join(os.path.dirname(SCRIPT_DIR), "keys", "CA.pem")
__certfile = os.path.join(os.path.dirname(SCRIPT_DIR), "keys", "client.crt")
__keyfile = os.path.join(os.path.dirname(SCRIPT_DIR), "keys", "client.key")
self.transport = THttpClient.THttpClient(uri, cafile=__cafile, cert_file=__certfile, key_file=__keyfile)
else:
self.transport = THttpClient.THttpClient(uri)
else:
if options.ssl:
from thrift.transport import TSSLSocket
@ -53,6 +63,9 @@ class AbstractTest(unittest.TestCase):
self.transport.open()
protocol = self.get_protocol(self.transport)
self.client = ThriftTest.Client(protocol)
# for multiplexed services:
protocol2 = self.get_protocol2(self.transport)
self.client2 = SecondService.Client(protocol2) if protocol2 is not None else None
def tearDown(self):
self.transport.close()
@ -97,6 +110,11 @@ class AbstractTest(unittest.TestCase):
self.assertEqual(self.client.testString(s1), s1)
self.assertEqual(self.client.testString(s2), s2)
def testMultiplexed(self):
if self.client2 is not None:
print('testMultiplexed')
self.assertEqual(self.client2.secondtestString('foobar'), 'testString("foobar")')
def testBool(self):
print('testBool')
self.assertEqual(self.client.testBool(True), True)
@ -250,44 +268,117 @@ class AbstractTest(unittest.TestCase):
self.assertEqual(self.client.testString('Python'), 'Python')
class NormalBinaryTest(AbstractTest):
class MultiplexedOptionalTest(AbstractTest):
def get_protocol2(self, transport):
return None
class BinaryTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
return TBinaryProtocol.TBinaryProtocolFactory().getProtocol(transport)
class CompactTest(AbstractTest):
class MultiplexedBinaryTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
return TCompactProtocol.TCompactProtocolFactory().getProtocol(transport)
wrapped_proto = TBinaryProtocol.TBinaryProtocolFactory().getProtocol(transport)
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest")
def get_protocol2(self, transport):
wrapped_proto = TBinaryProtocol.TBinaryProtocolFactory().getProtocol(transport)
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "SecondService")
class JSONTest(AbstractTest):
def get_protocol(self, transport):
return TJSONProtocol.TJSONProtocolFactory().getProtocol(transport)
class AcceleratedBinaryTest(AbstractTest):
class AcceleratedBinaryTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
return TBinaryProtocol.TBinaryProtocolAcceleratedFactory(fallback=False).getProtocol(transport)
class AcceleratedCompactTest(AbstractTest):
class MultiplexedAcceleratedBinaryTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
wrapped_proto = TBinaryProtocol.TBinaryProtocolAcceleratedFactory(fallback=False).getProtocol(transport)
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest")
def get_protocol2(self, transport):
wrapped_proto = TBinaryProtocol.TBinaryProtocolAcceleratedFactory(fallback=False).getProtocol(transport)
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "SecondService")
class CompactTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
return TCompactProtocol.TCompactProtocolFactory().getProtocol(transport)
class MultiplexedCompactTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
wrapped_proto = TCompactProtocol.TCompactProtocolFactory().getProtocol(transport)
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest")
def get_protocol2(self, transport):
wrapped_proto = TCompactProtocol.TCompactProtocolFactory().getProtocol(transport)
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "SecondService")
class AcceleratedCompactTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
return TCompactProtocol.TCompactProtocolAcceleratedFactory(fallback=False).getProtocol(transport)
class MultiplexedAcceleratedCompactTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
wrapped_proto = TCompactProtocol.TCompactProtocolAcceleratedFactory(fallback=False).getProtocol(transport)
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest")
def get_protocol2(self, transport):
wrapped_proto = TCompactProtocol.TCompactProtocolAcceleratedFactory(fallback=False).getProtocol(transport)
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "SecondService")
class JSONTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
return TJSONProtocol.TJSONProtocolFactory().getProtocol(transport)
class MultiplexedJSONTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
wrapped_proto = TJSONProtocol.TJSONProtocolFactory().getProtocol(transport)
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest")
def get_protocol2(self, transport):
wrapped_proto = TJSONProtocol.TJSONProtocolFactory().getProtocol(transport)
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "SecondService")
class HeaderTest(MultiplexedOptionalTest):
def get_protocol(self, transport):
factory = THeaderProtocol.THeaderProtocolFactory()
return factory.getProtocol(transport)
def suite():
suite = unittest.TestSuite()
loader = unittest.TestLoader()
if options.proto == 'binary': # look for --proto on cmdline
suite.addTest(loader.loadTestsFromTestCase(NormalBinaryTest))
suite.addTest(loader.loadTestsFromTestCase(BinaryTest))
elif options.proto == 'accel':
suite.addTest(loader.loadTestsFromTestCase(AcceleratedBinaryTest))
elif options.proto == 'compact':
suite.addTest(loader.loadTestsFromTestCase(CompactTest))
elif options.proto == 'accelc':
suite.addTest(loader.loadTestsFromTestCase(AcceleratedCompactTest))
elif options.proto == 'compact':
suite.addTest(loader.loadTestsFromTestCase(CompactTest))
elif options.proto == 'header':
suite.addTest(loader.loadTestsFromTestCase(HeaderTest))
elif options.proto == 'json':
suite.addTest(loader.loadTestsFromTestCase(JSONTest))
elif options.proto == 'multi':
suite.addTest(loader.loadTestsFromTestCase(MultiplexedBinaryTest))
elif options.proto == 'multia':
suite.addTest(loader.loadTestsFromTestCase(MultiplexedAcceleratedBinaryTest))
elif options.proto == 'multiac':
suite.addTest(loader.loadTestsFromTestCase(MultiplexedAcceleratedCompactTest))
elif options.proto == 'multic':
suite.addTest(loader.loadTestsFromTestCase(MultiplexedCompactTest))
elif options.proto == 'multij':
suite.addTest(loader.loadTestsFromTestCase(MultiplexedJSONTest))
else:
raise AssertionError('Unknown protocol given with --protocol: %s' % options.proto)
return suite
@ -301,6 +392,7 @@ class OwnArgsTestProgram(unittest.TestProgram):
self.testNames = ([self.defaultTest])
self.createTests()
if __name__ == "__main__":
parser = OptionParser()
parser.add_option('--libpydir', type='string', dest='libpydir',
@ -324,9 +416,9 @@ if __name__ == "__main__":
dest="verbose", const=0,
help="minimal output")
parser.add_option('--protocol', dest="proto", type="string",
help="protocol to use, one of: accel, binary, compact, json")
help="protocol to use, one of: accel, accelc, binary, compact, header, json, multi, multia, multiac, multic, multij")
parser.add_option('--transport', dest="trans", type="string",
help="transport to use, one of: buffered, framed")
help="transport to use, one of: buffered, framed, http")
parser.set_defaults(framed=False, http_path=None, verbose=1, host='localhost', port=9090, proto='binary')
options, args = parser.parse_args()
@ -334,6 +426,10 @@ if __name__ == "__main__":
sys.path.insert(0, os.path.join(SCRIPT_DIR, options.genpydir))
sys.path.insert(0, local_libpath())
if options.http_path:
options.trans = 'http'
from ThriftTest import SecondService
from ThriftTest import ThriftTest
from ThriftTest.ttypes import Xtruct, Xtruct2, Numberz, Xception, Xception2
from thrift.Thrift import TException
@ -343,6 +439,8 @@ if __name__ == "__main__":
from thrift.transport import TZlibTransport
from thrift.protocol import TBinaryProtocol
from thrift.protocol import TCompactProtocol
from thrift.protocol import THeaderProtocol
from thrift.protocol import TJSONProtocol
from thrift.protocol import TMultiplexedProtocol
OwnArgsTestProgram(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=1))

View file

@ -127,5 +127,6 @@ def suite():
suite.addTest(loader.loadTestsFromTestCase(TestEof))
return suite
if __name__ == "__main__":
unittest.main(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=2))

View file

@ -118,5 +118,6 @@ def suite():
suite.addTest(loader.loadTestsFromTestCase(TestFrozenAcceleratedCompact))
return suite
if __name__ == "__main__":
unittest.main(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=2))

View file

@ -0,0 +1,177 @@
#
# 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.
#
import unittest
from DoubleConstantsTest import constants
#
# In order to run the test under Windows. We need to create symbolic link
# name 'thrift' to '../src' folder by using:
#
# mklink /D thrift ..\src
#
class TestRenderedDoubleConstants(unittest.TestCase):
ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST = \
"failed to verify a double constant generated by Thrift (expected = %f, got = %f)"
ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST =\
"failed to verify a list item by Thrift (expected = %f, got = %f)"
ASSERTION_MESSAGE_FOR_TYPE_CHECKS = "the rendered variable with name %s is not of double type"
# to make sure the variables inside Thrift files are generated correctly
def test_rendered_double_constants(self):
EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT = 1.0
EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT = -100.0
EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT = 9223372036854775807.0
EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT = -9223372036854775807.0
EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS = 3.14159265359
EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE = 1000000.1
EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE = -1000000.1
EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE = 1.7e+308
EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE = 9223372036854775816.43
EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE = -1.7e+308
EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE = -9223372036854775816.43
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, constants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST))
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT,
places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT,
constants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST))
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT,
places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT,
constants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST))
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT,
places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT,
constants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST))
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST,
EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS,
constants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST))
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE,
places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE,
constants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST))
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST,
EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE,
constants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST))
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE,
constants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST))
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST,
EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE,
constants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST))
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE,
constants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST))
self.assertAlmostEqual(
constants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST,
EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, places=7,
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST % (
EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE,
constants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST))
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST")
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST")
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST")
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST")
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST")
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST")
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST")
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST")
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST")
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST")
self.assertTrue(
isinstance(constants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, float),
msg=TestRenderedDoubleConstants.ASSERTION_MESSAGE_FOR_TYPE_CHECKS %
"DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST")
# to make sure the variables inside Thrift files are generated correctly
def test_rendered_double_list(self):
EXPECTED_DOUBLE_LIST = [1.0, -100.0, 100.0, 9223372036854775807.0, -9223372036854775807.0, 3.14159265359,
1000000.1, -1000000.1, 1.7e+308, -1.7e+308, 9223372036854775816.43,
-9223372036854775816.43]
self.assertEqual(len(constants.DOUBLE_LIST_TEST), len(EXPECTED_DOUBLE_LIST))
for i, expectedValue in enumerate(EXPECTED_DOUBLE_LIST):
self.assertAlmostEqual(constants.DOUBLE_LIST_TEST[i], expectedValue, places=7)
def suite():
suite = unittest.TestSuite()
loader = unittest.TestLoader()
suite.addTest(loader.loadTestsFromTestCase(TestRenderedDoubleConstants))
return suite
if __name__ == "__main__":
unittest.main(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=2))

Some files were not shown because too many files have changed in this diff Show more