Revert "THRIFT-2729: C++ - .clang-format created and applied"
This reverts commit 74260aa9099c3bb209bc8e524b0e8ba603f62c41.
diff --git a/lib/cpp/test/AllProtocolTests.cpp b/lib/cpp/test/AllProtocolTests.cpp
index 29ba193..65d1927 100644
--- a/lib/cpp/test/AllProtocolTests.cpp
+++ b/lib/cpp/test/AllProtocolTests.cpp
@@ -31,8 +31,8 @@
char errorMessage[ERR_LEN];
int main(int argc, char** argv) {
- (void)argc;
- (void)argv;
+ (void) argc;
+ (void) argv;
try {
testProtocol<TBinaryProtocol>("TBinaryProtocol");
testProtocol<TCompactProtocol>("TCompactProtocol");
diff --git a/lib/cpp/test/AllProtocolTests.tcc b/lib/cpp/test/AllProtocolTests.tcc
index 8c8eaa8..3c98943 100644
--- a/lib/cpp/test/AllProtocolTests.tcc
+++ b/lib/cpp/test/AllProtocolTests.tcc
@@ -45,10 +45,7 @@
Val out;
GenericIO::read(protocol, out);
if (out != val) {
- THRIFT_SNPRINTF(errorMessage,
- ERR_LEN,
- "Invalid naked test (type: %s)",
- ClassNames::getName<Val>());
+ THRIFT_SNPRINTF(errorMessage, ERR_LEN, "Invalid naked test (type: %s)", ClassNames::getName<Val>());
throw TException(errorMessage);
}
}
@@ -100,18 +97,22 @@
const char* name;
TMessageType type;
int32_t seqid;
- } messages[] = {{"short message name", T_CALL, 0},
- {"1", T_REPLY, 12345},
- {"loooooooooooooooooooooooooooooooooong", T_EXCEPTION, 1 << 16},
- {"one way push", T_ONEWAY, 12},
- {"Janky", T_CALL, 0}};
+ } messages[] = {
+ {"short message name", T_CALL, 0},
+ {"1", T_REPLY, 12345},
+ {"loooooooooooooooooooooooooooooooooong", T_EXCEPTION, 1 << 16},
+ {"one way push", T_ONEWAY, 12},
+ {"Janky", T_CALL, 0}
+ };
const int messages_count = sizeof(messages) / sizeof(TMessage);
for (int i = 0; i < messages_count; i++) {
shared_ptr<TTransport> transport(new TMemoryBuffer());
shared_ptr<TProtocol> protocol(new TProto(transport));
- protocol->writeMessageBegin(messages[i].name, messages[i].type, messages[i].seqid);
+ protocol->writeMessageBegin(messages[i].name,
+ messages[i].type,
+ messages[i].seqid);
protocol->writeMessageEnd();
std::string name;
@@ -119,7 +120,9 @@
int32_t seqid;
protocol->readMessageBegin(name, type, seqid);
- if (name != messages[i].name || type != messages[i].type || seqid != messages[i].seqid) {
+ if (name != messages[i].name ||
+ type != messages[i].type ||
+ seqid != messages[i].seqid) {
throw TException("readMessageBegin failed.");
}
}
@@ -188,6 +191,7 @@
testNaked<TProto, int64_t>((std::numeric_limits<int64_t>::min)());
testNaked<TProto, int64_t>((std::numeric_limits<int64_t>::max)());
+
testNaked<TProto, int64_t>(0);
for (int64_t i = 0; i < 62; i++) {
testNaked<TProto, int64_t>(1L << i);
@@ -206,7 +210,7 @@
testNaked<TProto, std::string>("short");
testNaked<TProto, std::string>("borderlinetiny");
testNaked<TProto, std::string>("a bit longer than the smallest possible");
- testNaked<TProto, std::string>("\x1\x2\x3\x4\x5\x6\x7\x8\x9\xA"); // kinda binary test
+ testNaked<TProto, std::string>("\x1\x2\x3\x4\x5\x6\x7\x8\x9\xA"); //kinda binary test
testField<TProto, T_STRING, std::string>("");
testField<TProto, T_STRING, std::string>("short");
diff --git a/lib/cpp/test/Base64Test.cpp b/lib/cpp/test/Base64Test.cpp
index e9e86dd..5caaae8 100644
--- a/lib/cpp/test/Base64Test.cpp
+++ b/lib/cpp/test/Base64Test.cpp
@@ -23,7 +23,7 @@
using apache::thrift::protocol::base64_encode;
using apache::thrift::protocol::base64_decode;
-BOOST_AUTO_TEST_SUITE(Base64Test)
+BOOST_AUTO_TEST_SUITE( Base64Test )
void setupTestData(int i, uint8_t* data, int& len) {
len = 0;
@@ -42,7 +42,7 @@
}
}
-BOOST_AUTO_TEST_CASE(test_Base64_Encode_Decode) {
+BOOST_AUTO_TEST_CASE( test_Base64_Encode_Decode ) {
int len;
uint8_t testInput[3];
uint8_t testOutput[4];
@@ -64,6 +64,7 @@
// decode output and check that it matches input
base64_decode(testOutput, len + 1);
BOOST_ASSERT(0 == memcmp(testInput, testOutput, len));
+
}
}
diff --git a/lib/cpp/test/Benchmark.cpp b/lib/cpp/test/Benchmark.cpp
index cf6b79a..3571150 100644
--- a/lib/cpp/test/Benchmark.cpp
+++ b/lib/cpp/test/Benchmark.cpp
@@ -34,8 +34,12 @@
public:
timeval vStart;
- Timer() { THRIFT_GETTIMEOFDAY(&vStart, 0); }
- void start() { THRIFT_GETTIMEOFDAY(&vStart, 0); }
+ Timer() {
+ THRIFT_GETTIMEOFDAY(&vStart, 0);
+ }
+ void start() {
+ THRIFT_GETTIMEOFDAY(&vStart, 0);
+ }
double frame() {
timeval vEnd;
@@ -44,6 +48,7 @@
double dend = vEnd.tv_sec + ((double)vEnd.tv_usec / 1000000.0);
return dend - dstart;
}
+
};
int main() {
@@ -54,15 +59,15 @@
using namespace boost;
OneOfEach ooe;
- ooe.im_true = true;
- ooe.im_false = false;
- ooe.a_bite = 0x7f;
+ ooe.im_true = true;
+ ooe.im_false = false;
+ ooe.a_bite = 0x7f;
ooe.integer16 = 27000;
- ooe.integer32 = 1 << 24;
+ ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
- ooe.some_characters = "JSON THIS! \"\1";
- ooe.zomg_unicode = "\xd7\n\a\t";
+ ooe.some_characters = "JSON THIS! \"\1";
+ ooe.zomg_unicode = "\xd7\n\a\t";
ooe.base64 = "\1\2\3\255";
boost::shared_ptr<TMemoryBuffer> buf(new TMemoryBuffer());
@@ -72,7 +77,7 @@
{
Timer timer;
- for (int i = 0; i < num; i++) {
+ for (int i = 0; i < num; i ++) {
buf->resetBuffer();
TBinaryProtocolT<TBufferBase> prot(buf);
ooe.write(&prot);
@@ -89,17 +94,18 @@
Timer timer;
- for (int i = 0; i < num; i++) {
+ for (int i = 0; i < num; i ++) {
OneOfEach ooe2;
boost::shared_ptr<TMemoryBuffer> buf2(new TMemoryBuffer(data, datasize));
- // buf2->resetBuffer(data, datasize);
+ //buf2->resetBuffer(data, datasize);
TBinaryProtocolT<TBufferBase> prot(buf2);
ooe2.read(&prot);
- // cout << apache::thrift::ThriftDebugString(ooe2) << endl << endl;
+ //cout << apache::thrift::ThriftDebugString(ooe2) << endl << endl;
}
cout << " Read: " << num / (1000 * timer.frame()) << " kHz" << endl;
}
+
return 0;
}
diff --git a/lib/cpp/test/DebugProtoTest.cpp b/lib/cpp/test/DebugProtoTest.cpp
index 98c66b8..5649e18 100644
--- a/lib/cpp/test/DebugProtoTest.cpp
+++ b/lib/cpp/test/DebugProtoTest.cpp
@@ -28,34 +28,37 @@
using std::endl;
using namespace thrift::test::debug;
+
OneOfEach ooe;
- ooe.im_true = true;
- ooe.im_false = false;
- ooe.a_bite = 0x7f;
+ ooe.im_true = true;
+ ooe.im_false = false;
+ ooe.a_bite = 0x7f;
ooe.integer16 = 27000;
- ooe.integer32 = 1 << 24;
+ ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
- ooe.some_characters = "Debug THIS!";
- ooe.zomg_unicode = "\xd7\n\a\t";
+ ooe.some_characters = "Debug THIS!";
+ ooe.zomg_unicode = "\xd7\n\a\t";
cout << apache::thrift::ThriftDebugString(ooe) << endl << endl;
+
Nesting n;
n.my_ooe = ooe;
n.my_ooe.integer16 = 16;
n.my_ooe.integer32 = 32;
n.my_ooe.integer64 = 64;
- n.my_ooe.double_precision = (std::sqrt(5.0) + 1) / 2;
- n.my_ooe.some_characters = ":R (me going \"rrrr\")";
+ n.my_ooe.double_precision = (std::sqrt(5.0)+1)/2;
+ n.my_ooe.some_characters = ":R (me going \"rrrr\")";
n.my_ooe.zomg_unicode = "\xd3\x80\xe2\x85\xae\xce\x9d\x20"
"\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"
"\x20\xce\x91\x74\x74\xce\xb1\xe2\x85\xbd\xce\xba\xc7\x83\xe2\x80\xbc";
- n.my_bonk.type = 31337;
+ n.my_bonk.type = 31337;
n.my_bonk.message = "I am a bonk... xor!";
cout << apache::thrift::ThriftDebugString(n) << endl << endl;
+
HolyMoley hm;
hm.big.push_back(ooe);
@@ -77,26 +80,27 @@
std::vector<Bonk> stage2;
hm.bonks["nothing"] = stage2;
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 1;
stage2.back().message = "Wait.";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 2;
stage2.back().message = "What?";
hm.bonks["something"] = stage2;
stage2.clear();
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 3;
stage2.back().message = "quoth";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 4;
stage2.back().message = "the raven";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 5;
stage2.back().message = "nevermore";
hm.bonks["poe"] = stage2;
cout << apache::thrift::ThriftDebugString(hm) << endl << endl;
+
return 0;
}
diff --git a/lib/cpp/test/DebugProtoTest_extras.cpp b/lib/cpp/test/DebugProtoTest_extras.cpp
index 5c4fd35..c89db74 100644
--- a/lib/cpp/test/DebugProtoTest_extras.cpp
+++ b/lib/cpp/test/DebugProtoTest_extras.cpp
@@ -21,15 +21,13 @@
#include "gen-cpp/DebugProtoTest_types.h"
-namespace thrift {
-namespace test {
-namespace debug {
+
+namespace thrift { namespace test { namespace debug {
bool Empty::operator<(Empty const& other) const {
- (void)other;
+ (void) other;
// It is empty, so all are equal.
return false;
}
-}
-}
-}
+
+}}}
diff --git a/lib/cpp/test/DenseProtoTest.cpp b/lib/cpp/test/DenseProtoTest.cpp
index d827d3c..f73579f 100644
--- a/lib/cpp/test/DenseProtoTest.cpp
+++ b/lib/cpp/test/DenseProtoTest.cpp
@@ -42,6 +42,7 @@
#include <thrift/protocol/TDenseProtocol.h>
#include <thrift/transport/TBufferTransports.h>
+
// Can't use memcmp here. GCC is too smart.
bool my_memeq(const char* str1, const char* str2, int len) {
for (int i = 0; i < len; i++) {
@@ -52,6 +53,7 @@
return true;
}
+
int main() {
using std::string;
using std::cout;
@@ -61,33 +63,36 @@
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;
+
OneOfEach ooe;
- ooe.im_true = true;
- ooe.im_false = false;
- ooe.a_bite = 0xd6;
+ ooe.im_true = true;
+ ooe.im_false = false;
+ ooe.a_bite = 0xd6;
ooe.integer16 = 27000;
- ooe.integer32 = 1 << 24;
+ ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
- ooe.some_characters = "Debug THIS!";
- ooe.zomg_unicode = "\xd7\n\a\t";
+ ooe.some_characters = "Debug THIS!";
+ ooe.zomg_unicode = "\xd7\n\a\t";
- // cout << apache::thrift::ThriftDebugString(ooe) << endl << endl;
+ //cout << apache::thrift::ThriftDebugString(ooe) << endl << endl;
+
Nesting n;
n.my_ooe = ooe;
n.my_ooe.integer16 = 16;
n.my_ooe.integer32 = 32;
n.my_ooe.integer64 = 64;
- n.my_ooe.double_precision = (std::sqrt(5) + 1) / 2;
- n.my_ooe.some_characters = ":R (me going \"rrrr\")";
+ n.my_ooe.double_precision = (std::sqrt(5)+1)/2;
+ n.my_ooe.some_characters = ":R (me going \"rrrr\")";
n.my_ooe.zomg_unicode = "\xd3\x80\xe2\x85\xae\xce\x9d\x20"
"\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"
"\x20\xce\x91\x74\x74\xce\xb1\xe2\x85\xbd\xce\xba\xc7\x83\xe2\x80\xbc";
- n.my_bonk.type = 31337;
+ n.my_bonk.type = 31337;
n.my_bonk.message = "I am a bonk... xor!";
- // cout << apache::thrift::ThriftDebugString(n) << endl << endl;
+ //cout << apache::thrift::ThriftDebugString(n) << endl << endl;
+
HolyMoley hm;
@@ -110,26 +115,26 @@
std::vector<Bonk> stage2;
hm.bonks["nothing"] = stage2;
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 1;
stage2.back().message = "Wait.";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 2;
stage2.back().message = "What?";
hm.bonks["something"] = stage2;
stage2.clear();
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 3;
stage2.back().message = "quoth";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 4;
stage2.back().message = "the raven";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 5;
stage2.back().message = "nevermore";
hm.bonks["poe"] = stage2;
- // cout << apache::thrift::ThriftDebugString(hm) << endl << endl;
+ //cout << apache::thrift::ThriftDebugString(hm) << endl << endl;
shared_ptr<TMemoryBuffer> buffer(new TMemoryBuffer());
shared_ptr<TDenseProtocol> proto(new TDenseProtocol(buffer));
@@ -141,16 +146,16 @@
assert(hm == hm2);
+
// Let's test out the variable-length ints, shall we?
uint64_t vlq;
-#define checkout(i, c) \
- { \
- buffer->resetBuffer(); \
- proto->vlqWrite(i); \
- proto->getTransport()->flush(); \
- assert(my_memeq(buffer->getBufferAsString().data(), c, sizeof(c) - 1)); \
- proto->vlqRead(vlq); \
- assert(vlq == i); \
+ #define checkout(i, c) { \
+ buffer->resetBuffer(); \
+ proto->vlqWrite(i); \
+ proto->getTransport()->flush(); \
+ assert(my_memeq(buffer->getBufferAsString().data(), c, sizeof(c)-1)); \
+ proto->vlqRead(vlq); \
+ assert(vlq == i); \
}
checkout(0x00000000, "\x00");
@@ -287,6 +292,7 @@
assert(mo1 == mo6);
+
// Test fingerprint checking stuff.
{
@@ -360,7 +366,7 @@
buffer->resetBuffer();
// Make sure the fingerprint prefix is right.
buffer->write(Nesting::binary_fingerprint, 4);
- for (int j = 0; j < 1024 * 1024; j++) {
+ for (int j = 0; j < 1024*1024; j++) {
uint8_t r = std::rand();
buffer->write(&r, 1);
}
diff --git a/lib/cpp/test/EnumTest.cpp b/lib/cpp/test/EnumTest.cpp
index 0e34b16..72f98bb 100644
--- a/lib/cpp/test/EnumTest.cpp
+++ b/lib/cpp/test/EnumTest.cpp
@@ -20,9 +20,9 @@
#include <boost/test/unit_test.hpp>
#include "gen-cpp/EnumTest_types.h"
-BOOST_AUTO_TEST_SUITE(EnumTest)
+BOOST_AUTO_TEST_SUITE( EnumTest )
-BOOST_AUTO_TEST_CASE(test_enum) {
+BOOST_AUTO_TEST_CASE( test_enum ) {
// Check that all the enum values match what we expect
BOOST_CHECK_EQUAL(MyEnum1::ME1_0, 0);
BOOST_CHECK_EQUAL(MyEnum1::ME1_1, 1);
@@ -49,7 +49,7 @@
BOOST_CHECK_EQUAL(MyEnum4::ME4_C, 0x7fffffff);
}
-BOOST_AUTO_TEST_CASE(test_enum_constant) {
+BOOST_AUTO_TEST_CASE( test_enum_constant ) {
MyStruct ms;
BOOST_CHECK_EQUAL(ms.me2_2, 2);
BOOST_CHECK_EQUAL(ms.me3_n2, -2);
diff --git a/lib/cpp/test/GenericHelpers.h b/lib/cpp/test/GenericHelpers.h
index c175561..1853a37 100644
--- a/lib/cpp/test/GenericHelpers.h
+++ b/lib/cpp/test/GenericHelpers.h
@@ -29,41 +29,22 @@
/* ClassName Helper for cleaner exceptions */
class ClassNames {
-public:
+ public:
template <typename T>
- static const char* getName() {
- return "Unknown type";
- }
+ static const char* getName() { return "Unknown type"; }
};
-template <>
-const char* ClassNames::getName<int8_t>() {
- return "byte";
-}
-template <>
-const char* ClassNames::getName<int16_t>() {
- return "short";
-}
-template <>
-const char* ClassNames::getName<int32_t>() {
- return "int";
-}
-template <>
-const char* ClassNames::getName<int64_t>() {
- return "long";
-}
-template <>
-const char* ClassNames::getName<double>() {
- return "double";
-}
-template <>
-const char* ClassNames::getName<std::string>() {
- return "string";
-}
+template <> const char* ClassNames::getName<int8_t>() { return "byte"; }
+template <> const char* ClassNames::getName<int16_t>() { return "short"; }
+template <> const char* ClassNames::getName<int32_t>() { return "int"; }
+template <> const char* ClassNames::getName<int64_t>() { return "long"; }
+template <> const char* ClassNames::getName<double>() { return "double"; }
+template <> const char* ClassNames::getName<std::string>() { return "string"; }
/* Generic Protocol I/O function for tests */
class GenericIO {
-public:
+ public:
+
/* Write functions */
static uint32_t write(shared_ptr<TProtocol> proto, const int8_t& val) {
@@ -92,19 +73,30 @@
/* Read functions */
- static uint32_t read(shared_ptr<TProtocol> proto, int8_t& val) { return proto->readByte(val); }
+ static uint32_t read(shared_ptr<TProtocol> proto, int8_t& val) {
+ return proto->readByte(val);
+ }
- static uint32_t read(shared_ptr<TProtocol> proto, int16_t& val) { return proto->readI16(val); }
+ static uint32_t read(shared_ptr<TProtocol> proto, int16_t& val) {
+ return proto->readI16(val);
+ }
- static uint32_t read(shared_ptr<TProtocol> proto, int32_t& val) { return proto->readI32(val); }
+ static uint32_t read(shared_ptr<TProtocol> proto, int32_t& val) {
+ return proto->readI32(val);
+ }
- static uint32_t read(shared_ptr<TProtocol> proto, int64_t& val) { return proto->readI64(val); }
+ static uint32_t read(shared_ptr<TProtocol> proto, int64_t& val) {
+ return proto->readI64(val);
+ }
- static uint32_t read(shared_ptr<TProtocol> proto, double& val) { return proto->readDouble(val); }
+ static uint32_t read(shared_ptr<TProtocol> proto, double& val) {
+ return proto->readDouble(val);
+ }
static uint32_t read(shared_ptr<TProtocol> proto, std::string& val) {
return proto->readString(val);
}
+
};
#endif
diff --git a/lib/cpp/test/JSONProtoTest.cpp b/lib/cpp/test/JSONProtoTest.cpp
index aa07f93..a3259c0 100644
--- a/lib/cpp/test/JSONProtoTest.cpp
+++ b/lib/cpp/test/JSONProtoTest.cpp
@@ -32,33 +32,35 @@
using apache::thrift::protocol::TJSONProtocol;
OneOfEach ooe;
- ooe.im_true = true;
- ooe.im_false = false;
- ooe.a_bite = 0x7f;
+ ooe.im_true = true;
+ ooe.im_false = false;
+ ooe.a_bite = 0x7f;
ooe.integer16 = 27000;
- ooe.integer32 = 1 << 24;
+ ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
- ooe.some_characters = "JSON THIS! \"\1";
- ooe.zomg_unicode = "\xd7\n\a\t";
+ ooe.some_characters = "JSON THIS! \"\1";
+ ooe.zomg_unicode = "\xd7\n\a\t";
ooe.base64 = "\1\2\3\255";
cout << apache::thrift::ThriftJSONString(ooe) << endl << endl;
+
Nesting n;
n.my_ooe = ooe;
n.my_ooe.integer16 = 16;
n.my_ooe.integer32 = 32;
n.my_ooe.integer64 = 64;
- n.my_ooe.double_precision = (std::sqrt(5.0) + 1) / 2;
- n.my_ooe.some_characters = ":R (me going \"rrrr\")";
+ n.my_ooe.double_precision = (std::sqrt(5.0)+1)/2;
+ n.my_ooe.some_characters = ":R (me going \"rrrr\")";
n.my_ooe.zomg_unicode = "\xd3\x80\xe2\x85\xae\xce\x9d\x20"
"\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"
"\x20\xce\x91\x74\x74\xce\xb1\xe2\x85\xbd\xce\xba\xc7\x83\xe2\x80\xbc";
- n.my_bonk.type = 31337;
+ n.my_bonk.type = 31337;
n.my_bonk.message = "I am a bonk... xor!";
cout << apache::thrift::ThriftJSONString(n) << endl << endl;
+
HolyMoley hm;
hm.big.push_back(ooe);
@@ -80,21 +82,21 @@
std::vector<Bonk> stage2;
hm.bonks["nothing"] = stage2;
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 1;
stage2.back().message = "Wait.";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 2;
stage2.back().message = "What?";
hm.bonks["something"] = stage2;
stage2.clear();
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 3;
stage2.back().message = "quoth";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 4;
stage2.back().message = "the raven";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 5;
stage2.back().message = "nevermore";
hm.bonks["poe"] = stage2;
@@ -104,6 +106,7 @@
boost::shared_ptr<TMemoryBuffer> buffer(new TMemoryBuffer());
boost::shared_ptr<TJSONProtocol> proto(new TJSONProtocol(buffer));
+
cout << "Testing ooe" << endl;
ooe.write(proto.get());
@@ -112,6 +115,7 @@
assert(ooe == ooe2);
+
cout << "Testing hm" << endl;
hm.write(proto.get());
@@ -125,10 +129,10 @@
assert(hm != hm2);
Doubles dub;
- dub.nan = HUGE_VAL / HUGE_VAL;
+ dub.nan = HUGE_VAL/HUGE_VAL;
dub.inf = HUGE_VAL;
dub.neginf = -HUGE_VAL;
- dub.repeating = 10.0 / 3.0;
+ dub.repeating = 10.0/3.0;
dub.big = 1E+305;
dub.tiny = 1E-305;
dub.zero = 0.0;
diff --git a/lib/cpp/test/OpenSSLManualInitTest.cpp b/lib/cpp/test/OpenSSLManualInitTest.cpp
index b04ed43..fbecbc3 100644
--- a/lib/cpp/test/OpenSSLManualInitTest.cpp
+++ b/lib/cpp/test/OpenSSLManualInitTest.cpp
@@ -69,7 +69,8 @@
boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
THRIFT_UNUSED_VARIABLE(argc);
THRIFT_UNUSED_VARIABLE(argv);
- boost::unit_test::test_suite* suite = &boost::unit_test::framework::master_test_suite();
+ boost::unit_test::test_suite* suite =
+ &boost::unit_test::framework::master_test_suite();
suite->p_name.value = "OpenSSLManualInit";
suite->add(BOOST_TEST_CASE(test_openssl_availability));
diff --git a/lib/cpp/test/OptionalRequiredTest.cpp b/lib/cpp/test/OptionalRequiredTest.cpp
index 79fa697..44b6885 100644
--- a/lib/cpp/test/OptionalRequiredTest.cpp
+++ b/lib/cpp/test/OptionalRequiredTest.cpp
@@ -38,6 +38,7 @@
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;
+
/*
template<typename Struct>
void trywrite(const Struct& s, bool should_work) {
@@ -54,12 +55,13 @@
*/
template <typename Struct1, typename Struct2>
-void write_to_read(const Struct1& w, Struct2& r) {
+void write_to_read(const Struct1 & w, Struct2 & r) {
TBinaryProtocol protocol(boost::shared_ptr<TTransport>(new TMemoryBuffer));
w.write(&protocol);
r.read(&protocol);
}
+
int main() {
cout << "This old school struct should have three fields." << endl;
@@ -96,22 +98,22 @@
Simple s1, s2, s3;
s1.im_optional = 10;
assert(!s1.__isset.im_default);
- // assert(!s1.__isset.im_required); // Compile error.
+ //assert(!s1.__isset.im_required); // Compile error.
assert(!s1.__isset.im_optional);
write_to_read(s1, s2);
- assert(s2.__isset.im_default);
- // assert( s2.__isset.im_required); // Compile error.
+ assert( s2.__isset.im_default);
+ //assert( s2.__isset.im_required); // Compile error.
assert(!s2.__isset.im_optional);
assert(s3.im_optional == 0);
s1.__isset.im_optional = true;
write_to_read(s1, s3);
- assert(s3.__isset.im_default);
- // assert( s3.__isset.im_required); // Compile error.
- assert(s3.__isset.im_optional);
+ assert( s3.__isset.im_default);
+ //assert( s3.__isset.im_required); // Compile error.
+ assert( s3.__isset.im_optional);
assert(s3.im_optional == 10);
}
@@ -124,7 +126,7 @@
write_to_read(t2, t1);
write_to_read(t1, t2);
assert(!t1.__isset.im_default);
- assert(t2.__isset.im_optional);
+ assert( t2.__isset.im_optional);
assert(t1.im_default == t2.im_optional);
assert(t1.im_default == 0);
}
@@ -154,8 +156,8 @@
try {
write_to_read(t2, t3);
abort();
- } catch (const TProtocolException&) {
}
+ catch (const TProtocolException&) {}
write_to_read(t3, t2);
assert(t2.__isset.im_optional);
@@ -167,6 +169,7 @@
cout << ThriftDebugString(c) << endl;
}
+
{
Tricky1 t1;
Tricky2 t2;
@@ -191,12 +194,12 @@
assert(o1 == o2);
o1.__isset.im_str = o2.__isset.im_str = true;
assert(o1 == o2);
- map<int32_t, string> mymap;
+ map<int32_t,string> mymap;
mymap[1] = "bar";
mymap[2] = "baz";
- o1.im_big.push_back(map<int32_t, string>());
+ o1.im_big.push_back(map<int32_t,string>());
assert(o1 != o2);
- o2.im_big.push_back(map<int32_t, string>());
+ o2.im_big.push_back(map<int32_t,string>());
assert(o1 == o2);
o2.im_big.push_back(mymap);
assert(o1 != o2);
@@ -217,7 +220,7 @@
o3.im_big.push_back(mymap);
assert(o1 == o3);
- // cout << ThriftDebugString(o3) << endl;
+ //cout << ThriftDebugString(o3) << endl;
}
{
diff --git a/lib/cpp/test/RWMutexStarveTest.cpp b/lib/cpp/test/RWMutexStarveTest.cpp
index 32c1531..e6cccf2 100644
--- a/lib/cpp/test/RWMutexStarveTest.cpp
+++ b/lib/cpp/test/RWMutexStarveTest.cpp
@@ -33,13 +33,16 @@
using namespace apache::thrift::concurrency;
using namespace std;
-class Locker : public Runnable {
+class Locker : public Runnable
+{
protected:
- Locker(boost::shared_ptr<ReadWriteMutex> rwlock, bool writer)
- : rwlock_(rwlock), writer_(writer), started_(false), gotLock_(false), signaled_(false) {}
+ Locker(boost::shared_ptr<ReadWriteMutex> rwlock, bool writer) :
+ rwlock_(rwlock), writer_(writer),
+ started_(false), gotLock_(false), signaled_(false) { }
public:
- virtual void run() {
+ virtual void run()
+ {
started_ = true;
if (writer_) {
rwlock_->acquireWrite();
@@ -65,17 +68,20 @@
volatile bool signaled_;
};
-class Reader : public Locker {
+class Reader : public Locker
+{
public:
- Reader(boost::shared_ptr<ReadWriteMutex> rwlock) : Locker(rwlock, false) {}
+ Reader(boost::shared_ptr<ReadWriteMutex> rwlock) : Locker(rwlock, false) { }
};
-class Writer : public Locker {
+class Writer : public Locker
+{
public:
- Writer(boost::shared_ptr<ReadWriteMutex> rwlock) : Locker(rwlock, true) {}
+ Writer(boost::shared_ptr<ReadWriteMutex> rwlock) : Locker(rwlock, true) { }
};
-void test_starve(PosixThreadFactory::POLICY policy) {
+void test_starve(PosixThreadFactory::POLICY policy)
+{
// the man pages for pthread_wrlock_rdlock suggest that any OS guarantee about
// writer starvation may be influenced by the scheduling policy, so let's try
// all 3 policies to see if any of them work.
@@ -142,17 +148,20 @@
BOOST_CHECK_MESSAGE(success, "writer is starving");
}
-BOOST_AUTO_TEST_SUITE(RWMutexStarveTest)
+BOOST_AUTO_TEST_SUITE( RWMutexStarveTest )
-BOOST_AUTO_TEST_CASE(test_starve_other) {
+BOOST_AUTO_TEST_CASE( test_starve_other )
+{
test_starve(PosixThreadFactory::OTHER);
}
-BOOST_AUTO_TEST_CASE(test_starve_rr) {
+BOOST_AUTO_TEST_CASE( test_starve_rr )
+{
test_starve(PosixThreadFactory::ROUND_ROBIN);
}
-BOOST_AUTO_TEST_CASE(test_starve_fifo) {
+BOOST_AUTO_TEST_CASE( test_starve_fifo )
+{
test_starve(PosixThreadFactory::FIFO);
}
diff --git a/lib/cpp/test/RecursiveTest.cpp b/lib/cpp/test/RecursiveTest.cpp
index a74be91..24c0f7c 100644
--- a/lib/cpp/test/RecursiveTest.cpp
+++ b/lib/cpp/test/RecursiveTest.cpp
@@ -27,7 +27,7 @@
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::protocol::TBinaryProtocol;
-using boost::shared_ptr;
+ using boost::shared_ptr;
int main() {
shared_ptr<TMemoryBuffer> buf(new TMemoryBuffer());
@@ -71,4 +71,5 @@
assert(false);
} catch (const apache::thrift::protocol::TProtocolException& e) {
}
+
}
diff --git a/lib/cpp/test/SpecializationTest.cpp b/lib/cpp/test/SpecializationTest.cpp
index 856bdac..0bef12a 100644
--- a/lib/cpp/test/SpecializationTest.cpp
+++ b/lib/cpp/test/SpecializationTest.cpp
@@ -12,20 +12,20 @@
using namespace apache::thrift::protocol;
typedef TBinaryProtocolT<TMemoryBuffer> MyProtocol;
-// typedef TBinaryProtocolT<TTransport> MyProtocol;
+//typedef TBinaryProtocolT<TTransport> MyProtocol;
int main() {
OneOfEach ooe;
- ooe.im_true = true;
- ooe.im_false = false;
- ooe.a_bite = 0x7f;
+ ooe.im_true = true;
+ ooe.im_false = false;
+ ooe.a_bite = 0x7f;
ooe.integer16 = 27000;
- ooe.integer32 = 1 << 24;
+ ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
- ooe.some_characters = "JSON THIS! \"\1";
- ooe.zomg_unicode = "\xd7\n\a\t";
+ ooe.some_characters = "JSON THIS! \"\1";
+ ooe.zomg_unicode = "\xd7\n\a\t";
ooe.base64 = "\1\2\3\255";
Nesting n;
@@ -33,12 +33,12 @@
n.my_ooe.integer16 = 16;
n.my_ooe.integer32 = 32;
n.my_ooe.integer64 = 64;
- n.my_ooe.double_precision = (std::sqrt(5.0) + 1) / 2;
- n.my_ooe.some_characters = ":R (me going \"rrrr\")";
+ n.my_ooe.double_precision = (std::sqrt(5.0)+1)/2;
+ n.my_ooe.some_characters = ":R (me going \"rrrr\")";
n.my_ooe.zomg_unicode = "\xd3\x80\xe2\x85\xae\xce\x9d\x20"
"\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"
"\x20\xce\x91\x74\x74\xce\xb1\xe2\x85\xbd\xce\xba\xc7\x83\xe2\x80\xbc";
- n.my_bonk.type = 31337;
+ n.my_bonk.type = 31337;
n.my_bonk.message = "I am a bonk... xor!";
HolyMoley hm;
@@ -62,21 +62,21 @@
std::vector<Bonk> stage2;
hm.bonks["nothing"] = stage2;
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 1;
stage2.back().message = "Wait.";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 2;
stage2.back().message = "What?";
hm.bonks["something"] = stage2;
stage2.clear();
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 3;
stage2.back().message = "quoth";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 4;
stage2.back().message = "the raven";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 5;
stage2.back().message = "nevermore";
hm.bonks["poe"] = stage2;
@@ -92,6 +92,7 @@
assert(ooe == ooe2);
+
cout << "Testing hm" << endl;
hm.write(proto.get());
diff --git a/lib/cpp/test/TFDTransportTest.cpp b/lib/cpp/test/TFDTransportTest.cpp
index 9d2bd90..7b962d8 100644
--- a/lib/cpp/test/TFDTransportTest.cpp
+++ b/lib/cpp/test/TFDTransportTest.cpp
@@ -25,10 +25,13 @@
using apache::thrift::transport::TTransportException;
using apache::thrift::transport::TFDTransport;
-class DummyException : std::exception {};
+class DummyException : std::exception {
+};
int main() {
- { TFDTransport t(256, TFDTransport::NO_CLOSE_ON_DESTROY); }
+ {
+ TFDTransport t(256, TFDTransport::NO_CLOSE_ON_DESTROY);
+ }
try {
{
@@ -53,4 +56,5 @@
}
return 0;
+
}
diff --git a/lib/cpp/test/TFileTransportTest.cpp b/lib/cpp/test/TFileTransportTest.cpp
old mode 100644
new mode 100755
index 294c9a6..67e05e3
--- a/lib/cpp/test/TFileTransportTest.cpp
+++ b/lib/cpp/test/TFileTransportTest.cpp
@@ -41,6 +41,7 @@
class FsyncLog;
FsyncLog* fsync_log;
+
/**************************************************************************
* Helper code
**************************************************************************/
@@ -48,11 +49,11 @@
// Provide BOOST_WARN_LT() and BOOST_WARN_GT(), in case we're compiled
// with an older version of boost
#ifndef BOOST_WARN_LT
-#define BOOST_WARN_CMP(a, b, op, check_fn) \
- check_fn((a)op(b), \
- "check " BOOST_STRINGIZE(a) " " BOOST_STRINGIZE(op) " " BOOST_STRINGIZE( \
- b) " failed: " BOOST_STRINGIZE(a) "=" \
- << (a) << " " BOOST_STRINGIZE(b) "=" << (b))
+#define BOOST_WARN_CMP(a, b, op, check_fn) \
+ check_fn((a) op (b), \
+ "check " BOOST_STRINGIZE(a) " " BOOST_STRINGIZE(op) " " \
+ BOOST_STRINGIZE(b) " failed: " BOOST_STRINGIZE(a) "=" << (a) << \
+ " " BOOST_STRINGIZE(b) "=" << (b))
#define BOOST_WARN_LT(a, b) BOOST_WARN_CMP(a, b, <, BOOST_WARN_MESSAGE)
#define BOOST_WARN_GT(a, b) BOOST_WARN_CMP(a, b, >, BOOST_WARN_MESSAGE)
@@ -63,7 +64,7 @@
* Class to record calls to fsync
*/
class FsyncLog {
-public:
+ public:
struct FsyncCall {
struct timeval time;
int fd;
@@ -73,15 +74,17 @@
FsyncLog() {}
void fsync(int fd) {
- (void)fd;
+ (void) fd;
FsyncCall call;
gettimeofday(&call.time, NULL);
calls_.push_back(call);
}
- const CallList* getCalls() const { return &calls_; }
+ const CallList* getCalls() const {
+ return &calls_;
+ }
-private:
+ private:
CallList calls_;
};
@@ -89,7 +92,7 @@
* Helper class to clean up temporary files
*/
class TempFile {
-public:
+ public:
TempFile(const char* directory, const char* prefix) {
size_t path_len = strlen(directory) + strlen(prefix) + 8;
path_ = new char[path_len];
@@ -106,9 +109,13 @@
close();
}
- const char* getPath() const { return path_; }
+ const char* getPath() const {
+ return path_;
+ }
- int getFD() const { return fd_; }
+ int getFD() const {
+ return fd_;
+ }
void unlink() {
if (path_) {
@@ -127,7 +134,7 @@
fd_ = -1;
}
-private:
+ private:
char* path_;
int fd_;
};
@@ -135,7 +142,8 @@
// Use our own version of fsync() for testing.
// This returns immediately, so timing in test_destructor() isn't affected by
// waiting on the actual filesystem.
-extern "C" int fsync(int fd) {
+extern "C"
+int fsync(int fd) {
if (fsync_log) {
fsync_log->fsync(fd);
}
@@ -146,6 +154,7 @@
return (t2->tv_usec - t1->tv_usec) + (t2->tv_sec - t1->tv_sec) * 1000000;
}
+
/**************************************************************************
* Test cases
**************************************************************************/
@@ -212,7 +221,8 @@
/**
* Make sure setFlushMaxUs() is honored.
*/
-void test_flush_max_us_impl(uint32_t flush_us, uint32_t write_us, uint32_t test_us) {
+void test_flush_max_us_impl(uint32_t flush_us, uint32_t write_us,
+ uint32_t test_us) {
// TFileTransport only calls fsync() if data has been written,
// so make sure the write interval is smaller than the flush interval.
BOOST_WARN(write_us < flush_us);
@@ -267,10 +277,13 @@
const FsyncLog::CallList* calls = log.getCalls();
// We added 1 fsync call above.
// Make sure TFileTransport called fsync at least once
- BOOST_WARN_GE(calls->size(), static_cast<FsyncLog::CallList::size_type>(1));
+ BOOST_WARN_GE(calls->size(),
+ static_cast<FsyncLog::CallList::size_type>(1));
const struct timeval* prev_time = NULL;
- for (FsyncLog::CallList::const_iterator it = calls->begin(); it != calls->end(); ++it) {
+ for (FsyncLog::CallList::const_iterator it = calls->begin();
+ it != calls->end();
+ ++it) {
if (prev_time) {
int delta = time_diff(prev_time, &it->time);
BOOST_WARN_LT(delta, max_allowed_delta);
@@ -339,8 +352,11 @@
}
void parse_args(int argc, char* argv[]) {
- struct option long_opts[]
- = {{"help", false, NULL, 'h'}, {"tmp-dir", true, NULL, 't'}, {NULL, 0, NULL, 0}};
+ struct option long_opts[] = {
+ { "help", false, NULL, 'h' },
+ { "tmp-dir", true, NULL, 't' },
+ { NULL, 0, NULL, 0 }
+ };
while (true) {
optopt = 1;
@@ -350,25 +366,26 @@
}
switch (optchar) {
- case 't':
- tmp_dir = optarg;
- break;
- case 'h':
- print_usage(stdout, argv[0]);
- exit(0);
- case '?':
- exit(1);
- default:
- // Only happens if someone adds another option to the optarg string,
- // but doesn't update the switch statement to handle it.
- fprintf(stderr, "unknown option \"-%c\"\n", optchar);
- exit(1);
+ case 't':
+ tmp_dir = optarg;
+ break;
+ case 'h':
+ print_usage(stdout, argv[0]);
+ exit(0);
+ case '?':
+ exit(1);
+ default:
+ // Only happens if someone adds another option to the optarg string,
+ // but doesn't update the switch statement to handle it.
+ fprintf(stderr, "unknown option \"-%c\"\n", optchar);
+ exit(1);
}
}
}
boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
- boost::unit_test::framework::master_test_suite().p_name.value = "TFileTransportTest";
+ boost::unit_test::framework::master_test_suite().p_name.value =
+ "TFileTransportTest";
// Parse arguments
parse_args(argc, argv);
diff --git a/lib/cpp/test/TMemoryBufferTest.cpp b/lib/cpp/test/TMemoryBufferTest.cpp
index cf49477..b81a667 100644
--- a/lib/cpp/test/TMemoryBufferTest.cpp
+++ b/lib/cpp/test/TMemoryBufferTest.cpp
@@ -25,84 +25,84 @@
#include <thrift/protocol/TBinaryProtocol.h>
#include "gen-cpp/ThriftTest_types.h"
-BOOST_AUTO_TEST_SUITE(TMemoryBufferTest)
+BOOST_AUTO_TEST_SUITE( TMemoryBufferTest )
-BOOST_AUTO_TEST_CASE(test_roundtrip) {
- using apache::thrift::transport::TMemoryBuffer;
- using apache::thrift::protocol::TBinaryProtocol;
- using boost::shared_ptr;
+BOOST_AUTO_TEST_CASE( test_roundtrip ) {
+ using apache::thrift::transport::TMemoryBuffer;
+ using apache::thrift::protocol::TBinaryProtocol;
+ using boost::shared_ptr;
- shared_ptr<TMemoryBuffer> strBuffer(new TMemoryBuffer());
- shared_ptr<TBinaryProtocol> binaryProtcol(new TBinaryProtocol(strBuffer));
+ shared_ptr<TMemoryBuffer> strBuffer(new TMemoryBuffer());
+ shared_ptr<TBinaryProtocol> binaryProtcol(new TBinaryProtocol(strBuffer));
- thrift::test::Xtruct a;
- a.i32_thing = 10;
- a.i64_thing = 30;
- a.string_thing = "holla back a";
+ thrift::test::Xtruct a;
+ a.i32_thing = 10;
+ a.i64_thing = 30;
+ a.string_thing ="holla back a";
- a.write(binaryProtcol.get());
- std::string serialized = strBuffer->getBufferAsString();
+ a.write(binaryProtcol.get());
+ std::string serialized = strBuffer->getBufferAsString();
- shared_ptr<TMemoryBuffer> strBuffer2(new TMemoryBuffer());
- shared_ptr<TBinaryProtocol> binaryProtcol2(new TBinaryProtocol(strBuffer2));
+ shared_ptr<TMemoryBuffer> strBuffer2(new TMemoryBuffer());
+ shared_ptr<TBinaryProtocol> binaryProtcol2(new TBinaryProtocol(strBuffer2));
- strBuffer2->resetBuffer((uint8_t*)serialized.data(), static_cast<uint32_t>(serialized.length()));
- thrift::test::Xtruct a2;
- a2.read(binaryProtcol2.get());
+ strBuffer2->resetBuffer((uint8_t*)serialized.data(), static_cast<uint32_t>(serialized.length()));
+ thrift::test::Xtruct a2;
+ a2.read(binaryProtcol2.get());
- assert(a == a2);
-}
-
-BOOST_AUTO_TEST_CASE(test_copy) {
- using apache::thrift::transport::TMemoryBuffer;
- using std::string;
- using std::cout;
- using std::endl;
-
- string* str1 = new string("abcd1234");
- const char* data1 = str1->data();
- TMemoryBuffer buf((uint8_t*)str1->data(),
- static_cast<uint32_t>(str1->length()),
- TMemoryBuffer::COPY);
- delete str1;
- string* str2 = new string("plsreuse");
- bool obj_reuse = (str1 == str2);
- bool dat_reuse = (data1 == str2->data());
- cout << "Object reuse: " << obj_reuse << " Data reuse: " << dat_reuse
- << ((obj_reuse && dat_reuse) ? " YAY!" : "") << endl;
- delete str2;
-
- string str3 = "wxyz", str4 = "6789";
- buf.readAppendToString(str3, 4);
- buf.readAppendToString(str4, INT_MAX);
-
- assert(str3 == "wxyzabcd");
- assert(str4 == "67891234");
-}
-
-BOOST_AUTO_TEST_CASE(test_exceptions) {
- using apache::thrift::transport::TTransportException;
- using apache::thrift::transport::TMemoryBuffer;
- using std::string;
-
- char data[] = "foo\0bar";
-
- TMemoryBuffer buf1((uint8_t*)data, 7, TMemoryBuffer::OBSERVE);
- string str = buf1.getBufferAsString();
- assert(str.length() == 7);
- buf1.resetBuffer();
- try {
- buf1.write((const uint8_t*)"foo", 3);
- assert(false);
- } catch (TTransportException&) {
+ assert(a == a2);
}
- TMemoryBuffer buf2((uint8_t*)data, 7, TMemoryBuffer::COPY);
- try {
- buf2.write((const uint8_t*)"bar", 3);
- } catch (TTransportException&) {
- assert(false);
+BOOST_AUTO_TEST_CASE( test_copy )
+ {
+ using apache::thrift::transport::TMemoryBuffer;
+ using std::string;
+ using std::cout;
+ using std::endl;
+
+ string* str1 = new string("abcd1234");
+ const char* data1 = str1->data();
+ TMemoryBuffer buf((uint8_t*)str1->data(), static_cast<uint32_t>(str1->length()), TMemoryBuffer::COPY);
+ delete str1;
+ string* str2 = new string("plsreuse");
+ bool obj_reuse = (str1 == str2);
+ bool dat_reuse = (data1 == str2->data());
+ cout << "Object reuse: " << obj_reuse << " Data reuse: " << dat_reuse
+ << ((obj_reuse && dat_reuse) ? " YAY!" : "") << endl;
+ delete str2;
+
+ string str3 = "wxyz", str4 = "6789";
+ buf.readAppendToString(str3, 4);
+ buf.readAppendToString(str4, INT_MAX);
+
+ assert(str3 == "wxyzabcd");
+ assert(str4 == "67891234");
}
-}
+
+BOOST_AUTO_TEST_CASE( test_exceptions )
+ {
+ using apache::thrift::transport::TTransportException;
+ using apache::thrift::transport::TMemoryBuffer;
+ using std::string;
+
+ char data[] = "foo\0bar";
+
+ TMemoryBuffer buf1((uint8_t*)data, 7, TMemoryBuffer::OBSERVE);
+ string str = buf1.getBufferAsString();
+ assert(str.length() == 7);
+ buf1.resetBuffer();
+ try {
+ buf1.write((const uint8_t*)"foo", 3);
+ assert(false);
+ } catch (TTransportException&) {}
+
+ TMemoryBuffer buf2((uint8_t*)data, 7, TMemoryBuffer::COPY);
+ try {
+ buf2.write((const uint8_t*)"bar", 3);
+ } catch (TTransportException&) {
+ assert(false);
+ }
+ }
BOOST_AUTO_TEST_SUITE_END()
+
diff --git a/lib/cpp/test/TPipedTransportTest.cpp b/lib/cpp/test/TPipedTransportTest.cpp
index 53a6fb5..7762f05 100644
--- a/lib/cpp/test/TPipedTransportTest.cpp
+++ b/lib/cpp/test/TPipedTransportTest.cpp
@@ -36,17 +36,18 @@
underlying->write((uint8_t*)"abcd", 4);
trans->readAll(buffer, 2);
- assert(string((char*)buffer, 2) == "ab");
+ assert( string((char*)buffer, 2) == "ab" );
trans->readEnd();
- assert(pipe->getBufferAsString() == "ab");
+ assert( pipe->getBufferAsString() == "ab" );
pipe->resetBuffer();
underlying->write((uint8_t*)"ef", 2);
trans->readAll(buffer, 2);
- assert(string((char*)buffer, 2) == "cd");
+ assert( string((char*)buffer, 2) == "cd" );
trans->readAll(buffer, 2);
- assert(string((char*)buffer, 2) == "ef");
+ assert( string((char*)buffer, 2) == "ef" );
trans->readEnd();
- assert(pipe->getBufferAsString() == "cdef");
+ assert( pipe->getBufferAsString() == "cdef" );
return 0;
+
}
diff --git a/lib/cpp/test/ThriftTest_extras.cpp b/lib/cpp/test/ThriftTest_extras.cpp
index af5606e..33f681f 100644
--- a/lib/cpp/test/ThriftTest_extras.cpp
+++ b/lib/cpp/test/ThriftTest_extras.cpp
@@ -22,12 +22,12 @@
#include <thrift/protocol/TDebugProtocol.h>
#include "gen-cpp/ThriftTest_types.h"
-namespace thrift {
-namespace test {
+
+namespace thrift { namespace test {
bool Insanity::operator<(thrift::test::Insanity const& other) const {
using apache::thrift::ThriftDebugString;
return ThriftDebugString(*this) < ThriftDebugString(other);
}
-}
-}
+
+}}
diff --git a/lib/cpp/test/ToStringTest.cpp b/lib/cpp/test/ToStringTest.cpp
index d204cb3..1a89c11 100644
--- a/lib/cpp/test/ToStringTest.cpp
+++ b/lib/cpp/test/ToStringTest.cpp
@@ -30,9 +30,9 @@
using apache::thrift::to_string;
-BOOST_AUTO_TEST_SUITE(ToStringTest)
+BOOST_AUTO_TEST_SUITE( ToStringTest )
-BOOST_AUTO_TEST_CASE(base_types_to_string) {
+BOOST_AUTO_TEST_CASE( base_types_to_string ) {
BOOST_CHECK_EQUAL(to_string(10), "10");
BOOST_CHECK_EQUAL(to_string(true), "1");
BOOST_CHECK_EQUAL(to_string('a'), "a");
@@ -40,91 +40,91 @@
BOOST_CHECK_EQUAL(to_string("abc"), "abc");
}
-BOOST_AUTO_TEST_CASE(empty_vector_to_string) {
+BOOST_AUTO_TEST_CASE( empty_vector_to_string ) {
std::vector<int> l;
BOOST_CHECK_EQUAL(to_string(l), "[]");
}
-BOOST_AUTO_TEST_CASE(single_item_vector_to_string) {
+BOOST_AUTO_TEST_CASE( single_item_vector_to_string ) {
std::vector<int> l;
l.push_back(100);
BOOST_CHECK_EQUAL(to_string(l), "[100]");
}
-BOOST_AUTO_TEST_CASE(multiple_item_vector_to_string) {
+BOOST_AUTO_TEST_CASE( multiple_item_vector_to_string ) {
std::vector<int> l;
l.push_back(100);
l.push_back(150);
BOOST_CHECK_EQUAL(to_string(l), "[100, 150]");
}
-BOOST_AUTO_TEST_CASE(empty_map_to_string) {
+BOOST_AUTO_TEST_CASE( empty_map_to_string ) {
std::map<int, std::string> m;
BOOST_CHECK_EQUAL(to_string(m), "{}");
}
-BOOST_AUTO_TEST_CASE(single_item_map_to_string) {
+BOOST_AUTO_TEST_CASE( single_item_map_to_string ) {
std::map<int, std::string> m;
m[12] = "abc";
BOOST_CHECK_EQUAL(to_string(m), "{12: abc}");
}
-BOOST_AUTO_TEST_CASE(multi_item_map_to_string) {
+BOOST_AUTO_TEST_CASE( multi_item_map_to_string ) {
std::map<int, std::string> m;
m[12] = "abc";
m[31] = "xyz";
BOOST_CHECK_EQUAL(to_string(m), "{12: abc, 31: xyz}");
}
-BOOST_AUTO_TEST_CASE(empty_set_to_string) {
+BOOST_AUTO_TEST_CASE( empty_set_to_string ) {
std::set<char> s;
BOOST_CHECK_EQUAL(to_string(s), "{}");
}
-BOOST_AUTO_TEST_CASE(single_item_set_to_string) {
+BOOST_AUTO_TEST_CASE( single_item_set_to_string ) {
std::set<char> s;
s.insert('c');
BOOST_CHECK_EQUAL(to_string(s), "{c}");
}
-BOOST_AUTO_TEST_CASE(multi_item_set_to_string) {
+BOOST_AUTO_TEST_CASE( multi_item_set_to_string ) {
std::set<char> s;
s.insert('a');
s.insert('z');
BOOST_CHECK_EQUAL(to_string(s), "{a, z}");
}
-BOOST_AUTO_TEST_CASE(generated_empty_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_empty_object_to_string ) {
thrift::test::EmptyStruct e;
BOOST_CHECK_EQUAL(to_string(e), "EmptyStruct()");
}
-BOOST_AUTO_TEST_CASE(generated_single_basic_field_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_single_basic_field_object_to_string ) {
thrift::test::StructA a;
a.__set_s("abcd");
BOOST_CHECK_EQUAL(to_string(a), "StructA(s=abcd)");
}
-BOOST_AUTO_TEST_CASE(generated_two_basic_fields_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_two_basic_fields_object_to_string ) {
thrift::test::Bonk a;
a.__set_message("abcd");
a.__set_type(1234);
BOOST_CHECK_EQUAL(to_string(a), "Bonk(message=abcd, type=1234)");
}
-BOOST_AUTO_TEST_CASE(generated_optional_fields_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_optional_fields_object_to_string ) {
thrift::test::Tricky2 a;
BOOST_CHECK_EQUAL(to_string(a), "Tricky2(im_optional=<null>)");
a.__set_im_optional(123);
BOOST_CHECK_EQUAL(to_string(a), "Tricky2(im_optional=123)");
}
-BOOST_AUTO_TEST_CASE(generated_nested_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_nested_object_to_string ) {
thrift::test::OneField a;
BOOST_CHECK_EQUAL(to_string(a), "OneField(field=EmptyStruct())");
}
-BOOST_AUTO_TEST_CASE(generated_nested_list_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_nested_list_object_to_string ) {
thrift::test::ListBonks l;
l.bonk.assign(2, thrift::test::Bonk());
l.bonk[0].__set_message("a");
diff --git a/lib/cpp/test/TransportTest.cpp b/lib/cpp/test/TransportTest.cpp
old mode 100644
new mode 100755
index 0305732..c1cb976
--- a/lib/cpp/test/TransportTest.cpp
+++ b/lib/cpp/test/TransportTest.cpp
@@ -36,9 +36,10 @@
#include <thrift/concurrency/FunctionRunner.h>
#if _WIN32
-#include <thrift/windows/TWinsockSingleton.h>
+ #include <thrift/windows/TWinsockSingleton.h>
#endif
+
using namespace apache::thrift::transport;
static boost::mt19937 rng;
@@ -48,14 +49,14 @@
}
class SizeGenerator {
-public:
+ public:
virtual ~SizeGenerator() {}
virtual uint32_t nextSize() = 0;
virtual std::string describe() const = 0;
};
class ConstantSizeGenerator : public SizeGenerator {
-public:
+ public:
ConstantSizeGenerator(uint32_t value) : value_(value) {}
uint32_t nextSize() { return value_; }
std::string describe() const {
@@ -64,14 +65,14 @@
return desc.str();
}
-private:
+ private:
uint32_t value_;
};
class RandomSizeGenerator : public SizeGenerator {
-public:
- RandomSizeGenerator(uint32_t min, uint32_t max)
- : generator_(rng, boost::uniform_int<int>(min, max)) {}
+ public:
+ RandomSizeGenerator(uint32_t min, uint32_t max) :
+ generator_(rng, boost::uniform_int<int>(min, max)) {}
uint32_t nextSize() { return generator_(); }
@@ -84,8 +85,9 @@
uint32_t getMin() const { return (generator_.distribution().min)(); }
uint32_t getMax() const { return (generator_.distribution().max)(); }
-private:
- boost::variate_generator<boost::mt19937&, boost::uniform_int<int> > generator_;
+ private:
+ boost::variate_generator< boost::mt19937&, boost::uniform_int<int> >
+ generator_;
};
/**
@@ -96,15 +98,16 @@
* to make a copy of the generator to bind it to the test function.)
*/
class GenericSizeGenerator : public SizeGenerator {
-public:
- GenericSizeGenerator(uint32_t value) : generator_(new ConstantSizeGenerator(value)) {}
- GenericSizeGenerator(uint32_t min, uint32_t max)
- : generator_(new RandomSizeGenerator(min, max)) {}
+ public:
+ GenericSizeGenerator(uint32_t value) :
+ generator_(new ConstantSizeGenerator(value)) {}
+ GenericSizeGenerator(uint32_t min, uint32_t max) :
+ generator_(new RandomSizeGenerator(min, max)) {}
uint32_t nextSize() { return generator_->nextSize(); }
std::string describe() const { return generator_->describe(); }
-private:
+ private:
boost::shared_ptr<SizeGenerator> generator_;
};
@@ -122,7 +125,7 @@
*/
template <class Transport_>
class CoupledTransports {
-public:
+ public:
virtual ~CoupledTransports() {}
typedef Transport_ TransportType;
@@ -131,17 +134,18 @@
boost::shared_ptr<Transport_> in;
boost::shared_ptr<Transport_> out;
-private:
+ private:
CoupledTransports(const CoupledTransports&);
- CoupledTransports& operator=(const CoupledTransports&);
+ CoupledTransports &operator=(const CoupledTransports&);
};
/**
* Coupled TMemoryBuffers
*/
class CoupledMemoryBuffers : public CoupledTransports<TMemoryBuffer> {
-public:
- CoupledMemoryBuffers() : buf(new TMemoryBuffer) {
+ public:
+ CoupledMemoryBuffers() :
+ buf(new TMemoryBuffer) {
in = buf;
out = buf;
}
@@ -155,7 +159,7 @@
*/
template <class WrapperTransport_, class InnerCoupledTransports_>
class CoupledWrapperTransportsT : public CoupledTransports<WrapperTransport_> {
-public:
+ public:
CoupledWrapperTransportsT() {
if (inner_.in) {
this->in.reset(new WrapperTransport_(inner_.in));
@@ -172,27 +176,34 @@
* Coupled TBufferedTransports.
*/
template <class InnerTransport_>
-class CoupledBufferedTransportsT
- : public CoupledWrapperTransportsT<TBufferedTransport, InnerTransport_> {};
+class CoupledBufferedTransportsT :
+ public CoupledWrapperTransportsT<TBufferedTransport, InnerTransport_> {
+};
-typedef CoupledBufferedTransportsT<CoupledMemoryBuffers> CoupledBufferedTransports;
+typedef CoupledBufferedTransportsT<CoupledMemoryBuffers>
+ CoupledBufferedTransports;
/**
* Coupled TFramedTransports.
*/
template <class InnerTransport_>
-class CoupledFramedTransportsT
- : public CoupledWrapperTransportsT<TFramedTransport, InnerTransport_> {};
+class CoupledFramedTransportsT :
+ public CoupledWrapperTransportsT<TFramedTransport, InnerTransport_> {
+};
-typedef CoupledFramedTransportsT<CoupledMemoryBuffers> CoupledFramedTransports;
+typedef CoupledFramedTransportsT<CoupledMemoryBuffers>
+ CoupledFramedTransports;
/**
* Coupled TZlibTransports.
*/
template <class InnerTransport_>
-class CoupledZlibTransportsT : public CoupledWrapperTransportsT<TZlibTransport, InnerTransport_> {};
+class CoupledZlibTransportsT :
+ public CoupledWrapperTransportsT<TZlibTransport, InnerTransport_> {
+};
-typedef CoupledZlibTransportsT<CoupledMemoryBuffers> CoupledZlibTransports;
+typedef CoupledZlibTransportsT<CoupledMemoryBuffers>
+ CoupledZlibTransports;
#ifndef _WIN32
// FD transport doesn't make much sense on Windows.
@@ -200,7 +211,7 @@
* Coupled TFDTransports.
*/
class CoupledFDTransports : public CoupledTransports<TFDTransport> {
-public:
+ public:
CoupledFDTransports() {
int pipes[2];
@@ -218,7 +229,7 @@
* Coupled TSockets
*/
class CoupledSocketTransports : public CoupledTransports<TSocket> {
-public:
+ public:
CoupledSocketTransports() {
THRIFT_SOCKET sockets[2] = {0};
if (THRIFT_SOCKETPAIR(PF_UNIX, SOCK_STREAM, 0, sockets) != 0) {
@@ -231,34 +242,39 @@
}
};
-// These could be made to work on Windows, but I don't care enough to make it happen
+//These could be made to work on Windows, but I don't care enough to make it happen
#ifndef _WIN32
/**
* Coupled TFileTransports
*/
class CoupledFileTransports : public CoupledTransports<TFileTransport> {
-public:
+ public:
CoupledFileTransports() {
#ifndef _WIN32
const char* tmp_dir = "/tmp";
-#define FILENAME_SUFFIX "/thrift.transport_test"
+ #define FILENAME_SUFFIX "/thrift.transport_test"
#else
const char* tmp_dir = getenv("TMP");
-#define FILENAME_SUFFIX "\\thrift.transport_test"
+ #define FILENAME_SUFFIX "\\thrift.transport_test"
#endif
// Create a temporary file to use
filename.resize(strlen(tmp_dir) + strlen(FILENAME_SUFFIX));
- THRIFT_SNPRINTF(&filename[0], filename.size(), "%s" FILENAME_SUFFIX, tmp_dir);
-#undef FILENAME_SUFFIX
+ THRIFT_SNPRINTF(&filename[0], filename.size(),
+ "%s" FILENAME_SUFFIX, tmp_dir);
+ #undef FILENAME_SUFFIX
- { std::ofstream dummy_creation(filename.c_str(), std::ofstream::trunc); }
+ {
+ std::ofstream dummy_creation(filename.c_str(), std::ofstream::trunc);
+ }
in.reset(new TFileTransport(filename, true));
out.reset(new TFileTransport(filename));
}
- ~CoupledFileTransports() { remove(filename.c_str()); }
+ ~CoupledFileTransports() {
+ remove(filename.c_str());
+ }
std::string filename;
};
@@ -274,7 +290,7 @@
*/
template <class CoupledTransports_>
class CoupledTTransports : public CoupledTransports<TTransport> {
-public:
+ public:
CoupledTTransports() : transports() {
in = transports.in;
out = transports.out;
@@ -292,7 +308,7 @@
*/
template <class CoupledTransports_>
class CoupledBufferBases : public CoupledTransports<TBufferBase> {
-public:
+ public:
CoupledBufferBases() : transports() {
in = transports.in;
out = transports.out;
@@ -316,8 +332,12 @@
**************************************************************************/
struct TriggerInfo {
- TriggerInfo(int seconds, const boost::shared_ptr<TTransport>& transport, uint32_t writeLength)
- : timeoutSeconds(seconds), transport(transport), writeLength(writeLength), next(NULL) {}
+ TriggerInfo(int seconds, const boost::shared_ptr<TTransport>& transport,
+ uint32_t writeLength) :
+ timeoutSeconds(seconds),
+ transport(transport),
+ writeLength(writeLength),
+ next(NULL) {}
int timeoutSeconds;
boost::shared_ptr<TTransport> transport;
@@ -331,7 +351,7 @@
bool g_teardown = false;
void alarm_handler() {
- TriggerInfo* info = NULL;
+ TriggerInfo *info = NULL;
{
apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
// The alarm timed out, which almost certainly means we're stuck
@@ -363,26 +383,26 @@
}
void alarm_handler_wrapper() {
- int64_t timeout = 0; // timeout of 0 means wait forever
- while (true) {
+ int64_t timeout = 0; //timeout of 0 means wait forever
+ while(true) {
bool fireHandler = false;
{
apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
- if (g_teardown)
- return;
- // calculate timeout
+ if(g_teardown)
+ return;
+ //calculate timeout
if (g_triggerInfo == NULL) {
timeout = 0;
} else {
- timeout = g_triggerInfo->timeoutSeconds * 1000;
+ timeout = g_triggerInfo->timeoutSeconds * 1000;
}
int waitResult = g_alarm_monitor.waitForTimeRelative(timeout);
- if (waitResult == THRIFT_ETIMEDOUT)
+ if(waitResult == THRIFT_ETIMEDOUT)
fireHandler = true;
}
- if (fireHandler)
- alarm_handler(); // calling outside the lock
+ if(fireHandler)
+ alarm_handler(); //calling outside the lock
}
}
@@ -395,7 +415,7 @@
* to the end.)
*/
void add_trigger(unsigned int seconds,
- const boost::shared_ptr<TTransport>& transport,
+ const boost::shared_ptr<TTransport> &transport,
uint32_t write_len) {
TriggerInfo* info = new TriggerInfo(seconds, transport, write_len);
{
@@ -417,7 +437,7 @@
}
void clear_triggers() {
- TriggerInfo* info = NULL;
+ TriggerInfo *info = NULL;
{
apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
@@ -435,7 +455,7 @@
}
void set_trigger(unsigned int seconds,
- const boost::shared_ptr<TTransport>& transport,
+ const boost::shared_ptr<TTransport> &transport,
uint32_t write_len) {
clear_triggers();
add_trigger(seconds, transport, write_len);
@@ -479,8 +499,10 @@
BOOST_REQUIRE(transports.in != NULL);
BOOST_REQUIRE(transports.out != NULL);
- boost::shared_array<uint8_t> wbuf = boost::shared_array<uint8_t>(new uint8_t[totalSize]);
- boost::shared_array<uint8_t> rbuf = boost::shared_array<uint8_t>(new uint8_t[totalSize]);
+ boost::shared_array<uint8_t> wbuf =
+ boost::shared_array<uint8_t>(new uint8_t[totalSize]);
+ boost::shared_array<uint8_t> rbuf =
+ boost::shared_array<uint8_t>(new uint8_t[totalSize]);
// store some data in wbuf
for (uint32_t n = 0; n < totalSize; ++n) {
@@ -500,7 +522,8 @@
// Make sure (total_written - total_read) + wchunk_size
// is less than maxOutstanding
- if (maxOutstanding > 0 && wchunk_size > maxOutstanding - (total_written - total_read)) {
+ if (maxOutstanding > 0 &&
+ wchunk_size > maxOutstanding - (total_written - total_read)) {
wchunk_size = maxOutstanding - (total_written - total_read);
}
@@ -514,7 +537,8 @@
try {
transports.out->write(wbuf.get() + total_written, write_size);
- } catch (TTransportException& te) {
+ }
+ catch (TTransportException & te) {
if (te.getType() == TTransportException::TIMED_OUT)
break;
throw te;
@@ -548,15 +572,17 @@
try {
bytes_read = transports.in->read(rbuf.get() + total_read, read_size);
} catch (TTransportException& e) {
- BOOST_FAIL("read(pos=" << total_read << ", size=" << read_size << ") threw exception \""
- << e.what() << "\"; written so far: " << total_written << " / "
- << totalSize << " bytes");
+ BOOST_FAIL("read(pos=" << total_read << ", size=" << read_size <<
+ ") threw exception \"" << e.what() <<
+ "\"; written so far: " << total_written << " / " <<
+ totalSize << " bytes");
}
BOOST_REQUIRE_MESSAGE(bytes_read > 0,
- "read(pos=" << total_read << ", size=" << read_size << ") returned "
- << bytes_read << "; written so far: " << total_written
- << " / " << totalSize << " bytes");
+ "read(pos=" << total_read << ", size=" <<
+ read_size << ") returned " << bytes_read <<
+ "; written so far: " << total_written << " / " <<
+ totalSize << " bytes");
chunk_read += bytes_read;
total_read += bytes_read;
}
@@ -566,6 +592,7 @@
BOOST_CHECK_EQUAL(memcmp(rbuf.get(), wbuf.get(), totalSize), 0);
}
+
template <class CoupledTransports>
void test_read_part_available() {
CoupledTransports transports;
@@ -582,8 +609,8 @@
transports.out->flush();
set_trigger(3, transports.out, 1);
uint32_t bytes_read = transports.in->read(read_buf, 10);
- BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int)0);
- BOOST_CHECK_EQUAL(bytes_read, (uint32_t)9);
+ BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
+ BOOST_CHECK_EQUAL(bytes_read, (uint32_t) 9);
clear_triggers();
}
@@ -649,7 +676,7 @@
// Now read 4 bytes, so that we are partway through the written data.
uint32_t bytes_read = transports.in->read(read_buf, 4);
- BOOST_CHECK_EQUAL(bytes_read, (uint32_t)4);
+ BOOST_CHECK_EQUAL(bytes_read, (uint32_t) 4);
// Now attempt to read 10 bytes. Only 9 more are available.
//
@@ -662,13 +689,13 @@
while (total_read < 9) {
set_trigger(3, transports.out, 1);
bytes_read = transports.in->read(read_buf, 10);
- BOOST_REQUIRE_EQUAL(g_numTriggersFired, (unsigned int)0);
- BOOST_REQUIRE_GT(bytes_read, (uint32_t)0);
+ BOOST_REQUIRE_EQUAL(g_numTriggersFired, (unsigned int) 0);
+ BOOST_REQUIRE_GT(bytes_read, (uint32_t) 0);
total_read += bytes_read;
- BOOST_REQUIRE_LE(total_read, (uint32_t)9);
+ BOOST_REQUIRE_LE(total_read, (uint32_t) 9);
}
- BOOST_CHECK_EQUAL(total_read, (uint32_t)9);
+ BOOST_CHECK_EQUAL(total_read, (uint32_t) 9);
clear_triggers();
}
@@ -690,7 +717,7 @@
set_trigger(3, transports.out, 1);
uint32_t borrow_len = 10;
const uint8_t* borrowed_buf = transports.in->borrow(read_buf, &borrow_len);
- BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int)0);
+ BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
BOOST_CHECK(borrowed_buf == NULL);
clear_triggers();
@@ -716,11 +743,11 @@
add_trigger(1, transports.out, 8);
uint32_t bytes_read = transports.in->read(read_buf, 10);
if (bytes_read == 0) {
- BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int)0);
+ BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
clear_triggers();
} else {
- BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int)1);
- BOOST_CHECK_EQUAL(bytes_read, (uint32_t)2);
+ BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 1);
+ BOOST_CHECK_EQUAL(bytes_read, (uint32_t) 2);
}
clear_triggers();
@@ -740,7 +767,7 @@
uint32_t borrow_len = 10;
const uint8_t* borrowed_buf = transports.in->borrow(NULL, &borrow_len);
BOOST_CHECK(borrowed_buf == NULL);
- BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int)0);
+ BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
clear_triggers();
}
@@ -761,40 +788,47 @@
* is compiler-dependent. gcc returns mangled names.)
**************************************************************************/
-#define ADD_TEST_RW(CoupledTransports, totalSize, ...) \
- addTestRW<CoupledTransports>(BOOST_STRINGIZE(CoupledTransports), totalSize, ##__VA_ARGS__);
+#define ADD_TEST_RW(CoupledTransports, totalSize, ...) \
+ addTestRW< CoupledTransports >(BOOST_STRINGIZE(CoupledTransports), \
+ totalSize, ## __VA_ARGS__);
-#define TEST_RW(CoupledTransports, totalSize, ...) \
- do { \
- /* Add the test as specified, to test the non-virtual function calls */ \
- ADD_TEST_RW(CoupledTransports, totalSize, ##__VA_ARGS__); \
- /* \
- * Also test using the transport as a TTransport*, to test \
- * the read_virt()/write_virt() calls \
- */ \
- ADD_TEST_RW(CoupledTTransports<CoupledTransports>, totalSize, ##__VA_ARGS__); \
- /* Test wrapping the transport with TBufferedTransport */ \
- ADD_TEST_RW(CoupledBufferedTransportsT<CoupledTransports>, totalSize, ##__VA_ARGS__); \
- /* Test wrapping the transport with TFramedTransports */ \
- ADD_TEST_RW(CoupledFramedTransportsT<CoupledTransports>, totalSize, ##__VA_ARGS__); \
- /* Test wrapping the transport with TZlibTransport */ \
- ADD_TEST_RW(CoupledZlibTransportsT<CoupledTransports>, totalSize, ##__VA_ARGS__); \
+#define TEST_RW(CoupledTransports, totalSize, ...) \
+ do { \
+ /* Add the test as specified, to test the non-virtual function calls */ \
+ ADD_TEST_RW(CoupledTransports, totalSize, ## __VA_ARGS__); \
+ /* \
+ * Also test using the transport as a TTransport*, to test \
+ * the read_virt()/write_virt() calls \
+ */ \
+ ADD_TEST_RW(CoupledTTransports<CoupledTransports>, \
+ totalSize, ## __VA_ARGS__); \
+ /* Test wrapping the transport with TBufferedTransport */ \
+ ADD_TEST_RW(CoupledBufferedTransportsT<CoupledTransports>, \
+ totalSize, ## __VA_ARGS__); \
+ /* Test wrapping the transport with TFramedTransports */ \
+ ADD_TEST_RW(CoupledFramedTransportsT<CoupledTransports>, \
+ totalSize, ## __VA_ARGS__); \
+ /* Test wrapping the transport with TZlibTransport */ \
+ ADD_TEST_RW(CoupledZlibTransportsT<CoupledTransports>, \
+ totalSize, ## __VA_ARGS__); \
} while (0)
-#define ADD_TEST_BLOCKING(CoupledTransports) \
- addTestBlocking<CoupledTransports>(BOOST_STRINGIZE(CoupledTransports));
+#define ADD_TEST_BLOCKING(CoupledTransports) \
+ addTestBlocking< CoupledTransports >(BOOST_STRINGIZE(CoupledTransports));
-#define TEST_BLOCKING_BEHAVIOR(CoupledTransports) \
- ADD_TEST_BLOCKING(CoupledTransports); \
- ADD_TEST_BLOCKING(CoupledTTransports<CoupledTransports>); \
- ADD_TEST_BLOCKING(CoupledBufferedTransportsT<CoupledTransports>); \
- ADD_TEST_BLOCKING(CoupledFramedTransportsT<CoupledTransports>); \
+#define TEST_BLOCKING_BEHAVIOR(CoupledTransports) \
+ ADD_TEST_BLOCKING(CoupledTransports); \
+ ADD_TEST_BLOCKING(CoupledTTransports<CoupledTransports>); \
+ ADD_TEST_BLOCKING(CoupledBufferedTransportsT<CoupledTransports>); \
+ ADD_TEST_BLOCKING(CoupledFramedTransportsT<CoupledTransports>); \
ADD_TEST_BLOCKING(CoupledZlibTransportsT<CoupledTransports>);
class TransportTestGen {
-public:
- TransportTestGen(boost::unit_test::test_suite* suite, float sizeMultiplier)
- : suite_(suite), sizeMultiplier_(sizeMultiplier) {}
+ public:
+ TransportTestGen(boost::unit_test::test_suite* suite,
+ float sizeMultiplier) :
+ suite_(suite),
+ sizeMultiplier_(sizeMultiplier) {}
void generate() {
GenericSizeGenerator rand4k(1, 4096);
@@ -805,15 +839,15 @@
*/
// TMemoryBuffer tests
- TEST_RW(CoupledMemoryBuffers, 1024 * 1024, 0, 0);
- TEST_RW(CoupledMemoryBuffers, 1024 * 256, rand4k, rand4k);
- TEST_RW(CoupledMemoryBuffers, 1024 * 256, 167, 163);
- TEST_RW(CoupledMemoryBuffers, 1024 * 16, 1, 1);
+ TEST_RW(CoupledMemoryBuffers, 1024*1024, 0, 0);
+ TEST_RW(CoupledMemoryBuffers, 1024*256, rand4k, rand4k);
+ TEST_RW(CoupledMemoryBuffers, 1024*256, 167, 163);
+ TEST_RW(CoupledMemoryBuffers, 1024*16, 1, 1);
- TEST_RW(CoupledMemoryBuffers, 1024 * 256, 0, 0, rand4k, rand4k);
- TEST_RW(CoupledMemoryBuffers, 1024 * 256, rand4k, rand4k, rand4k, rand4k);
- TEST_RW(CoupledMemoryBuffers, 1024 * 256, 167, 163, rand4k, rand4k);
- TEST_RW(CoupledMemoryBuffers, 1024 * 16, 1, 1, rand4k, rand4k);
+ TEST_RW(CoupledMemoryBuffers, 1024*256, 0, 0, rand4k, rand4k);
+ TEST_RW(CoupledMemoryBuffers, 1024*256, rand4k, rand4k, rand4k, rand4k);
+ TEST_RW(CoupledMemoryBuffers, 1024*256, 167, 163, rand4k, rand4k);
+ TEST_RW(CoupledMemoryBuffers, 1024*16, 1, 1, rand4k, rand4k);
TEST_BLOCKING_BEHAVIOR(CoupledMemoryBuffers);
@@ -822,57 +856,68 @@
// Since CoupledFDTransports tests with a pipe, writes will block
// if there is too much outstanding unread data in the pipe.
uint32_t fd_max_outstanding = 4096;
- TEST_RW(CoupledFDTransports, 1024 * 1024, 0, 0, 0, 0, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 256, rand4k, rand4k, 0, 0, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 256, 167, 163, 0, 0, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 16, 1, 1, 0, 0, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*1024, 0, 0,
+ 0, 0, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*256, rand4k, rand4k,
+ 0, 0, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*256, 167, 163,
+ 0, 0, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*16, 1, 1,
+ 0, 0, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 256, 0, 0, rand4k, rand4k, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 256, rand4k, rand4k, rand4k, rand4k, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 256, 167, 163, rand4k, rand4k, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 16, 1, 1, rand4k, rand4k, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*256, 0, 0,
+ rand4k, rand4k, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*256, rand4k, rand4k,
+ rand4k, rand4k, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*256, 167, 163,
+ rand4k, rand4k, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*16, 1, 1,
+ rand4k, rand4k, fd_max_outstanding);
TEST_BLOCKING_BEHAVIOR(CoupledFDTransports);
#endif //_WIN32
// TSocket tests
uint32_t socket_max_outstanding = 4096;
- TEST_RW(CoupledSocketTransports, 1024 * 1024, 0, 0, 0, 0, socket_max_outstanding);
- TEST_RW(CoupledSocketTransports, 1024 * 256, rand4k, rand4k, 0, 0, socket_max_outstanding);
- TEST_RW(CoupledSocketTransports, 1024 * 256, 167, 163, 0, 0, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*1024, 0, 0,
+ 0, 0, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*256, rand4k, rand4k,
+ 0, 0, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*256, 167, 163,
+ 0, 0, socket_max_outstanding);
// Doh. Apparently writing to a socket has some additional overhead for
// each send() call. If we have more than ~400 outstanding 1-byte write
// requests, additional send() calls start blocking.
- TEST_RW(CoupledSocketTransports, 1024 * 16, 1, 1, 0, 0, socket_max_outstanding);
- TEST_RW(CoupledSocketTransports, 1024 * 256, 0, 0, rand4k, rand4k, socket_max_outstanding);
- TEST_RW(CoupledSocketTransports,
- 1024 * 256,
- rand4k,
- rand4k,
- rand4k,
- rand4k,
- socket_max_outstanding);
- TEST_RW(CoupledSocketTransports, 1024 * 256, 167, 163, rand4k, rand4k, socket_max_outstanding);
- TEST_RW(CoupledSocketTransports, 1024 * 16, 1, 1, rand4k, rand4k, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*16, 1, 1,
+ 0, 0, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*256, 0, 0,
+ rand4k, rand4k, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*256, rand4k, rand4k,
+ rand4k, rand4k, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*256, 167, 163,
+ rand4k, rand4k, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*16, 1, 1,
+ rand4k, rand4k, socket_max_outstanding);
TEST_BLOCKING_BEHAVIOR(CoupledSocketTransports);
-// These could be made to work on Windows, but I don't care enough to make it happen
+//These could be made to work on Windows, but I don't care enough to make it happen
#ifndef _WIN32
// TFileTransport tests
// We use smaller buffer sizes here, since TFileTransport is fairly slow.
//
// TFileTransport can't write more than 16MB at once
- uint32_t max_write_at_once = 1024 * 1024 * 16 - 4;
- TEST_RW(CoupledFileTransports, 1024 * 1024, max_write_at_once, 0);
- TEST_RW(CoupledFileTransports, 1024 * 128, rand4k, rand4k);
- TEST_RW(CoupledFileTransports, 1024 * 128, 167, 163);
- TEST_RW(CoupledFileTransports, 1024 * 2, 1, 1);
+ uint32_t max_write_at_once = 1024*1024*16 - 4;
+ TEST_RW(CoupledFileTransports, 1024*1024, max_write_at_once, 0);
+ TEST_RW(CoupledFileTransports, 1024*128, rand4k, rand4k);
+ TEST_RW(CoupledFileTransports, 1024*128, 167, 163);
+ TEST_RW(CoupledFileTransports, 1024*2, 1, 1);
- TEST_RW(CoupledFileTransports, 1024 * 64, 0, 0, rand4k, rand4k);
- TEST_RW(CoupledFileTransports, 1024 * 64, rand4k, rand4k, rand4k, rand4k);
- TEST_RW(CoupledFileTransports, 1024 * 64, 167, 163, rand4k, rand4k);
- TEST_RW(CoupledFileTransports, 1024 * 2, 1, 1, rand4k, rand4k);
+ TEST_RW(CoupledFileTransports, 1024*64, 0, 0, rand4k, rand4k);
+ TEST_RW(CoupledFileTransports, 1024*64,
+ rand4k, rand4k, rand4k, rand4k);
+ TEST_RW(CoupledFileTransports, 1024*64, 167, 163, rand4k, rand4k);
+ TEST_RW(CoupledFileTransports, 1024*2, 1, 1, rand4k, rand4k);
TEST_BLOCKING_BEHAVIOR(CoupledFileTransports);
#endif
@@ -880,45 +925,23 @@
// Add some tests that access TBufferedTransport and TFramedTransport
// via TTransport pointers and TBufferBase pointers.
ADD_TEST_RW(CoupledTTransports<CoupledBufferedTransports>,
- 1024 * 1024,
- rand4k,
- rand4k,
- rand4k,
- rand4k);
+ 1024*1024, rand4k, rand4k, rand4k, rand4k);
ADD_TEST_RW(CoupledBufferBases<CoupledBufferedTransports>,
- 1024 * 1024,
- rand4k,
- rand4k,
- rand4k,
- rand4k);
+ 1024*1024, rand4k, rand4k, rand4k, rand4k);
ADD_TEST_RW(CoupledTTransports<CoupledFramedTransports>,
- 1024 * 1024,
- rand4k,
- rand4k,
- rand4k,
- rand4k);
+ 1024*1024, rand4k, rand4k, rand4k, rand4k);
ADD_TEST_RW(CoupledBufferBases<CoupledFramedTransports>,
- 1024 * 1024,
- rand4k,
- rand4k,
- rand4k,
- rand4k);
+ 1024*1024, rand4k, rand4k, rand4k, rand4k);
// Test using TZlibTransport via a TTransport pointer
ADD_TEST_RW(CoupledTTransports<CoupledZlibTransports>,
- 1024 * 1024,
- rand4k,
- rand4k,
- rand4k,
- rand4k);
+ 1024*1024, rand4k, rand4k, rand4k, rand4k);
}
-private:
+ private:
template <class CoupledTransports>
- void addTestRW(const char* transport_name,
- uint32_t totalSize,
- GenericSizeGenerator wSizeGen,
- GenericSizeGenerator rSizeGen,
+ void addTestRW(const char* transport_name, uint32_t totalSize,
+ GenericSizeGenerator wSizeGen, GenericSizeGenerator rSizeGen,
GenericSizeGenerator wChunkSizeGen = 0,
GenericSizeGenerator rChunkSizeGen = 0,
uint32_t maxOutstanding = 0,
@@ -927,50 +950,60 @@
totalSize = static_cast<uint32_t>(totalSize * sizeMultiplier_);
std::ostringstream name;
- name << transport_name << "::test_rw(" << totalSize << ", " << wSizeGen.describe() << ", "
- << rSizeGen.describe() << ", " << wChunkSizeGen.describe() << ", "
- << rChunkSizeGen.describe() << ", " << maxOutstanding << ")";
+ name << transport_name << "::test_rw(" << totalSize << ", " <<
+ wSizeGen.describe() << ", " << rSizeGen.describe() << ", " <<
+ wChunkSizeGen.describe() << ", " << rChunkSizeGen.describe() << ", " <<
+ maxOutstanding << ")";
- boost::unit_test::callback0<> test_func
- = apache::thrift::stdcxx::bind(test_rw<CoupledTransports>,
- totalSize,
- wSizeGen,
- rSizeGen,
- wChunkSizeGen,
- rChunkSizeGen,
- maxOutstanding);
- boost::unit_test::test_case* tc = boost::unit_test::make_test_case(test_func, name.str());
+ boost::unit_test::callback0<> test_func =
+ apache::thrift::stdcxx::bind(test_rw<CoupledTransports>, totalSize,
+ wSizeGen, rSizeGen, wChunkSizeGen, rChunkSizeGen,
+ maxOutstanding);
+ boost::unit_test::test_case* tc =
+ boost::unit_test::make_test_case(test_func, name.str());
suite_->add(tc, expectedFailures);
}
template <class CoupledTransports>
- void addTestBlocking(const char* transportName, uint32_t expectedFailures = 0) {
+ void addTestBlocking(const char* transportName,
+ uint32_t expectedFailures = 0) {
char name[1024];
boost::unit_test::test_case* tc;
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available()", transportName);
- tc = boost::unit_test::make_test_case(test_read_part_available<CoupledTransports>, name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_read_part_available<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available_in_chunks()", transportName);
- tc = boost::unit_test::make_test_case(test_read_part_available_in_chunks<CoupledTransports>,
- name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available_in_chunks()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_read_part_available_in_chunks<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_partial_midframe()", transportName);
- tc = boost::unit_test::make_test_case(test_read_partial_midframe<CoupledTransports>, name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_partial_midframe()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_read_partial_midframe<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_none_available()", transportName);
- tc = boost::unit_test::make_test_case(test_read_none_available<CoupledTransports>, name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_none_available()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_read_none_available<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_part_available()", transportName);
- tc = boost::unit_test::make_test_case(test_borrow_part_available<CoupledTransports>, name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_part_available()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_borrow_part_available<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_none_available()", transportName);
- tc = boost::unit_test::make_test_case(test_borrow_none_available<CoupledTransports>, name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_none_available()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_borrow_none_available<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
}
@@ -989,15 +1022,15 @@
struct global_fixture {
boost::shared_ptr<apache::thrift::concurrency::Thread> alarmThread_;
global_fixture() {
-#if _WIN32
+ #if _WIN32
apache::thrift::transport::TWinsockSingleton::create();
-#endif
+ #endif
apache::thrift::concurrency::PlatformThreadFactory factory;
factory.setDetached(false);
alarmThread_ = factory.newThread(
- apache::thrift::concurrency::FunctionRunner::create(alarm_handler_wrapper));
+ apache::thrift::concurrency::FunctionRunner::create(alarm_handler_wrapper));
alarmThread_->start();
}
~global_fixture() {
@@ -1021,7 +1054,8 @@
initrand(seed);
- boost::unit_test::test_suite* suite = &boost::unit_test::framework::master_test_suite();
+ boost::unit_test::test_suite* suite =
+ &boost::unit_test::framework::master_test_suite();
suite->p_name.value = "TransportTest";
TransportTestGen transport_test_generator(suite, 1);
transport_test_generator.generate();
diff --git a/lib/cpp/test/ZlibTest.cpp b/lib/cpp/test/ZlibTest.cpp
index 14b1a37..49c5514 100644
--- a/lib/cpp/test/ZlibTest.cpp
+++ b/lib/cpp/test/ZlibTest.cpp
@@ -48,24 +48,26 @@
*/
class SizeGenerator {
-public:
+ public:
virtual ~SizeGenerator() {}
virtual unsigned int getSize() = 0;
};
class ConstantSizeGenerator : public SizeGenerator {
-public:
+ public:
ConstantSizeGenerator(unsigned int value) : value_(value) {}
- virtual unsigned int getSize() { return value_; }
+ virtual unsigned int getSize() {
+ return value_;
+ }
-private:
+ private:
unsigned int value_;
};
class LogNormalSizeGenerator : public SizeGenerator {
-public:
- LogNormalSizeGenerator(double mean, double std_dev)
- : gen_(rng, boost::lognormal_distribution<double>(mean, std_dev)) {}
+ public:
+ LogNormalSizeGenerator(double mean, double std_dev) :
+ gen_(rng, boost::lognormal_distribution<double>(mean, std_dev)) {}
virtual unsigned int getSize() {
// Loop until we get a size of 1 or more
@@ -77,8 +79,8 @@
}
}
-private:
- boost::variate_generator<boost::mt19937, boost::lognormal_distribution<double> > gen_;
+ private:
+ boost::variate_generator< boost::mt19937, boost::lognormal_distribution<double> > gen_;
};
uint8_t* gen_uniform_buffer(uint32_t buf_len, uint8_t c) {
@@ -93,10 +95,10 @@
// Generate small runs of alternately increasing and decreasing bytes
boost::uniform_smallint<uint32_t> run_length_distribution(1, 64);
boost::uniform_smallint<uint8_t> byte_distribution(0, UINT8_MAX);
- boost::variate_generator<boost::mt19937, boost::uniform_smallint<uint8_t> >
- byte_generator(rng, byte_distribution);
- boost::variate_generator<boost::mt19937, boost::uniform_smallint<uint32_t> >
- run_len_generator(rng, run_length_distribution);
+ boost::variate_generator< boost::mt19937, boost::uniform_smallint<uint8_t> >
+ byte_generator(rng, byte_distribution);
+ boost::variate_generator< boost::mt19937, boost::uniform_smallint<uint32_t> >
+ run_len_generator(rng, run_length_distribution);
uint32_t idx = 0;
int8_t step = 1;
@@ -123,8 +125,8 @@
uint8_t* buf = new uint8_t[buf_len];
boost::uniform_smallint<uint8_t> distribution(0, UINT8_MAX);
- boost::variate_generator<boost::mt19937, boost::uniform_smallint<uint8_t> >
- generator(rng, distribution);
+ boost::variate_generator< boost::mt19937, boost::uniform_smallint<uint8_t> >
+ generator(rng, distribution);
for (uint32_t n = 0; n < buf_len; ++n) {
buf[n] = generator();
@@ -165,7 +167,7 @@
membuf->appendBufferToString(tmp_buf);
zlib_trans.reset(new TZlibTransport(membuf,
TZlibTransport::DEFAULT_URBUF_SIZE,
- static_cast<uint32_t>(tmp_buf.length() - 1)));
+ static_cast<uint32_t>(tmp_buf.length()-1)));
boost::shared_array<uint8_t> mirror(new uint8_t[buf_len]);
uint32_t got = zlib_trans->readAll(mirror.get(), buf_len);
@@ -184,7 +186,8 @@
string tmp_buf;
membuf->appendBufferToString(tmp_buf);
tmp_buf.erase(tmp_buf.length() - 1);
- membuf->resetBuffer(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(tmp_buf.data())),
+ membuf->resetBuffer(const_cast<uint8_t*>(
+ reinterpret_cast<const uint8_t*>(tmp_buf.data())),
static_cast<uint32_t>(tmp_buf.length()));
boost::shared_array<uint8_t> mirror(new uint8_t[buf_len]);
@@ -199,8 +202,7 @@
}
}
-void test_read_write_mix(const uint8_t* buf,
- uint32_t buf_len,
+void test_read_write_mix(const uint8_t* buf, uint32_t buf_len,
const boost::shared_ptr<SizeGenerator>& write_gen,
const boost::shared_ptr<SizeGenerator>& read_gen) {
// Try it with a mix of read/write sizes.
@@ -230,7 +232,7 @@
}
uint32_t got = zlib_trans->read(mirror.get() + tot, read_len);
BOOST_REQUIRE_LE(got, expected_read_len);
- BOOST_REQUIRE_NE(got, (uint32_t)0);
+ BOOST_REQUIRE_NE(got, (uint32_t) 0);
tot += got;
}
@@ -262,7 +264,8 @@
// error when only modifying checksum bytes.
int index = static_cast<int>(tmp_buf.size() - 1);
tmp_buf[index]++;
- membuf->resetBuffer(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(tmp_buf.data())),
+ membuf->resetBuffer(const_cast<uint8_t*>(
+ reinterpret_cast<const uint8_t*>(tmp_buf.data())),
static_cast<uint32_t>(tmp_buf.length()));
boost::shared_array<uint8_t> mirror(new uint8_t[buf_len]);
@@ -320,22 +323,21 @@
TZlibTransport w_zlib_trans(membuf);
}
- BOOST_CHECK_EQUAL(membuf->available_read(), (uint32_t)0);
+ BOOST_CHECK_EQUAL(membuf->available_read(), (uint32_t) 0);
}
/*
* Initialization
*/
-#define ADD_TEST_CASE(suite, name, function, ...) \
- do { \
- ::std::ostringstream name_ss; \
- name_ss << name << "-" << BOOST_STRINGIZE(function); \
- ::boost::unit_test::test_case* tc \
- = ::boost::unit_test::make_test_case(::apache::thrift::stdcxx::bind(function, \
- ##__VA_ARGS__), \
- name_ss.str()); \
- (suite)->add(tc); \
+#define ADD_TEST_CASE(suite, name, function, ...) \
+ do { \
+ ::std::ostringstream name_ss; \
+ name_ss << name << "-" << BOOST_STRINGIZE(function); \
+ ::boost::unit_test::test_case* tc = ::boost::unit_test::make_test_case( \
+ ::apache::thrift::stdcxx::bind(function, ## __VA_ARGS__), \
+ name_ss.str()); \
+ (suite)->add(tc); \
} while (0)
void add_tests(boost::unit_test::test_suite* suite,
@@ -348,30 +350,20 @@
ADD_TEST_CASE(suite, name, test_invalid_checksum, buf, buf_len);
ADD_TEST_CASE(suite, name, test_write_after_flush, buf, buf_len);
- boost::shared_ptr<SizeGenerator> size_32k(new ConstantSizeGenerator(1 << 15));
+ boost::shared_ptr<SizeGenerator> size_32k(new ConstantSizeGenerator(1<<15));
boost::shared_ptr<SizeGenerator> size_lognormal(new LogNormalSizeGenerator(20, 30));
- ADD_TEST_CASE(suite, name << "-constant", test_read_write_mix, buf, buf_len, size_32k, size_32k);
- ADD_TEST_CASE(suite,
- name << "-lognormal-write",
- test_read_write_mix,
- buf,
- buf_len,
- size_lognormal,
- size_32k);
- ADD_TEST_CASE(suite,
- name << "-lognormal-read",
- test_read_write_mix,
- buf,
- buf_len,
- size_32k,
- size_lognormal);
- ADD_TEST_CASE(suite,
- name << "-lognormal-both",
- test_read_write_mix,
- buf,
- buf_len,
- size_lognormal,
- size_lognormal);
+ ADD_TEST_CASE(suite, name << "-constant",
+ test_read_write_mix, buf, buf_len,
+ size_32k, size_32k);
+ ADD_TEST_CASE(suite, name << "-lognormal-write",
+ test_read_write_mix, buf, buf_len,
+ size_lognormal, size_32k);
+ ADD_TEST_CASE(suite, name << "-lognormal-read",
+ test_read_write_mix, buf, buf_len,
+ size_32k, size_lognormal);
+ ADD_TEST_CASE(suite, name << "-lognormal-both",
+ test_read_write_mix, buf, buf_len,
+ size_lognormal, size_lognormal);
// Test with a random size distribution,
// but use the exact same distribution for reading as for writing.
@@ -381,13 +373,9 @@
// both start with random number generators in the same state.
boost::shared_ptr<SizeGenerator> write_size_gen(new LogNormalSizeGenerator(20, 30));
boost::shared_ptr<SizeGenerator> read_size_gen(new LogNormalSizeGenerator(20, 30));
- ADD_TEST_CASE(suite,
- name << "-lognormal-same-distribution",
- test_read_write_mix,
- buf,
- buf_len,
- write_size_gen,
- read_size_gen);
+ ADD_TEST_CASE(suite, name << "-lognormal-same-distribution",
+ test_read_write_mix, buf, buf_len,
+ write_size_gen, read_size_gen);
}
void print_usage(FILE* f, const char* argv0) {
@@ -404,10 +392,11 @@
printf("seed: %" PRIu32 "\n", seed);
rng.seed(seed);
- boost::unit_test::test_suite* suite = &boost::unit_test::framework::master_test_suite();
+ boost::unit_test::test_suite* suite =
+ &boost::unit_test::framework::master_test_suite();
suite->p_name.value = "ZlibTest";
- uint32_t buf_len = 1024 * 32;
+ uint32_t buf_len = 1024*32;
add_tests(suite, gen_uniform_buffer(buf_len, 'a'), buf_len, "uniform");
add_tests(suite, gen_compressible_buffer(buf_len), buf_len, "compressible");
add_tests(suite, gen_random_buffer(buf_len), buf_len, "random");
diff --git a/lib/cpp/test/concurrency/Tests.cpp b/lib/cpp/test/concurrency/Tests.cpp
index 0d81d7e..c80bb88 100644
--- a/lib/cpp/test/concurrency/Tests.cpp
+++ b/lib/cpp/test/concurrency/Tests.cpp
@@ -29,7 +29,7 @@
std::string arg;
- std::vector<std::string> args(argc - 1 > 1 ? argc - 1 : 1);
+ std::vector<std::string> args(argc - 1 > 1 ? argc - 1 : 1);
args[0] = "all";
@@ -45,9 +45,9 @@
std::cout << "ThreadFactory tests..." << std::endl;
- size_t count = 1000;
- size_t floodLoops = 1;
- size_t floodCount = 100000;
+ size_t count = 1000;
+ size_t floodLoops = 1;
+ size_t floodCount = 100000;
std::cout << "\t\tThreadFactory reap N threads test: N = " << count << std::endl;
@@ -89,6 +89,7 @@
std::cout << "\t\t\tscall per ms: " << count / (time01 - time00) << std::endl;
}
+
if (runAll || args[0].compare("timer-manager") == 0) {
std::cout << "TimerManager tests..." << std::endl;
@@ -112,17 +113,16 @@
int64_t delay = 10LL;
- std::cout << "\t\tThreadManager load test: worker count: " << workerCount
- << " task count: " << taskCount << " delay: " << delay << std::endl;
+ std::cout << "\t\tThreadManager load test: worker count: " << workerCount << " task count: " << taskCount << " delay: " << delay << std::endl;
ThreadManagerTests threadManagerTests;
assert(threadManagerTests.loadTest(taskCount, delay, workerCount));
- std::cout << "\t\tThreadManager block test: worker count: " << workerCount
- << " delay: " << delay << std::endl;
+ std::cout << "\t\tThreadManager block test: worker count: " << workerCount << " delay: " << delay << std::endl;
assert(threadManagerTests.blockTest(delay, workerCount));
+
}
}
@@ -140,12 +140,11 @@
int64_t delay = 10LL;
- for (size_t workerCount = minWorkerCount; workerCount < maxWorkerCount; workerCount *= 2) {
+ for (size_t workerCount = minWorkerCount; workerCount < maxWorkerCount; workerCount*= 2) {
size_t taskCount = workerCount * tasksPerWorker;
- std::cout << "\t\tThreadManager load test: worker count: " << workerCount
- << " task count: " << taskCount << " delay: " << delay << std::endl;
+ std::cout << "\t\tThreadManager load test: worker count: " << workerCount << " task count: " << taskCount << " delay: " << delay << std::endl;
ThreadManagerTests threadManagerTests;
diff --git a/lib/cpp/test/concurrency/ThreadFactoryTests.h b/lib/cpp/test/concurrency/ThreadFactoryTests.h
old mode 100644
new mode 100755
index d7431a8..2d97337
--- a/lib/cpp/test/concurrency/ThreadFactoryTests.h
+++ b/lib/cpp/test/concurrency/ThreadFactoryTests.h
@@ -27,10 +27,7 @@
#include <iostream>
#include <set>
-namespace apache {
-namespace thrift {
-namespace concurrency {
-namespace test {
+namespace apache { namespace thrift { namespace concurrency { namespace test {
using boost::shared_ptr;
using namespace apache::thrift::concurrency;
@@ -43,14 +40,18 @@
class ThreadFactoryTests {
public:
+
static const double TEST_TOLERANCE;
- class Task : public Runnable {
+ class Task: public Runnable {
public:
+
Task() {}
- void run() { std::cout << "\t\t\tHello World" << std::endl; }
+ void run() {
+ std::cout << "\t\t\tHello World" << std::endl;
+ }
};
/**
@@ -76,17 +77,20 @@
/**
* Reap N threads
*/
- class ReapNTask : public Runnable {
+ class ReapNTask: public Runnable {
- public:
- ReapNTask(Monitor& monitor, int& activeCount) : _monitor(monitor), _count(activeCount) {}
+ public:
+
+ ReapNTask(Monitor& monitor, int& activeCount) :
+ _monitor(monitor),
+ _count(activeCount) {}
void run() {
Synchronized s(_monitor);
_count--;
- // std::cout << "\t\t\tthread count: " << _count << std::endl;
+ //std::cout << "\t\t\tthread count: " << _count << std::endl;
if (_count == 0) {
_monitor.notify();
@@ -98,15 +102,15 @@
int& _count;
};
- bool reapNThreads(int loop = 1, int count = 10) {
+ bool reapNThreads(int loop=1, int count=10) {
- PlatformThreadFactory threadFactory = PlatformThreadFactory();
+ PlatformThreadFactory threadFactory = PlatformThreadFactory();
Monitor* monitor = new Monitor();
- for (int lix = 0; lix < loop; lix++) {
+ for(int lix = 0; lix < loop; lix++) {
- int* activeCount = new int(count);
+ int* activeCount = new int(count);
std::set<shared_ptr<Thread> > threads;
@@ -114,25 +118,20 @@
for (tix = 0; tix < count; tix++) {
try {
- threads.insert(
- threadFactory.newThread(shared_ptr<Runnable>(new ReapNTask(*monitor, *activeCount))));
- } catch (SystemResourceException& e) {
- std::cout << "\t\t\tfailed to create " << lix* count + tix << " thread " << e.what()
- << std::endl;
+ threads.insert(threadFactory.newThread(shared_ptr<Runnable>(new ReapNTask(*monitor, *activeCount))));
+ } catch(SystemResourceException& e) {
+ std::cout << "\t\t\tfailed to create " << lix * count + tix << " thread " << e.what() << std::endl;
throw e;
}
}
tix = 0;
- for (std::set<shared_ptr<Thread> >::const_iterator thread = threads.begin();
- thread != threads.end();
- tix++, ++thread) {
+ for (std::set<shared_ptr<Thread> >::const_iterator thread = threads.begin(); thread != threads.end(); tix++, ++thread) {
try {
(*thread)->start();
- } catch (SystemResourceException& e) {
- std::cout << "\t\t\tfailed to start " << lix* count + tix << " thread " << e.what()
- << std::endl;
+ } catch(SystemResourceException& e) {
+ std::cout << "\t\t\tfailed to start " << lix * count + tix << " thread " << e.what() << std::endl;
throw e;
}
}
@@ -144,7 +143,7 @@
}
}
delete activeCount;
- std::cout << "\t\t\treaped " << lix* count << " threads" << std::endl;
+ std::cout << "\t\t\treaped " << lix * count << " threads" << std::endl;
}
std::cout << "\t\t\tSuccess!" << std::endl;
@@ -152,12 +151,21 @@
return true;
}
- class SynchStartTask : public Runnable {
+ class SynchStartTask: public Runnable {
- public:
- enum STATE { UNINITIALIZED, STARTING, STARTED, STOPPING, STOPPED };
+ public:
- SynchStartTask(Monitor& monitor, volatile STATE& state) : _monitor(monitor), _state(state) {}
+ enum STATE {
+ UNINITIALIZED,
+ STARTING,
+ STARTED,
+ STOPPING,
+ STOPPED
+ };
+
+ SynchStartTask(Monitor& monitor, volatile STATE& state) :
+ _monitor(monitor),
+ _state(state) {}
void run() {
{
@@ -181,9 +189,9 @@
}
}
- private:
+ private:
Monitor& _monitor;
- volatile STATE& _state;
+ volatile STATE& _state;
};
bool synchStartTest() {
@@ -192,10 +200,9 @@
SynchStartTask::STATE state = SynchStartTask::UNINITIALIZED;
- shared_ptr<SynchStartTask> task
- = shared_ptr<SynchStartTask>(new SynchStartTask(monitor, state));
+ shared_ptr<SynchStartTask> task = shared_ptr<SynchStartTask>(new SynchStartTask(monitor, state));
- PlatformThreadFactory threadFactory = PlatformThreadFactory();
+ PlatformThreadFactory threadFactory = PlatformThreadFactory();
shared_ptr<Thread> thread = threadFactory.newThread(task);
@@ -219,8 +226,8 @@
Synchronized s(monitor);
try {
- monitor.wait(100);
- } catch (TimedOutException& e) {
+ monitor.wait(100);
+ } catch(TimedOutException& e) {
}
if (state == SynchStartTask::STARTED) {
@@ -246,7 +253,7 @@
/** See how accurate monitor timeout is. */
- bool monitorTimeoutTest(size_t count = 1000, int64_t timeout = 10) {
+ bool monitorTimeoutTest(size_t count=1000, int64_t timeout=10) {
Monitor monitor;
@@ -256,8 +263,8 @@
{
Synchronized s(monitor);
try {
- monitor.wait(timeout);
- } catch (TimedOutException& e) {
+ monitor.wait(timeout);
+ } catch(TimedOutException& e) {
}
}
}
@@ -266,32 +273,31 @@
double error = ((endTime - startTime) - (count * timeout)) / (double)(count * timeout);
- if (error < 0.0) {
+ if (error < 0.0) {
error *= 1.0;
}
bool success = error < ThreadFactoryTests::TEST_TOLERANCE;
- std::cout << "\t\t\t" << (success ? "Success" : "Failure")
- << "! expected time: " << count * timeout
- << "ms elapsed time: " << endTime - startTime << "ms error%: " << error * 100.0
- << std::endl;
+ std::cout << "\t\t\t" << (success ? "Success" : "Failure") << "! expected time: " << count * timeout << "ms elapsed time: "<< endTime - startTime << "ms error%: " << error * 100.0 << std::endl;
return success;
}
+
class FloodTask : public Runnable {
public:
- FloodTask(const size_t id) : _id(id) {}
- ~FloodTask() {
- if (_id % 1000 == 0) {
+
+ FloodTask(const size_t id) :_id(id) {}
+ ~FloodTask(){
+ if(_id % 1000 == 0) {
std::cout << "\t\tthread " << _id << " done" << std::endl;
}
}
- void run() {
- if (_id % 1000 == 0) {
+ void run(){
+ if(_id % 1000 == 0) {
std::cout << "\t\tthread " << _id << " started" << std::endl;
}
@@ -300,41 +306,42 @@
const size_t _id;
};
- void foo(PlatformThreadFactory* tf) { (void)tf; }
+ void foo(PlatformThreadFactory *tf) {
+ (void) tf;
+ }
- bool floodNTest(size_t loop = 1, size_t count = 100000) {
+ bool floodNTest(size_t loop=1, size_t count=100000) {
bool success = false;
- for (size_t lix = 0; lix < loop; lix++) {
+ for(size_t lix = 0; lix < loop; lix++) {
PlatformThreadFactory threadFactory = PlatformThreadFactory();
threadFactory.setDetached(true);
- for (size_t tix = 0; tix < count; tix++) {
+ for(size_t tix = 0; tix < count; tix++) {
- try {
+ try {
- shared_ptr<FloodTask> task(new FloodTask(lix * count + tix));
+ shared_ptr<FloodTask> task(new FloodTask(lix * count + tix ));
- shared_ptr<Thread> thread = threadFactory.newThread(task);
+ shared_ptr<Thread> thread = threadFactory.newThread(task);
- thread->start();
+ thread->start();
- THRIFT_SLEEP_USEC(1);
+ THRIFT_SLEEP_USEC(1);
- } catch (TException& e) {
+ } catch (TException& e) {
- std::cout << "\t\t\tfailed to start " << lix* count + tix << " thread " << e.what()
- << std::endl;
+ std::cout << "\t\t\tfailed to start " << lix * count + tix << " thread " << e.what() << std::endl;
- return success;
+ return success;
+ }
}
- }
- std::cout << "\t\t\tflooded " << (lix + 1) * count << " threads" << std::endl;
+ std::cout << "\t\t\tflooded " << (lix + 1) * count << " threads" << std::endl;
- success = true;
+ success = true;
}
return success;
@@ -342,7 +349,5 @@
};
const double ThreadFactoryTests::TEST_TOLERANCE = .20;
-}
-}
-}
-} // apache::thrift::concurrency::test
+
+}}}} // apache::thrift::concurrency::test
diff --git a/lib/cpp/test/concurrency/ThreadManagerTests.h b/lib/cpp/test/concurrency/ThreadManagerTests.h
old mode 100644
new mode 100755
index 27bf6c5..c08448b
--- a/lib/cpp/test/concurrency/ThreadManagerTests.h
+++ b/lib/cpp/test/concurrency/ThreadManagerTests.h
@@ -29,10 +29,7 @@
#include <set>
#include <stdint.h>
-namespace apache {
-namespace thrift {
-namespace concurrency {
-namespace test {
+namespace apache { namespace thrift { namespace concurrency { namespace test {
using namespace apache::thrift::concurrency;
@@ -41,11 +38,15 @@
static const double TEST_TOLERANCE;
public:
- class Task : public Runnable {
+ class Task: public Runnable {
public:
- Task(Monitor& monitor, size_t& count, int64_t timeout)
- : _monitor(monitor), _count(count), _timeout(timeout), _done(false) {}
+
+ Task(Monitor& monitor, size_t& count, int64_t timeout) :
+ _monitor(monitor),
+ _count(count),
+ _timeout(timeout),
+ _done(false) {}
void run() {
@@ -56,9 +57,9 @@
try {
_sleep.wait(_timeout);
- } catch (TimedOutException& e) {
+ } catch(TimedOutException& e) {
;
- } catch (...) {
+ }catch(...) {
assert(0);
}
}
@@ -95,7 +96,7 @@
* completes. Verify that all tasks completed and that thread manager cleans
* up properly on delete.
*/
- bool loadTest(size_t count = 100, int64_t timeout = 100LL, size_t workerCount = 4) {
+ bool loadTest(size_t count=100, int64_t timeout=100LL, size_t workerCount=4) {
Monitor monitor;
@@ -103,8 +104,7 @@
shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(workerCount);
- shared_ptr<PlatformThreadFactory> threadFactory
- = shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
+ shared_ptr<PlatformThreadFactory> threadFactory = shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
#ifndef USE_BOOST_THREAD
threadFactory->setPriority(PosixThreadFactory::HIGHEST);
@@ -117,23 +117,20 @@
for (size_t ix = 0; ix < count; ix++) {
- tasks.insert(shared_ptr<ThreadManagerTests::Task>(
- new ThreadManagerTests::Task(monitor, activeCount, timeout)));
+ tasks.insert(shared_ptr<ThreadManagerTests::Task>(new ThreadManagerTests::Task(monitor, activeCount, timeout)));
}
int64_t time00 = Util::currentTime();
- for (std::set<shared_ptr<ThreadManagerTests::Task> >::iterator ix = tasks.begin();
- ix != tasks.end();
- ix++) {
+ for (std::set<shared_ptr<ThreadManagerTests::Task> >::iterator ix = tasks.begin(); ix != tasks.end(); ix++) {
- threadManager->add(*ix);
+ threadManager->add(*ix);
}
{
Synchronized s(monitor);
- while (activeCount > 0) {
+ while(activeCount > 0) {
monitor.wait();
}
@@ -148,9 +145,7 @@
int64_t minTime = 9223372036854775807LL;
int64_t maxTime = 0;
- for (std::set<shared_ptr<ThreadManagerTests::Task> >::iterator ix = tasks.begin();
- ix != tasks.end();
- ix++) {
+ for (std::set<shared_ptr<ThreadManagerTests::Task> >::iterator ix = tasks.begin(); ix != tasks.end(); ix++) {
shared_ptr<ThreadManagerTests::Task> task = *ix;
@@ -174,43 +169,43 @@
maxTime = delta;
}
- averageTime += delta;
+ averageTime+= delta;
}
averageTime /= count;
- std::cout << "\t\t\tfirst start: " << firstTime << "ms Last end: " << lastTime
- << "ms min: " << minTime << "ms max: " << maxTime << "ms average: " << averageTime
- << "ms" << std::endl;
+ std::cout << "\t\t\tfirst start: " << firstTime << "ms Last end: " << lastTime << "ms min: " << minTime << "ms max: " << maxTime << "ms average: " << averageTime << "ms" << std::endl;
double expectedTime = ((count + (workerCount - 1)) / workerCount) * timeout;
double error = ((time01 - time00) - expectedTime) / expectedTime;
if (error < 0) {
- error *= -1.0;
+ error*= -1.0;
}
bool success = error < TEST_TOLERANCE;
- std::cout << "\t\t\t" << (success ? "Success" : "Failure")
- << "! expected time: " << expectedTime << "ms elapsed time: " << time01 - time00
- << "ms error%: " << error * 100.0 << std::endl;
+ std::cout << "\t\t\t" << (success ? "Success" : "Failure") << "! expected time: " << expectedTime << "ms elapsed time: "<< time01 - time00 << "ms error%: " << error * 100.0 << std::endl;
return success;
}
- class BlockTask : public Runnable {
+ class BlockTask: public Runnable {
public:
- BlockTask(Monitor& monitor, Monitor& bmonitor, size_t& count)
- : _monitor(monitor), _bmonitor(bmonitor), _count(count) {}
+
+ BlockTask(Monitor& monitor, Monitor& bmonitor, size_t& count) :
+ _monitor(monitor),
+ _bmonitor(bmonitor),
+ _count(count) {}
void run() {
{
Synchronized s(_bmonitor);
_bmonitor.wait();
+
}
{
@@ -234,8 +229,8 @@
* Block test. Create pendingTaskCountMax tasks. Verify that we block adding the
* pendingTaskCountMax + 1th task. Verify that we unblock when a task completes */
- bool blockTest(int64_t timeout = 100LL, size_t workerCount = 2) {
- (void)timeout;
+ bool blockTest(int64_t timeout=100LL, size_t workerCount=2) {
+ (void) timeout;
bool success = false;
try {
@@ -247,11 +242,9 @@
size_t activeCounts[] = {workerCount, pendingTaskMaxCount, 1};
- shared_ptr<ThreadManager> threadManager
- = ThreadManager::newSimpleThreadManager(workerCount, pendingTaskMaxCount);
+ shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(workerCount, pendingTaskMaxCount);
- shared_ptr<PlatformThreadFactory> threadFactory
- = shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
+ shared_ptr<PlatformThreadFactory> threadFactory = shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
#ifndef USE_BOOST_THREAD
threadFactory->setPriority(PosixThreadFactory::HIGHEST);
@@ -264,49 +257,43 @@
for (size_t ix = 0; ix < workerCount; ix++) {
- tasks.insert(shared_ptr<ThreadManagerTests::BlockTask>(
- new ThreadManagerTests::BlockTask(monitor, bmonitor, activeCounts[0])));
+ tasks.insert(shared_ptr<ThreadManagerTests::BlockTask>(new ThreadManagerTests::BlockTask(monitor, bmonitor,activeCounts[0])));
}
for (size_t ix = 0; ix < pendingTaskMaxCount; ix++) {
- tasks.insert(shared_ptr<ThreadManagerTests::BlockTask>(
- new ThreadManagerTests::BlockTask(monitor, bmonitor, activeCounts[1])));
+ tasks.insert(shared_ptr<ThreadManagerTests::BlockTask>(new ThreadManagerTests::BlockTask(monitor, bmonitor,activeCounts[1])));
}
- for (std::set<shared_ptr<ThreadManagerTests::BlockTask> >::iterator ix = tasks.begin();
- ix != tasks.end();
- ix++) {
+ for (std::set<shared_ptr<ThreadManagerTests::BlockTask> >::iterator ix = tasks.begin(); ix != tasks.end(); ix++) {
threadManager->add(*ix);
}
- if (!(success = (threadManager->totalTaskCount() == pendingTaskMaxCount + workerCount))) {
+ if(!(success = (threadManager->totalTaskCount() == pendingTaskMaxCount + workerCount))) {
throw TException("Unexpected pending task count");
}
- shared_ptr<ThreadManagerTests::BlockTask> extraTask(
- new ThreadManagerTests::BlockTask(monitor, bmonitor, activeCounts[2]));
+ shared_ptr<ThreadManagerTests::BlockTask> extraTask(new ThreadManagerTests::BlockTask(monitor, bmonitor, activeCounts[2]));
try {
threadManager->add(extraTask, 1);
throw TException("Unexpected success adding task in excess of pending task count");
- } catch (TooManyPendingTasksException& e) {
+ } catch(TooManyPendingTasksException& e) {
throw TException("Should have timed out adding task in excess of pending task count");
- } catch (TimedOutException& e) {
+ } catch(TimedOutException& e) {
// Expected result
}
try {
threadManager->add(extraTask, -1);
throw TException("Unexpected success adding task in excess of pending task count");
- } catch (TimedOutException& e) {
+ } catch(TimedOutException& e) {
throw TException("Unexpected timeout adding task in excess of pending task count");
- } catch (TooManyPendingTasksException& e) {
+ } catch(TooManyPendingTasksException& e) {
// Expected result
}
- std::cout << "\t\t\t"
- << "Pending tasks " << threadManager->pendingTaskCount() << std::endl;
+ std::cout << "\t\t\t" << "Pending tasks " << threadManager->pendingTaskCount() << std::endl;
{
Synchronized s(bmonitor);
@@ -317,24 +304,21 @@
{
Synchronized s(monitor);
- while (activeCounts[0] != 0) {
+ while(activeCounts[0] != 0) {
monitor.wait();
}
}
- std::cout << "\t\t\t"
- << "Pending tasks " << threadManager->pendingTaskCount() << std::endl;
+ std::cout << "\t\t\t" << "Pending tasks " << threadManager->pendingTaskCount() << std::endl;
try {
threadManager->add(extraTask, 1);
- } catch (TimedOutException& e) {
- std::cout << "\t\t\t"
- << "add timed out unexpectedly" << std::endl;
+ } catch(TimedOutException& e) {
+ std::cout << "\t\t\t" << "add timed out unexpectedly" << std::endl;
throw TException("Unexpected timeout adding task");
- } catch (TooManyPendingTasksException& e) {
- std::cout << "\t\t\t"
- << "add encountered too many pending exepctions" << std::endl;
+ } catch(TooManyPendingTasksException& e) {
+ std::cout << "\t\t\t" << "add encountered too many pending exepctions" << std::endl;
throw TException("Unexpected timeout adding task");
}
@@ -349,7 +333,7 @@
{
Synchronized s(monitor);
- while (activeCounts[1] != 0) {
+ while(activeCounts[1] != 0) {
monitor.wait();
}
}
@@ -365,28 +349,26 @@
{
Synchronized s(monitor);
- while (activeCounts[2] != 0) {
+ while(activeCounts[2] != 0) {
monitor.wait();
}
}
- if (!(success = (threadManager->totalTaskCount() == 0))) {
+ if(!(success = (threadManager->totalTaskCount() == 0))) {
throw TException("Unexpected pending task count");
}
- } catch (TException& e) {
+ } catch(TException& e) {
std::cout << "ERROR: " << e.what() << std::endl;
}
std::cout << "\t\t\t" << (success ? "Success" : "Failure") << std::endl;
return success;
- }
+ }
};
const double ThreadManagerTests::TEST_TOLERANCE = .20;
-}
-}
-}
-} // apache::thrift::concurrency
+
+}}}} // apache::thrift::concurrency
using namespace apache::thrift::concurrency::test;
diff --git a/lib/cpp/test/concurrency/TimerManagerTests.h b/lib/cpp/test/concurrency/TimerManagerTests.h
index dda16ed..62eb4f4 100644
--- a/lib/cpp/test/concurrency/TimerManagerTests.h
+++ b/lib/cpp/test/concurrency/TimerManagerTests.h
@@ -25,10 +25,7 @@
#include <assert.h>
#include <iostream>
-namespace apache {
-namespace thrift {
-namespace concurrency {
-namespace test {
+namespace apache { namespace thrift { namespace concurrency { namespace test {
using namespace apache::thrift::concurrency;
@@ -36,15 +33,16 @@
static const double TEST_TOLERANCE;
-public:
- class Task : public Runnable {
- public:
- Task(Monitor& monitor, int64_t timeout)
- : _timeout(timeout),
- _startTime(Util::currentTime()),
- _monitor(monitor),
- _success(false),
- _done(false) {}
+ public:
+ class Task: public Runnable {
+ public:
+
+ Task(Monitor& monitor, int64_t timeout) :
+ _timeout(timeout),
+ _startTime(Util::currentTime()),
+ _monitor(monitor),
+ _success(false),
+ _done(false) {}
~Task() { std::cerr << this << std::endl; }
@@ -56,20 +54,20 @@
int64_t delta = _endTime - _startTime;
- delta = delta > _timeout ? delta - _timeout : _timeout - delta;
+
+ delta = delta > _timeout ? delta - _timeout : _timeout - delta;
float error = delta / _timeout;
- if (error < TEST_TOLERANCE) {
+ if(error < TEST_TOLERANCE) {
_success = true;
}
_done = true;
- std::cout << "\t\t\tTimerManagerTests::Task[" << this << "] done" << std::endl; // debug
+ std::cout << "\t\t\tTimerManagerTests::Task[" << this << "] done" << std::endl; //debug
- {
- Synchronized s(_monitor);
+ {Synchronized s(_monitor);
_monitor.notifyAll();
}
}
@@ -88,10 +86,9 @@
* properly clean up itself and the remaining orphaned timeout task when the
* manager goes out of scope and its destructor is called.
*/
- bool test00(int64_t timeout = 1000LL) {
+ bool test00(int64_t timeout=1000LL) {
- shared_ptr<TimerManagerTests::Task> orphanTask
- = shared_ptr<TimerManagerTests::Task>(new TimerManagerTests::Task(_monitor, 10 * timeout));
+ shared_ptr<TimerManagerTests::Task> orphanTask = shared_ptr<TimerManagerTests::Task>(new TimerManagerTests::Task(_monitor, 10 * timeout));
{
@@ -116,13 +113,12 @@
// Wait for 1 second in order to give timerManager a chance to start sleeping in response
// to adding orphanTask. We need to do this so we can verify that adding the second task
// kicks the dispatcher out of the current wait and starts the new 1 second wait.
- _monitor.wait(1000);
- assert(
- 0 == "ERROR: This wait should time out. TimerManager dispatcher may have a problem.");
- } catch (TimedOutException& ex) {
+ _monitor.wait (1000);
+ assert (0 == "ERROR: This wait should time out. TimerManager dispatcher may have a problem.");
+ } catch (TimedOutException &ex) {
}
- task.reset(new TimerManagerTests::Task(_monitor, timeout));
+ task.reset (new TimerManagerTests::Task(_monitor, timeout));
timerManager.add(task, timeout);
@@ -131,6 +127,7 @@
assert(task->_done);
+
std::cout << "\t\t\t" << (task->_success ? "Success" : "Failure") << "!" << std::endl;
}
@@ -147,7 +144,5 @@
};
const double TimerManagerTests::TEST_TOLERANCE = .20;
-}
-}
-}
-} // apache::thrift::concurrency
+
+}}}} // apache::thrift::concurrency
diff --git a/lib/cpp/test/processor/EventLog.cpp b/lib/cpp/test/processor/EventLog.cpp
index d4b8372..0ac3028 100644
--- a/lib/cpp/test/processor/EventLog.cpp
+++ b/lib/cpp/test/processor/EventLog.cpp
@@ -36,11 +36,10 @@
fprintf(stderr, "\n");
}
+
}
-namespace apache {
-namespace thrift {
-namespace test {
+namespace apache { namespace thrift { namespace test {
uint32_t EventLog::nextId_ = 0;
@@ -75,12 +74,11 @@
debug("New log: %d", id_);
}
-void EventLog::append(EventType type,
- uint32_t connectionId,
- uint32_t callId,
+void EventLog::append(EventType type, uint32_t connectionId, uint32_t callId,
const string& message) {
Synchronized s(monitor_);
- debug("%d <-- %u, %u, %s \"%s\"", id_, connectionId, callId, type, message.c_str());
+ debug("%d <-- %u, %u, %s \"%s\"", id_, connectionId, callId, type,
+ message.c_str());
Event e(type, connectionId, callId, message);
events_.push_back(e);
@@ -127,6 +125,5 @@
}
}
}
-}
-}
-} // apache::thrift::test
+
+}}} // apache::thrift::test
diff --git a/lib/cpp/test/processor/EventLog.h b/lib/cpp/test/processor/EventLog.h
index 4f8275d..d731cec 100644
--- a/lib/cpp/test/processor/EventLog.h
+++ b/lib/cpp/test/processor/EventLog.h
@@ -21,9 +21,7 @@
#include <thrift/concurrency/Monitor.h>
-namespace apache {
-namespace thrift {
-namespace test {
+namespace apache { namespace thrift { namespace test {
// Initially I made EventType an enum, but using char* results
// in much more readable error messages when there is a mismatch.
@@ -33,17 +31,21 @@
typedef const char* EventType;
struct Event {
- Event(EventType type, uint32_t connectionId, uint32_t callId, const std::string& message)
- : type(type), connectionId(connectionId), callId(callId), message(message) {}
+ Event(EventType type, uint32_t connectionId, uint32_t callId,
+ const std::string& message) :
+ type(type),
+ connectionId(connectionId),
+ callId(callId),
+ message(message) {}
EventType type;
- uint32_t connectionId;
- uint32_t callId;
- std::string message;
+ uint32_t connectionId;
+ uint32_t callId;
+ std::string message;
};
class EventLog {
-public:
+ public:
static EventType ET_LOG_END;
static EventType ET_CONN_CREATED;
static EventType ET_CONN_DESTROYED;
@@ -71,15 +73,13 @@
EventLog();
- void append(EventType type,
- uint32_t connectionId,
- uint32_t callId,
+ void append(EventType type, uint32_t connectionId, uint32_t callId,
const std::string& message = "");
Event waitForEvent(int64_t timeout = 500);
Event waitForConnEvent(uint32_t connId, int64_t timeout = 500);
-protected:
+ protected:
typedef std::list<Event> EventList;
concurrency::Monitor monitor_;
@@ -88,8 +88,7 @@
static uint32_t nextId_;
};
-}
-}
-} // apache::thrift::test
+
+}}} // apache::thrift::test
#endif // _THRIFT_TEST_EVENTLOG_H_
diff --git a/lib/cpp/test/processor/Handlers.h b/lib/cpp/test/processor/Handlers.h
index d894107..75f4349 100644
--- a/lib/cpp/test/processor/Handlers.h
+++ b/lib/cpp/test/processor/Handlers.h
@@ -23,14 +23,15 @@
#include "gen-cpp/ParentService.h"
#include "gen-cpp/ChildService.h"
-namespace apache {
-namespace thrift {
-namespace test {
+namespace apache { namespace thrift { namespace test {
class ParentHandler : virtual public ParentServiceIf {
-public:
- ParentHandler(const boost::shared_ptr<EventLog>& log)
- : triggerMonitor(&mutex_), generation_(0), wait_(false), log_(log) {}
+ public:
+ ParentHandler(const boost::shared_ptr<EventLog>& log) :
+ triggerMonitor(&mutex_),
+ generation_(0),
+ wait_(false),
+ log_(log) { }
int32_t incrementGeneration() {
concurrency::Guard g(mutex_);
@@ -115,7 +116,7 @@
triggerMonitor.notifyAll();
}
-protected:
+ protected:
/**
* blockUntilTriggered() won't return until triggerPendingCalls() is invoked
* in another thread.
@@ -140,8 +141,10 @@
};
class ChildHandler : public ParentHandler, virtual public ChildServiceIf {
-public:
- ChildHandler(const boost::shared_ptr<EventLog>& log) : ParentHandler(log), value_(0) {}
+ public:
+ ChildHandler(const boost::shared_ptr<EventLog>& log) :
+ ParentHandler(log),
+ value_(0) {}
int32_t setValue(int32_t value) {
concurrency::Guard g(mutex_);
@@ -159,16 +162,18 @@
return value_;
}
-protected:
+ protected:
int32_t value_;
};
struct ConnContext {
-public:
+ public:
ConnContext(boost::shared_ptr<protocol::TProtocol> in,
boost::shared_ptr<protocol::TProtocol> out,
- uint32_t id)
- : input(in), output(out), id(id) {}
+ uint32_t id) :
+ input(in),
+ output(out),
+ id(id) {}
boost::shared_ptr<protocol::TProtocol> input;
boost::shared_ptr<protocol::TProtocol> output;
@@ -176,18 +181,22 @@
};
struct CallContext {
-public:
- CallContext(ConnContext* context, uint32_t id, const std::string& name)
- : connContext(context), name(name), id(id) {}
+ public:
+ CallContext(ConnContext *context, uint32_t id, const std::string& name) :
+ connContext(context),
+ name(name),
+ id(id) {}
- ConnContext* connContext;
+ ConnContext *connContext;
std::string name;
uint32_t id;
};
class ServerEventHandler : public server::TServerEventHandler {
-public:
- ServerEventHandler(const boost::shared_ptr<EventLog>& log) : nextId_(1), log_(log) {}
+ public:
+ ServerEventHandler(const boost::shared_ptr<EventLog>& log) :
+ nextId_(1),
+ log_(log) {}
virtual void preServe() {}
@@ -200,8 +209,8 @@
}
virtual void deleteContext(void* serverContext,
- boost::shared_ptr<protocol::TProtocol> input,
- boost::shared_ptr<protocol::TProtocol> output) {
+ boost::shared_ptr<protocol::TProtocol>input,
+ boost::shared_ptr<protocol::TProtocol>output) {
ConnContext* context = reinterpret_cast<ConnContext*>(serverContext);
if (input != context->input) {
@@ -216,21 +225,22 @@
delete context;
}
- virtual void processContext(void* serverContext,
- boost::shared_ptr<transport::TTransport> transport) {
-// TODO: We currently don't test the behavior of the processContext()
-// calls. The various server implementations call processContext() at
-// slightly different times, and it is too annoying to try and account for
-// their various differences.
-//
-// TThreadedServer, TThreadPoolServer, and TSimpleServer usually wait until
-// they see the first byte of a request before calling processContext().
-// However, they don't wait for the first byte of the very first request,
-// and instead immediately call processContext() before any data is
-// received.
-//
-// TNonblockingServer always waits until receiving the full request before
-// calling processContext().
+ virtual void processContext(
+ void* serverContext,
+ boost::shared_ptr<transport::TTransport> transport) {
+ // TODO: We currently don't test the behavior of the processContext()
+ // calls. The various server implementations call processContext() at
+ // slightly different times, and it is too annoying to try and account for
+ // their various differences.
+ //
+ // TThreadedServer, TThreadPoolServer, and TSimpleServer usually wait until
+ // they see the first byte of a request before calling processContext().
+ // However, they don't wait for the first byte of the very first request,
+ // and instead immediately call processContext() before any data is
+ // received.
+ //
+ // TNonblockingServer always waits until receiving the full request before
+ // calling processContext().
#if 0
ConnContext* context = reinterpret_cast<ConnContext*>(serverContext);
log_->append(EventLog::ET_PROCESS, context->id, 0);
@@ -240,14 +250,16 @@
#endif
}
-protected:
+ protected:
uint32_t nextId_;
boost::shared_ptr<EventLog> log_;
};
class ProcessorEventHandler : public TProcessorEventHandler {
-public:
- ProcessorEventHandler(const boost::shared_ptr<EventLog>& log) : nextId_(1), log_(log) {}
+ public:
+ ProcessorEventHandler(const boost::shared_ptr<EventLog>& log) :
+ nextId_(1),
+ log_(log) {}
void* getContext(const char* fnName, void* serverContext) {
ConnContext* connContext = reinterpret_cast<ConnContext*>(serverContext);
@@ -255,65 +267,71 @@
CallContext* context = new CallContext(connContext, nextId_, fnName);
++nextId_;
- log_->append(EventLog::ET_CALL_STARTED, connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_CALL_STARTED, connContext->id, context->id,
+ fnName);
return context;
}
void freeContext(void* ctx, const char* fnName) {
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_CALL_FINISHED, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_CALL_FINISHED, context->connContext->id,
+ context->id, fnName);
delete context;
}
void preRead(void* ctx, const char* fnName) {
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_PRE_READ, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_PRE_READ, context->connContext->id, context->id,
+ fnName);
}
void postRead(void* ctx, const char* fnName, uint32_t bytes) {
THRIFT_UNUSED_VARIABLE(bytes);
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_POST_READ, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_POST_READ, context->connContext->id, context->id,
+ fnName);
}
void preWrite(void* ctx, const char* fnName) {
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_PRE_WRITE, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_PRE_WRITE, context->connContext->id, context->id,
+ fnName);
}
void postWrite(void* ctx, const char* fnName, uint32_t bytes) {
THRIFT_UNUSED_VARIABLE(bytes);
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_POST_WRITE, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_POST_WRITE, context->connContext->id,
+ context->id, fnName);
}
void asyncComplete(void* ctx, const char* fnName) {
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_ASYNC_COMPLETE, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_ASYNC_COMPLETE, context->connContext->id,
+ context->id, fnName);
}
void handlerError(void* ctx, const char* fnName) {
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_HANDLER_ERROR, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_HANDLER_ERROR, context->connContext->id,
+ context->id, fnName);
}
-protected:
+ protected:
void checkName(const CallContext* context, const char* fnName) {
// Note: we can't use BOOST_CHECK_EQUAL here, since the handler runs in a
// different thread from the test functions. Just abort if the names are
// different
if (context->name != fnName) {
- fprintf(stderr,
- "call context name mismatch: \"%s\" != \"%s\"\n",
- context->name.c_str(),
- fnName);
+ fprintf(stderr, "call context name mismatch: \"%s\" != \"%s\"\n",
+ context->name.c_str(), fnName);
fflush(stderr);
abort();
}
@@ -322,8 +340,7 @@
uint32_t nextId_;
boost::shared_ptr<EventLog> log_;
};
-}
-}
-} // apache::thrift::test
+
+}}} // apache::thrift::test
#endif // _THRIFT_PROCESSOR_TEST_HANDLERS_H_
diff --git a/lib/cpp/test/processor/ProcessorTest.cpp b/lib/cpp/test/processor/ProcessorTest.cpp
index 300b729..eee90c7 100644
--- a/lib/cpp/test/processor/ProcessorTest.cpp
+++ b/lib/cpp/test/processor/ProcessorTest.cpp
@@ -54,7 +54,7 @@
*/
class TSimpleServerTraits {
-public:
+ public:
typedef TSimpleServer ServerType;
boost::shared_ptr<TSimpleServer> createServer(
@@ -63,13 +63,13 @@
const boost::shared_ptr<TTransportFactory>& transportFactory,
const boost::shared_ptr<TProtocolFactory>& protocolFactory) {
boost::shared_ptr<TServerSocket> socket(new TServerSocket(port));
- return boost::shared_ptr<TSimpleServer>(
- new TSimpleServer(processor, socket, transportFactory, protocolFactory));
+ return boost::shared_ptr<TSimpleServer>(new TSimpleServer(
+ processor, socket, transportFactory, protocolFactory));
}
};
class TThreadedServerTraits {
-public:
+ public:
typedef TThreadedServer ServerType;
boost::shared_ptr<TThreadedServer> createServer(
@@ -78,13 +78,13 @@
const boost::shared_ptr<TTransportFactory>& transportFactory,
const boost::shared_ptr<TProtocolFactory>& protocolFactory) {
boost::shared_ptr<TServerSocket> socket(new TServerSocket(port));
- return boost::shared_ptr<TThreadedServer>(
- new TThreadedServer(processor, socket, transportFactory, protocolFactory));
+ return boost::shared_ptr<TThreadedServer>(new TThreadedServer(
+ processor, socket, transportFactory, protocolFactory));
}
};
class TThreadPoolServerTraits {
-public:
+ public:
typedef TThreadPoolServer ServerType;
boost::shared_ptr<TThreadPoolServer> createServer(
@@ -95,17 +95,19 @@
boost::shared_ptr<TServerSocket> socket(new TServerSocket(port));
boost::shared_ptr<PosixThreadFactory> threadFactory(new PosixThreadFactory);
- boost::shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(8);
+ boost::shared_ptr<ThreadManager> threadManager =
+ ThreadManager::newSimpleThreadManager(8);
threadManager->threadFactory(threadFactory);
threadManager->start();
- return boost::shared_ptr<TThreadPoolServer>(
- new TThreadPoolServer(processor, socket, transportFactory, protocolFactory, threadManager));
+ return boost::shared_ptr<TThreadPoolServer>(new TThreadPoolServer(
+ processor, socket, transportFactory, protocolFactory,
+ threadManager));
}
};
class TNonblockingServerTraits {
-public:
+ public:
typedef TNonblockingServer ServerType;
boost::shared_ptr<TNonblockingServer> createServer(
@@ -116,24 +118,25 @@
// TNonblockingServer automatically uses TFramedTransport.
// Raise an exception if the supplied transport factory is not a
// TFramedTransportFactory
- TFramedTransportFactory* framedFactory
- = dynamic_cast<TFramedTransportFactory*>(transportFactory.get());
+ TFramedTransportFactory* framedFactory =
+ dynamic_cast<TFramedTransportFactory*>(transportFactory.get());
if (framedFactory == NULL) {
throw TException("TNonblockingServer must use TFramedTransport");
}
boost::shared_ptr<PosixThreadFactory> threadFactory(new PosixThreadFactory);
- boost::shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(8);
+ boost::shared_ptr<ThreadManager> threadManager =
+ ThreadManager::newSimpleThreadManager(8);
threadManager->threadFactory(threadFactory);
threadManager->start();
- return boost::shared_ptr<TNonblockingServer>(
- new TNonblockingServer(processor, protocolFactory, port, threadManager));
+ return boost::shared_ptr<TNonblockingServer>(new TNonblockingServer(
+ processor, protocolFactory, port, threadManager));
}
};
class TNonblockingServerNoThreadsTraits {
-public:
+ public:
typedef TNonblockingServer ServerType;
boost::shared_ptr<TNonblockingServer> createServer(
@@ -144,16 +147,16 @@
// TNonblockingServer automatically uses TFramedTransport.
// Raise an exception if the supplied transport factory is not a
// TFramedTransportFactory
- TFramedTransportFactory* framedFactory
- = dynamic_cast<TFramedTransportFactory*>(transportFactory.get());
+ TFramedTransportFactory* framedFactory =
+ dynamic_cast<TFramedTransportFactory*>(transportFactory.get());
if (framedFactory == NULL) {
throw TException("TNonblockingServer must use TFramedTransport");
}
// Use a NULL ThreadManager
boost::shared_ptr<ThreadManager> threadManager;
- return boost::shared_ptr<TNonblockingServer>(
- new TNonblockingServer(processor, protocolFactory, port, threadManager));
+ return boost::shared_ptr<TNonblockingServer>(new TNonblockingServer(
+ processor, protocolFactory, port, threadManager));
}
};
@@ -170,7 +173,7 @@
*/
class UntemplatedTraits {
-public:
+ public:
typedef TBinaryProtocolFactory ProtocolFactory;
typedef TBinaryProtocol Protocol;
@@ -181,7 +184,7 @@
};
class TemplatedTraits {
-public:
+ public:
typedef TBinaryProtocolFactoryT<TBufferBase> ProtocolFactory;
typedef TBinaryProtocolT<TBufferBase> Protocol;
@@ -191,9 +194,10 @@
typedef ChildServiceClientT<Protocol> ChildClient;
};
-template <typename TemplateTraits_>
+
+template<typename TemplateTraits_>
class ParentServiceTraits {
-public:
+ public:
typedef typename TemplateTraits_::ParentProcessor Processor;
typedef typename TemplateTraits_::ParentClient Client;
typedef ParentHandler Handler;
@@ -202,9 +206,9 @@
typedef typename TemplateTraits_::Protocol Protocol;
};
-template <typename TemplateTraits_>
+template<typename TemplateTraits_>
class ChildServiceTraits {
-public:
+ public:
typedef typename TemplateTraits_::ChildProcessor Processor;
typedef typename TemplateTraits_::ChildClient Client;
typedef ChildHandler Handler;
@@ -220,18 +224,17 @@
// It would also be niec if they used covariant return types. Unfortunately,
// since they return shared_ptr instead of raw pointers, covariant return types
// won't work.
-template <typename ServerTraits_,
- typename ServiceTraits_,
- typename TransportFactory_ = TFramedTransportFactory,
- typename Transport_ = TFramedTransport>
+template<typename ServerTraits_, typename ServiceTraits_,
+ typename TransportFactory_ = TFramedTransportFactory,
+ typename Transport_ = TFramedTransport>
class ServiceState : public ServerState {
-public:
+ public:
typedef typename ServiceTraits_::Processor Processor;
typedef typename ServiceTraits_::Client Client;
typedef typename ServiceTraits_::Handler Handler;
- ServiceState()
- : port_(0),
+ ServiceState() :
+ port_(0),
log_(new EventLog),
handler_(new Handler(log_)),
processor_(new Processor(handler_)),
@@ -244,18 +247,29 @@
boost::shared_ptr<TServer> createServer(uint16_t port) {
ServerTraits_ serverTraits;
- return serverTraits.createServer(processor_, port, transportFactory_, protocolFactory_);
+ return serverTraits.createServer(processor_, port, transportFactory_,
+ protocolFactory_);
}
- boost::shared_ptr<TServerEventHandler> getServerEventHandler() { return serverEventHandler_; }
+ boost::shared_ptr<TServerEventHandler> getServerEventHandler() {
+ return serverEventHandler_;
+ }
- void bindSuccessful(uint16_t port) { port_ = port; }
+ void bindSuccessful(uint16_t port) {
+ port_ = port;
+ }
- uint16_t getPort() const { return port_; }
+ uint16_t getPort() const {
+ return port_;
+ }
- const boost::shared_ptr<EventLog>& getLog() const { return log_; }
+ const boost::shared_ptr<EventLog>& getLog() const {
+ return log_;
+ }
- const boost::shared_ptr<Handler>& getHandler() const { return handler_; }
+ const boost::shared_ptr<Handler>& getHandler() const {
+ return handler_;
+ }
boost::shared_ptr<Client> createClient() {
typedef typename ServiceTraits_::Protocol Protocol;
@@ -269,7 +283,7 @@
return client;
}
-private:
+ private:
uint16_t port_;
boost::shared_ptr<EventLog> log_;
boost::shared_ptr<Handler> handler_;
@@ -280,6 +294,7 @@
boost::shared_ptr<TProcessorEventHandler> processorEventHandler_;
};
+
/**
* Check that there are no more events in the log
*/
@@ -421,7 +436,7 @@
* Test functions
*/
-template <typename State_>
+template<typename State_>
void testParentService(const boost::shared_ptr<State_>& state) {
boost::shared_ptr<typename State_::Client> client = state->createClient();
@@ -443,7 +458,7 @@
BOOST_REQUIRE_EQUAL("asdf", strings[2]);
}
-template <typename State_>
+template<typename State_>
void testChildService(const boost::shared_ptr<State_>& state) {
boost::shared_ptr<typename State_::Client> client = state->createClient();
@@ -461,9 +476,10 @@
BOOST_CHECK_EQUAL(99, client->getValue());
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testBasicService() {
- typedef ServiceState<ServerTraits, ParentServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ParentServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -472,9 +488,10 @@
testParentService(state);
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testInheritedService() {
- typedef ServiceState<ServerTraits, ChildServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -488,16 +505,15 @@
* Test to make sure that the TServerEventHandler and TProcessorEventHandler
* methods are invoked in the correct order with the actual events.
*/
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testEventSequencing() {
// We use TBufferedTransport for this test, instead of TFramedTransport.
// This way the server will start processing data as soon as it is received,
// instead of waiting for the full request. This is necessary so we can
// separate the preRead() and postRead() events.
- typedef ServiceState<ServerTraits,
- ChildServiceTraits<TemplateTraits>,
- TBufferedTransportFactory,
- TBufferedTransport> State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits>,
+ TBufferedTransportFactory, TBufferedTransport>
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -546,7 +562,7 @@
// Send the rest of the request
protocol.writeStructBegin("ParentService_getDataNotified_pargs");
protocol.writeFieldBegin("length", apache::thrift::protocol::T_I32, 1);
- protocol.writeI32(8 * 1024 * 1024);
+ protocol.writeI32(8*1024*1024);
protocol.writeFieldEnd();
protocol.writeFieldStop();
protocol.writeStructEnd();
@@ -628,9 +644,10 @@
checkNoEvents(log);
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testSeparateConnections() {
- typedef ServiceState<ServerTraits, ChildServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -656,19 +673,20 @@
// Make a call, and check for the proper events
int32_t value = 5;
client1->setValue(value);
- uint32_t call1
- = checkCallEvents(log, client1Id, EventLog::ET_CALL_SET_VALUE, "ChildService.setValue");
+ uint32_t call1 = checkCallEvents(log, client1Id, EventLog::ET_CALL_SET_VALUE,
+ "ChildService.setValue");
// Make a call with client2
int32_t v = client2->getValue();
BOOST_CHECK_EQUAL(value, v);
- checkCallEvents(log, client2Id, EventLog::ET_CALL_GET_VALUE, "ChildService.getValue");
+ checkCallEvents(log, client2Id, EventLog::ET_CALL_GET_VALUE,
+ "ChildService.getValue");
// Make another call with client1
v = client1->getValue();
BOOST_CHECK_EQUAL(value, v);
- uint32_t call2
- = checkCallEvents(log, client1Id, EventLog::ET_CALL_GET_VALUE, "ChildService.getValue");
+ uint32_t call2 = checkCallEvents(log, client1Id, EventLog::ET_CALL_GET_VALUE,
+ "ChildService.getValue");
BOOST_CHECK_NE(call1, call2);
// Close the second client, and check for the appropriate events
@@ -676,9 +694,10 @@
checkCloseEvents(log, client2Id);
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testOnewayCall() {
- typedef ServiceState<ServerTraits, ChildServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -696,7 +715,9 @@
state->getHandler()->prepareTriggeredCall();
client->onewayWait();
string callName = "ParentService.onewayWait";
- uint32_t callId = checkCallHandlerEvents(log, connId, EventLog::ET_CALL_ONEWAY_WAIT, callName);
+ uint32_t callId = checkCallHandlerEvents(log, connId,
+ EventLog::ET_CALL_ONEWAY_WAIT,
+ callName);
// There shouldn't be any more events
checkNoEvents(log);
@@ -728,9 +749,10 @@
checkNoEvents(log);
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testExpectedError() {
- typedef ServiceState<ServerTraits, ChildServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -747,7 +769,9 @@
string message = "test 1234 test";
client->send_exceptionWait(message);
string callName = "ParentService.exceptionWait";
- uint32_t callId = checkCallHandlerEvents(log, connId, EventLog::ET_CALL_EXCEPTION_WAIT, callName);
+ uint32_t callId = checkCallHandlerEvents(log, connId,
+ EventLog::ET_CALL_EXCEPTION_WAIT,
+ callName);
// There shouldn't be any more events
checkNoEvents(log);
@@ -780,9 +804,10 @@
checkNoEvents(log);
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testUnexpectedError() {
- typedef ServiceState<ServerTraits, ChildServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -799,8 +824,8 @@
string message = "1234 test 5678";
client->send_unexpectedExceptionWait(message);
string callName = "ParentService.unexpectedExceptionWait";
- uint32_t callId
- = checkCallHandlerEvents(log, connId, EventLog::ET_CALL_UNEXPECTED_EXCEPTION_WAIT, callName);
+ uint32_t callId = checkCallHandlerEvents(
+ log, connId, EventLog::ET_CALL_UNEXPECTED_EXCEPTION_WAIT, callName);
// There shouldn't be any more events
checkNoEvents(log);
@@ -846,46 +871,47 @@
checkNoEvents(log);
}
+
// Macro to define simple tests that can be used with all server types
-#define DEFINE_SIMPLE_TESTS(Server, Template) \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_basicService) { \
- testBasicService<Server##Traits, Template##Traits>(); \
- } \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_inheritedService) { \
- testInheritedService<Server##Traits, Template##Traits>(); \
- } \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_oneway) { \
- testOnewayCall<Server##Traits, Template##Traits>(); \
- } \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_exception) { \
- testExpectedError<Server##Traits, Template##Traits>(); \
- } \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_unexpectedException) { \
- testUnexpectedError<Server##Traits, Template##Traits>(); \
+#define DEFINE_SIMPLE_TESTS(Server, Template) \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_basicService) { \
+ testBasicService<Server##Traits, Template##Traits>(); \
+ } \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_inheritedService) { \
+ testInheritedService<Server##Traits, Template##Traits>(); \
+ } \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_oneway) { \
+ testOnewayCall<Server##Traits, Template##Traits>(); \
+ } \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_exception) { \
+ testExpectedError<Server##Traits, Template##Traits>(); \
+ } \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_unexpectedException) { \
+ testUnexpectedError<Server##Traits, Template##Traits>(); \
}
// Tests that require the server to process multiple connections concurrently
// (i.e., not TSimpleServer)
-#define DEFINE_CONCURRENT_SERVER_TESTS(Server, Template) \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_separateConnections) { \
- testSeparateConnections<Server##Traits, Template##Traits>(); \
+#define DEFINE_CONCURRENT_SERVER_TESTS(Server, Template) \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_separateConnections) { \
+ testSeparateConnections<Server##Traits, Template##Traits>(); \
}
// The testEventSequencing() test manually generates a request for the server,
// and doesn't work with TFramedTransport. Therefore we can't test it with
// TNonblockingServer.
-#define DEFINE_NOFRAME_TESTS(Server, Template) \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_eventSequencing) { \
- testEventSequencing<Server##Traits, Template##Traits>(); \
+#define DEFINE_NOFRAME_TESTS(Server, Template) \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_eventSequencing) { \
+ testEventSequencing<Server##Traits, Template##Traits>(); \
}
-#define DEFINE_TNONBLOCKINGSERVER_TESTS(Server, Template) \
- DEFINE_SIMPLE_TESTS(Server, Template) \
+#define DEFINE_TNONBLOCKINGSERVER_TESTS(Server, Template) \
+ DEFINE_SIMPLE_TESTS(Server, Template) \
DEFINE_CONCURRENT_SERVER_TESTS(Server, Template)
-#define DEFINE_ALL_SERVER_TESTS(Server, Template) \
- DEFINE_SIMPLE_TESTS(Server, Template) \
- DEFINE_CONCURRENT_SERVER_TESTS(Server, Template) \
+#define DEFINE_ALL_SERVER_TESTS(Server, Template) \
+ DEFINE_SIMPLE_TESTS(Server, Template) \
+ DEFINE_CONCURRENT_SERVER_TESTS(Server, Template) \
DEFINE_NOFRAME_TESTS(Server, Template)
DEFINE_ALL_SERVER_TESTS(TThreadedServer, Templated)
diff --git a/lib/cpp/test/processor/ServerThread.cpp b/lib/cpp/test/processor/ServerThread.cpp
index aa6fd7f..9f2087c 100644
--- a/lib/cpp/test/processor/ServerThread.cpp
+++ b/lib/cpp/test/processor/ServerThread.cpp
@@ -27,9 +27,7 @@
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/TServerSocket.h>
-namespace apache {
-namespace thrift {
-namespace test {
+namespace apache { namespace thrift { namespace test {
void ServerThread::start() {
assert(!running_);
@@ -50,8 +48,9 @@
}
if (error_) {
- throw transport::TTransportException(transport::TTransportException::NOT_OPEN,
- "failed to bind on server socket");
+ throw transport::TTransportException(
+ transport::TTransportException::NOT_OPEN,
+ "failed to bind on server socket");
}
}
@@ -128,8 +127,8 @@
serverState_->bindSuccessful(port_);
// Set the real server event handler (replacing ourself)
- boost::shared_ptr<server::TServerEventHandler> serverEventHandler
- = serverState_->getServerEventHandler();
+ boost::shared_ptr<server::TServerEventHandler> serverEventHandler =
+ serverState_->getServerEventHandler();
server_->setServerEventHandler(serverEventHandler);
// Notify the main thread that we have successfully started serving requests
@@ -143,8 +142,7 @@
serverEventHandler->preServe();
}
}
-}
-}
-} // apache::thrift::test
+
+}}} // apache::thrift::test
#endif // _THRIFT_TEST_SERVERTHREAD_TCC_
diff --git a/lib/cpp/test/processor/ServerThread.h b/lib/cpp/test/processor/ServerThread.h
index eed3469..f7fa0d5 100644
--- a/lib/cpp/test/processor/ServerThread.h
+++ b/lib/cpp/test/processor/ServerThread.h
@@ -26,15 +26,13 @@
#include "EventLog.h"
-namespace apache {
-namespace thrift {
-namespace test {
+namespace apache { namespace thrift { namespace test {
/**
* A helper class to tell ServerThread how to create the server
*/
class ServerState {
-public:
+ public:
virtual ~ServerState() {}
/**
@@ -52,7 +50,8 @@
* start serving traffic. It is invoked from the server thread, rather than
* the main thread.
*/
- virtual boost::shared_ptr<server::TServerEventHandler> getServerEventHandler() {
+ virtual boost::shared_ptr<server::TServerEventHandler>
+ getServerEventHandler() {
return boost::shared_ptr<server::TServerEventHandler>();
}
@@ -62,16 +61,17 @@
* Subclasses may override this method if they wish to record the final
* port that was used for the server.
*/
- virtual void bindSuccessful(uint16_t /*port*/) {}
+ virtual void bindSuccessful(uint16_t /*port*/) {
+ }
};
/**
* ServerThread starts a thrift server running in a separate thread.
*/
class ServerThread {
-public:
- ServerThread(const boost::shared_ptr<ServerState>& state, bool autoStart)
- : helper_(new Helper(this)),
+ public:
+ ServerThread(const boost::shared_ptr<ServerState>& state, bool autoStart) :
+ helper_(new Helper(this)),
port_(0),
running_(false),
serving_(false),
@@ -85,7 +85,9 @@
void start();
void stop();
- uint16_t getPort() const { return port_; }
+ uint16_t getPort() const {
+ return port_;
+ }
~ServerThread() {
if (running_) {
@@ -97,20 +99,26 @@
}
}
-protected:
+ protected:
// Annoying. thrift forces us to use shared_ptr, so we have to use
// a helper class that we can allocate on the heap and give to thrift.
// It would be simpler if we could just make Runnable and TServerEventHandler
// private base classes of ServerThread.
- class Helper : public concurrency::Runnable, public server::TServerEventHandler {
- public:
- Helper(ServerThread* serverThread) : serverThread_(serverThread) {}
+ class Helper : public concurrency::Runnable,
+ public server::TServerEventHandler {
+ public:
+ Helper(ServerThread* serverThread)
+ : serverThread_(serverThread) {}
- void run() { serverThread_->run(); }
+ void run() {
+ serverThread_->run();
+ }
- void preServe() { serverThread_->preServe(); }
+ void preServe() {
+ serverThread_->preServe();
+ }
- private:
+ private:
ServerThread* serverThread_;
};
@@ -129,8 +137,7 @@
boost::shared_ptr<server::TServer> server_;
boost::shared_ptr<concurrency::Thread> thread_;
};
-}
-}
-} // apache::thrift::test
+
+}}} // apache::thrift::test
#endif // _THRIFT_TEST_SERVERTHREAD_H_