blob: 59f2427a5182b41859047a87d954ea2272f24527 [file] [log] [blame]
David Reiss35dc7692010-10-06 17:10:19 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19#ifndef _GNU_SOURCE
20#define _GNU_SOURCE // needed for getopt_long
21#endif
22
23#include <stdlib.h>
24#include <time.h>
25#include <unistd.h>
26#include <getopt.h>
David Reisse5c435c2010-10-06 17:10:38 +000027#include <signal.h>
David Reiss35dc7692010-10-06 17:10:19 +000028#include <sstream>
29#include <tr1/functional>
30
31#include <boost/mpl/list.hpp>
32#include <boost/shared_array.hpp>
33#include <boost/random.hpp>
34#include <boost/type_traits.hpp>
35#include <boost/test/unit_test.hpp>
36
37#include <transport/TBufferTransports.h>
38#include <transport/TFDTransport.h>
39#include <transport/TFileTransport.h>
David Reisse94fa332010-10-06 17:10:26 +000040#include <transport/TZlibTransport.h>
David Reiss0c025e82010-10-06 17:10:36 +000041#include <transport/TSocket.h>
David Reiss35dc7692010-10-06 17:10:19 +000042
43using namespace apache::thrift::transport;
44
45static boost::mt19937 rng;
46static const char* tmp_dir = "/tmp";
47
David Reiss65e62d32010-10-06 17:10:35 +000048void initrand(unsigned int seed) {
David Reiss35dc7692010-10-06 17:10:19 +000049 rng.seed(seed);
50}
51
52class SizeGenerator {
53 public:
54 virtual ~SizeGenerator() {}
55 virtual uint32_t nextSize() = 0;
56 virtual std::string describe() const = 0;
57};
58
59class ConstantSizeGenerator : public SizeGenerator {
60 public:
61 ConstantSizeGenerator(uint32_t value) : value_(value) {}
62 uint32_t nextSize() { return value_; }
63 std::string describe() const {
64 std::ostringstream desc;
65 desc << value_;
66 return desc.str();
67 }
68
69 private:
70 uint32_t value_;
71};
72
73class RandomSizeGenerator : public SizeGenerator {
74 public:
75 RandomSizeGenerator(uint32_t min, uint32_t max) :
76 generator_(rng, boost::uniform_int<int>(min, max)) {}
77
78 uint32_t nextSize() { return generator_(); }
79
80 std::string describe() const {
81 std::ostringstream desc;
82 desc << "rand(" << getMin() << ", " << getMax() << ")";
83 return desc.str();
84 }
85
86 uint32_t getMin() const { return generator_.distribution().min(); }
87 uint32_t getMax() const { return generator_.distribution().max(); }
88
89 private:
90 boost::variate_generator< boost::mt19937&, boost::uniform_int<int> >
91 generator_;
92};
93
94/**
95 * This class exists solely to make the TEST_RW() macro easier to use.
96 * - it can be constructed implicitly from an integer
97 * - it can contain either a ConstantSizeGenerator or a RandomSizeGenerator
98 * (TEST_RW can't take a SizeGenerator pointer or reference, since it needs
99 * to make a copy of the generator to bind it to the test function.)
100 */
101class GenericSizeGenerator : public SizeGenerator {
102 public:
103 GenericSizeGenerator(uint32_t value) :
104 generator_(new ConstantSizeGenerator(value)) {}
105 GenericSizeGenerator(uint32_t min, uint32_t max) :
106 generator_(new RandomSizeGenerator(min, max)) {}
107
108 uint32_t nextSize() { return generator_->nextSize(); }
109 std::string describe() const { return generator_->describe(); }
110
111 private:
112 boost::shared_ptr<SizeGenerator> generator_;
113};
114
115/**************************************************************************
116 * Classes to set up coupled transports
117 **************************************************************************/
118
David Reiss0c025e82010-10-06 17:10:36 +0000119/**
120 * Helper class to represent a coupled pair of transports.
121 *
122 * Data written to the out transport can be read from the in transport.
123 *
124 * This is used as the base class for the various coupled transport
125 * implementations. It shouldn't be instantiated directly.
126 */
David Reiss35dc7692010-10-06 17:10:19 +0000127template <class Transport_>
128class CoupledTransports {
129 public:
130 typedef Transport_ TransportType;
131
David Reissd4788df2010-10-06 17:10:37 +0000132 CoupledTransports() : in(), out() {}
David Reiss35dc7692010-10-06 17:10:19 +0000133
David Reissd4788df2010-10-06 17:10:37 +0000134 boost::shared_ptr<Transport_> in;
135 boost::shared_ptr<Transport_> out;
David Reiss35dc7692010-10-06 17:10:19 +0000136
137 private:
138 CoupledTransports(const CoupledTransports&);
139 CoupledTransports &operator=(const CoupledTransports&);
140};
141
David Reiss0c025e82010-10-06 17:10:36 +0000142/**
143 * Coupled TMemoryBuffers
144 */
David Reiss35dc7692010-10-06 17:10:19 +0000145class CoupledMemoryBuffers : public CoupledTransports<TMemoryBuffer> {
146 public:
David Reissd4788df2010-10-06 17:10:37 +0000147 CoupledMemoryBuffers() :
148 buf(new TMemoryBuffer) {
149 in = buf;
150 out = buf;
David Reiss35dc7692010-10-06 17:10:19 +0000151 }
152
David Reissd4788df2010-10-06 17:10:37 +0000153 boost::shared_ptr<TMemoryBuffer> buf;
154};
155
156/**
157 * Helper template class for creating coupled transports that wrap
158 * another transport.
159 */
160template <class WrapperTransport_, class InnerCoupledTransports_>
161class CoupledWrapperTransportsT : public CoupledTransports<WrapperTransport_> {
162 public:
163 CoupledWrapperTransportsT() {
164 if (inner_.in) {
165 this->in.reset(new WrapperTransport_(inner_.in));
166 }
167 if (inner_.out) {
168 this->out.reset(new WrapperTransport_(inner_.out));
169 }
170 }
171
172 InnerCoupledTransports_ inner_;
David Reiss35dc7692010-10-06 17:10:19 +0000173};
174
David Reiss0c025e82010-10-06 17:10:36 +0000175/**
176 * Coupled TBufferedTransports.
David Reiss0c025e82010-10-06 17:10:36 +0000177 */
David Reissd4788df2010-10-06 17:10:37 +0000178template <class InnerTransport_>
179class CoupledBufferedTransportsT :
180 public CoupledWrapperTransportsT<TBufferedTransport, InnerTransport_> {
David Reiss35dc7692010-10-06 17:10:19 +0000181};
182
David Reissd4788df2010-10-06 17:10:37 +0000183typedef CoupledBufferedTransportsT<CoupledMemoryBuffers>
184 CoupledBufferedTransports;
185
David Reiss0c025e82010-10-06 17:10:36 +0000186/**
187 * Coupled TFramedTransports.
David Reiss0c025e82010-10-06 17:10:36 +0000188 */
David Reissd4788df2010-10-06 17:10:37 +0000189template <class InnerTransport_>
190class CoupledFramedTransportsT :
191 public CoupledWrapperTransportsT<TFramedTransport, InnerTransport_> {
David Reiss35dc7692010-10-06 17:10:19 +0000192};
193
David Reissd4788df2010-10-06 17:10:37 +0000194typedef CoupledFramedTransportsT<CoupledMemoryBuffers>
195 CoupledFramedTransports;
196
David Reiss0c025e82010-10-06 17:10:36 +0000197/**
198 * Coupled TZlibTransports.
199 */
David Reissd4788df2010-10-06 17:10:37 +0000200template <class InnerTransport_>
201class CoupledZlibTransportsT :
202 public CoupledWrapperTransportsT<TZlibTransport, InnerTransport_> {
David Reisse94fa332010-10-06 17:10:26 +0000203};
204
David Reissd4788df2010-10-06 17:10:37 +0000205typedef CoupledZlibTransportsT<CoupledMemoryBuffers>
206 CoupledZlibTransports;
207
David Reiss0c025e82010-10-06 17:10:36 +0000208/**
209 * Coupled TFDTransports.
210 */
David Reiss35dc7692010-10-06 17:10:19 +0000211class CoupledFDTransports : public CoupledTransports<TFDTransport> {
212 public:
213 CoupledFDTransports() {
214 int pipes[2];
215
216 if (pipe(pipes) != 0) {
217 return;
218 }
219
David Reissd4788df2010-10-06 17:10:37 +0000220 in.reset(new TFDTransport(pipes[0], TFDTransport::CLOSE_ON_DESTROY));
221 out.reset(new TFDTransport(pipes[1], TFDTransport::CLOSE_ON_DESTROY));
David Reiss35dc7692010-10-06 17:10:19 +0000222 }
223};
224
David Reiss0c025e82010-10-06 17:10:36 +0000225/**
226 * Coupled TSockets
227 */
228class CoupledSocketTransports : public CoupledTransports<TSocket> {
229 public:
230 CoupledSocketTransports() {
231 int sockets[2];
232 if (socketpair(PF_UNIX, SOCK_STREAM, 0, sockets) != 0) {
233 return;
234 }
235
David Reissd4788df2010-10-06 17:10:37 +0000236 in.reset(new TSocket(sockets[0]));
237 out.reset(new TSocket(sockets[1]));
David Reiss0c025e82010-10-06 17:10:36 +0000238 }
239};
240
241/**
242 * Coupled TFileTransports
243 */
David Reiss35dc7692010-10-06 17:10:19 +0000244class CoupledFileTransports : public CoupledTransports<TFileTransport> {
245 public:
246 CoupledFileTransports() {
247 // Create a temporary file to use
248 size_t filename_len = strlen(tmp_dir) + 32;
249 filename = new char[filename_len];
250 snprintf(filename, filename_len,
251 "%s/thrift.transport_test.XXXXXX", tmp_dir);
252 fd = mkstemp(filename);
253 if (fd < 0) {
254 return;
255 }
256
David Reissd4788df2010-10-06 17:10:37 +0000257 in.reset(new TFileTransport(filename, true));
258 out.reset(new TFileTransport(filename));
David Reiss35dc7692010-10-06 17:10:19 +0000259 }
260
261 ~CoupledFileTransports() {
David Reiss35dc7692010-10-06 17:10:19 +0000262 if (fd >= 0) {
263 close(fd);
264 unlink(filename);
265 }
266 delete[] filename;
267 }
268
269 char* filename;
270 int fd;
271};
272
David Reiss0c025e82010-10-06 17:10:36 +0000273/**
274 * Wrapper around another CoupledTransports implementation that exposes the
275 * transports as TTransport pointers.
276 *
277 * This is used since accessing a transport via a "TTransport*" exercises a
278 * different code path than using the base pointer class. As part of the
279 * template code changes, most transport methods are no longer virtual.
280 */
David Reiss35dc7692010-10-06 17:10:19 +0000281template <class CoupledTransports_>
282class CoupledTTransports : public CoupledTransports<TTransport> {
283 public:
284 CoupledTTransports() : transports() {
285 in = transports.in;
286 out = transports.out;
287 }
288
289 CoupledTransports_ transports;
290};
291
David Reiss0c025e82010-10-06 17:10:36 +0000292/**
293 * Wrapper around another CoupledTransports implementation that exposes the
294 * transports as TBufferBase pointers.
295 *
296 * This can only be instantiated with a transport type that is a subclass of
297 * TBufferBase.
298 */
David Reiss35dc7692010-10-06 17:10:19 +0000299template <class CoupledTransports_>
300class CoupledBufferBases : public CoupledTransports<TBufferBase> {
301 public:
302 CoupledBufferBases() : transports() {
303 in = transports.in;
304 out = transports.out;
305 }
306
307 CoupledTransports_ transports;
308};
309
David Reiss35dc7692010-10-06 17:10:19 +0000310/**************************************************************************
David Reisse5c435c2010-10-06 17:10:38 +0000311 * Alarm handling code for use in tests that check the transport blocking
312 * semantics.
313 *
314 * If the transport ends up blocking, we don't want to hang forever. We use
315 * SIGALRM to fire schedule signal to wake up and try to write data so the
316 * transport will unblock.
317 *
318 * It isn't really the safest thing in the world to be mucking around with
319 * complicated global data structures in a signal handler. It should probably
320 * be okay though, since we know the main thread should always be blocked in a
321 * read() request when the signal handler is running.
322 **************************************************************************/
323
324struct TriggerInfo {
325 TriggerInfo(int seconds, const boost::shared_ptr<TTransport>& transport,
326 uint32_t writeLength) :
327 timeoutSeconds(seconds),
328 transport(transport),
329 writeLength(writeLength),
330 next(NULL) {}
331
332 int timeoutSeconds;
333 boost::shared_ptr<TTransport> transport;
334 uint32_t writeLength;
335 TriggerInfo* next;
336};
337
338TriggerInfo* triggerInfo;
339unsigned int numTriggersFired;
340
341void set_alarm();
342
343void alarm_handler(int signum) {
344 // The alarm timed out, which almost certainly means we're stuck
345 // on a transport that is incorrectly blocked.
346 ++numTriggersFired;
347
348 // Note: we print messages to stdout instead of stderr, since
349 // tools/test/runner only records stdout messages in the failure messages for
350 // boost tests. (boost prints its test info to stdout.)
351 printf("Timeout alarm expired; attempting to unblock transport\n");
352 if (triggerInfo == NULL) {
353 printf(" trigger stack is empty!\n");
354 }
355
356 // Pop off the first TriggerInfo.
357 // If there is another one, schedule an alarm for it.
358 TriggerInfo* info = triggerInfo;
359 triggerInfo = info->next;
360 set_alarm();
361
362 // Write some data to the transport to hopefully unblock it.
Roger Meier0069cc42010-10-13 18:10:18 +0000363 uint8_t* buf = new uint8_t[info->writeLength];
David Reisse5c435c2010-10-06 17:10:38 +0000364 memset(buf, 'b', info->writeLength);
Roger Meier0069cc42010-10-13 18:10:18 +0000365 boost::scoped_array<uint8_t> array(buf);
David Reisse5c435c2010-10-06 17:10:38 +0000366 info->transport->write(buf, info->writeLength);
367 info->transport->flush();
368
369 delete info;
370}
371
372void set_alarm() {
373 if (triggerInfo == NULL) {
374 // clear any alarm
375 alarm(0);
376 return;
377 }
378
379 struct sigaction action;
380 memset(&action, 0, sizeof(action));
381 action.sa_handler = alarm_handler;
382 action.sa_flags = SA_ONESHOT;
383 sigemptyset(&action.sa_mask);
384 sigaction(SIGALRM, &action, NULL);
385
386 alarm(triggerInfo->timeoutSeconds);
387}
388
389/**
390 * Add a trigger to be scheduled "seconds" seconds after the
391 * last currently scheduled trigger.
392 *
393 * (Note that this is not "seconds" from now. That might be more logical, but
394 * would require slightly more complicated sorting, rather than just appending
395 * to the end.)
396 */
397void add_trigger(unsigned int seconds,
398 const boost::shared_ptr<TTransport> &transport,
399 uint32_t write_len) {
400 TriggerInfo* info = new TriggerInfo(seconds, transport, write_len);
401
402 if (triggerInfo == NULL) {
403 // This is the first trigger.
404 // Set triggerInfo, and schedule the alarm
405 triggerInfo = info;
406 set_alarm();
407 } else {
408 // Add this trigger to the end of the list
409 TriggerInfo* prev = triggerInfo;
410 while (prev->next) {
411 prev = prev->next;
412 }
413
414 prev->next = info;
415 }
416}
417
418void clear_triggers() {
419 TriggerInfo *info = triggerInfo;
420 alarm(0);
421 triggerInfo = NULL;
422 numTriggersFired = 0;
423
424 while (info != NULL) {
425 TriggerInfo* next = info->next;
426 delete info;
427 info = next;
428 }
429}
430
431void set_trigger(unsigned int seconds,
432 const boost::shared_ptr<TTransport> &transport,
433 uint32_t write_len) {
434 clear_triggers();
435 add_trigger(seconds, transport, write_len);
436}
437
438/**************************************************************************
439 * Test functions
David Reiss35dc7692010-10-06 17:10:19 +0000440 **************************************************************************/
441
442/**
443 * Test interleaved write and read calls.
444 *
445 * Generates a buffer totalSize bytes long, then writes it to the transport,
446 * and verifies the written data can be read back correctly.
447 *
448 * Mode of operation:
449 * - call wChunkGenerator to figure out how large of a chunk to write
450 * - call wSizeGenerator to get the size for individual write() calls,
451 * and do this repeatedly until the entire chunk is written.
452 * - call rChunkGenerator to figure out how large of a chunk to read
453 * - call rSizeGenerator to get the size for individual read() calls,
454 * and do this repeatedly until the entire chunk is read.
455 * - repeat until the full buffer is written and read back,
456 * then compare the data read back against the original buffer
457 *
458 *
459 * - If any of the size generators return 0, this means to use the maximum
460 * possible size.
461 *
462 * - If maxOutstanding is non-zero, write chunk sizes will be chosen such that
463 * there are never more than maxOutstanding bytes waiting to be read back.
464 */
465template <class CoupledTransports>
466void test_rw(uint32_t totalSize,
467 SizeGenerator& wSizeGenerator,
468 SizeGenerator& rSizeGenerator,
469 SizeGenerator& wChunkGenerator,
470 SizeGenerator& rChunkGenerator,
471 uint32_t maxOutstanding) {
472 CoupledTransports transports;
473 BOOST_REQUIRE(transports.in != NULL);
474 BOOST_REQUIRE(transports.out != NULL);
475
476 boost::shared_array<uint8_t> wbuf =
477 boost::shared_array<uint8_t>(new uint8_t[totalSize]);
478 boost::shared_array<uint8_t> rbuf =
479 boost::shared_array<uint8_t>(new uint8_t[totalSize]);
480
481 // store some data in wbuf
482 for (uint32_t n = 0; n < totalSize; ++n) {
483 wbuf[n] = (n & 0xff);
484 }
485 // clear rbuf
486 memset(rbuf.get(), 0, totalSize);
487
488 uint32_t total_written = 0;
489 uint32_t total_read = 0;
490 while (total_read < totalSize) {
491 // Determine how large a chunk of data to write
492 uint32_t wchunk_size = wChunkGenerator.nextSize();
493 if (wchunk_size == 0 || wchunk_size > totalSize - total_written) {
494 wchunk_size = totalSize - total_written;
495 }
496
497 // Make sure (total_written - total_read) + wchunk_size
498 // is less than maxOutstanding
499 if (maxOutstanding > 0 &&
500 wchunk_size > maxOutstanding - (total_written - total_read)) {
501 wchunk_size = maxOutstanding - (total_written - total_read);
502 }
503
504 // Write the chunk
505 uint32_t chunk_written = 0;
506 while (chunk_written < wchunk_size) {
507 uint32_t write_size = wSizeGenerator.nextSize();
508 if (write_size == 0 || write_size > wchunk_size - chunk_written) {
509 write_size = wchunk_size - chunk_written;
510 }
511
512 transports.out->write(wbuf.get() + total_written, write_size);
513 chunk_written += write_size;
514 total_written += write_size;
515 }
516
517 // Flush the data, so it will be available in the read transport
518 // Don't flush if wchunk_size is 0. (This should only happen if
519 // total_written == totalSize already, and we're only reading now.)
520 if (wchunk_size > 0) {
521 transports.out->flush();
522 }
523
524 // Determine how large a chunk of data to read back
525 uint32_t rchunk_size = rChunkGenerator.nextSize();
526 if (rchunk_size == 0 || rchunk_size > total_written - total_read) {
527 rchunk_size = total_written - total_read;
528 }
529
530 // Read the chunk
531 uint32_t chunk_read = 0;
532 while (chunk_read < rchunk_size) {
533 uint32_t read_size = rSizeGenerator.nextSize();
534 if (read_size == 0 || read_size > rchunk_size - chunk_read) {
535 read_size = rchunk_size - chunk_read;
536 }
537
David Reisse94fa332010-10-06 17:10:26 +0000538 int bytes_read = -1;
539 try {
540 bytes_read = transports.in->read(rbuf.get() + total_read, read_size);
541 } catch (TTransportException& e) {
542 BOOST_FAIL("read(pos=" << total_read << ", size=" << read_size <<
543 ") threw exception \"" << e.what() <<
544 "\"; written so far: " << total_written << " / " <<
545 totalSize << " bytes");
546 }
547
David Reiss35dc7692010-10-06 17:10:19 +0000548 BOOST_REQUIRE_MESSAGE(bytes_read > 0,
549 "read(pos=" << total_read << ", size=" <<
550 read_size << ") returned " << bytes_read <<
551 "; written so far: " << total_written << " / " <<
552 totalSize << " bytes");
553 chunk_read += bytes_read;
554 total_read += bytes_read;
555 }
556 }
557
558 // make sure the data read back is identical to the data written
559 BOOST_CHECK_EQUAL(memcmp(rbuf.get(), wbuf.get(), totalSize), 0);
560}
561
David Reisse5c435c2010-10-06 17:10:38 +0000562template <class CoupledTransports>
563void test_read_part_available() {
564 CoupledTransports transports;
565 BOOST_REQUIRE(transports.in != NULL);
566 BOOST_REQUIRE(transports.out != NULL);
567
568 uint8_t write_buf[16];
569 uint8_t read_buf[16];
570 memset(write_buf, 'a', sizeof(write_buf));
571
572 // Attemping to read 10 bytes when only 9 are available should return 9
573 // immediately.
574 transports.out->write(write_buf, 9);
575 transports.out->flush();
576 set_trigger(3, transports.out, 1);
577 uint32_t bytes_read = transports.in->read(read_buf, 10);
578 BOOST_CHECK_EQUAL(numTriggersFired, 0);
579 BOOST_CHECK_EQUAL(bytes_read, 9);
580
581 clear_triggers();
582}
583
584template <class CoupledTransports>
David Reiss0a2d81e2010-10-06 17:10:40 +0000585void test_read_partial_midframe() {
586 CoupledTransports transports;
587 BOOST_REQUIRE(transports.in != NULL);
588 BOOST_REQUIRE(transports.out != NULL);
589
590 uint8_t write_buf[16];
591 uint8_t read_buf[16];
592 memset(write_buf, 'a', sizeof(write_buf));
593
594 // Attempt to read 10 bytes, when only 9 are available, but after we have
595 // already read part of the data that is available. This exercises a
596 // different code path for several of the transports.
597 //
598 // For transports that add their own framing (e.g., TFramedTransport and
599 // TFileTransport), the two flush calls break up the data in to a 10 byte
600 // frame and a 3 byte frame. The first read then puts us partway through the
601 // first frame, and then we attempt to read past the end of that frame, and
602 // through the next frame, too.
603 //
604 // For buffered transports that perform read-ahead (e.g.,
605 // TBufferedTransport), the read-ahead will most likely see all 13 bytes
606 // written on the first read. The next read will then attempt to read past
607 // the end of the read-ahead buffer.
608 //
609 // Flush 10 bytes, then 3 bytes. This creates 2 separate frames for
610 // transports that track framing internally.
611 transports.out->write(write_buf, 10);
612 transports.out->flush();
613 transports.out->write(write_buf, 3);
614 transports.out->flush();
615
616 // Now read 4 bytes, so that we are partway through the written data.
617 uint32_t bytes_read = transports.in->read(read_buf, 4);
618 BOOST_CHECK_EQUAL(bytes_read, 4);
619
620 // Now attempt to read 10 bytes. Only 9 more are available.
621 //
622 // We should be able to get all 9 bytes, but it might take multiple read
623 // calls, since it is valid for read() to return fewer bytes than requested.
624 // (Most transports do immediately return 9 bytes, but the framing transports
625 // tend to only return to the end of the current frame, which is 6 bytes in
626 // this case.)
627 uint32_t total_read = 0;
628 while (total_read < 9) {
629 set_trigger(3, transports.out, 1);
630 bytes_read = transports.in->read(read_buf, 10);
631 BOOST_REQUIRE_EQUAL(numTriggersFired, 0);
632 BOOST_REQUIRE_GT(bytes_read, 0);
633 total_read += bytes_read;
634 BOOST_REQUIRE_LE(total_read, 9);
635 }
636
637 BOOST_CHECK_EQUAL(total_read, 9);
638
639 clear_triggers();
640}
641
642template <class CoupledTransports>
David Reisse5c435c2010-10-06 17:10:38 +0000643void test_borrow_part_available() {
644 CoupledTransports transports;
645 BOOST_REQUIRE(transports.in != NULL);
646 BOOST_REQUIRE(transports.out != NULL);
647
648 uint8_t write_buf[16];
649 uint8_t read_buf[16];
650 memset(write_buf, 'a', sizeof(write_buf));
651
652 // Attemping to borrow 10 bytes when only 9 are available should return NULL
653 // immediately.
654 transports.out->write(write_buf, 9);
655 transports.out->flush();
656 set_trigger(3, transports.out, 1);
657 uint32_t borrow_len = 10;
658 const uint8_t* borrowed_buf = transports.in->borrow(read_buf, &borrow_len);
659 BOOST_CHECK_EQUAL(numTriggersFired, 0);
660 BOOST_CHECK(borrowed_buf == NULL);
661
662 clear_triggers();
663}
664
665template <class CoupledTransports>
666void test_read_none_available() {
667 CoupledTransports transports;
668 BOOST_REQUIRE(transports.in != NULL);
669 BOOST_REQUIRE(transports.out != NULL);
670
671 uint8_t write_buf[16];
672 uint8_t read_buf[16];
673 memset(write_buf, 'a', sizeof(write_buf));
674
675 // Attempting to read when no data is available should either block until
676 // some data is available, or fail immediately. (e.g., TSocket blocks,
677 // TMemoryBuffer just fails.)
678 //
679 // If the transport blocks, it should succeed once some data is available,
680 // even if less than the amount requested becomes available.
681 set_trigger(1, transports.out, 2);
682 add_trigger(1, transports.out, 8);
683 uint32_t bytes_read = transports.in->read(read_buf, 10);
684 if (bytes_read == 0) {
685 BOOST_CHECK_EQUAL(numTriggersFired, 0);
686 clear_triggers();
687 } else {
688 BOOST_CHECK_EQUAL(numTriggersFired, 1);
689 BOOST_CHECK_EQUAL(bytes_read, 2);
690 }
691
692 clear_triggers();
693}
694
695template <class CoupledTransports>
696void test_borrow_none_available() {
697 CoupledTransports transports;
698 BOOST_REQUIRE(transports.in != NULL);
699 BOOST_REQUIRE(transports.out != NULL);
700
701 uint8_t write_buf[16];
702 memset(write_buf, 'a', sizeof(write_buf));
703
704 // Attempting to borrow when no data is available should fail immediately
705 set_trigger(1, transports.out, 10);
706 uint32_t borrow_len = 10;
707 const uint8_t* borrowed_buf = transports.in->borrow(NULL, &borrow_len);
708 BOOST_CHECK(borrowed_buf == NULL);
709 BOOST_CHECK_EQUAL(numTriggersFired, 0);
710
711 clear_triggers();
712}
713
David Reiss35dc7692010-10-06 17:10:19 +0000714/**************************************************************************
715 * Test case generation
716 *
717 * Pretty ugly and annoying. This would be much easier if we the unit test
718 * framework didn't force each test to be a separate function.
719 * - Writing a completely separate function definition for each of these would
720 * result in a lot of repetitive boilerplate code.
721 * - Combining many tests into a single function makes it more difficult to
722 * tell precisely which tests failed. It also means you can't get a progress
723 * update after each test, and the tests are already fairly slow.
724 * - Similar registration could be acheived with BOOST_TEST_CASE_TEMPLATE,
725 * but it requires a lot of awkward MPL code, and results in useless test
726 * case names. (The names are generated from std::type_info::name(), which
727 * is compiler-dependent. gcc returns mangled names.)
728 **************************************************************************/
729
David Reisse5c435c2010-10-06 17:10:38 +0000730#define ADD_TEST_RW(CoupledTransports, totalSize, ...) \
731 addTestRW< CoupledTransports >(BOOST_STRINGIZE(CoupledTransports), \
732 totalSize, ## __VA_ARGS__);
David Reissd4788df2010-10-06 17:10:37 +0000733
David Reiss35dc7692010-10-06 17:10:19 +0000734#define TEST_RW(CoupledTransports, totalSize, ...) \
735 do { \
736 /* Add the test as specified, to test the non-virtual function calls */ \
David Reisse5c435c2010-10-06 17:10:38 +0000737 ADD_TEST_RW(CoupledTransports, totalSize, ## __VA_ARGS__); \
David Reiss35dc7692010-10-06 17:10:19 +0000738 /* \
739 * Also test using the transport as a TTransport*, to test \
740 * the read_virt()/write_virt() calls \
741 */ \
David Reisse5c435c2010-10-06 17:10:38 +0000742 ADD_TEST_RW(CoupledTTransports<CoupledTransports>, \
743 totalSize, ## __VA_ARGS__); \
David Reissd4788df2010-10-06 17:10:37 +0000744 /* Test wrapping the transport with TBufferedTransport */ \
David Reisse5c435c2010-10-06 17:10:38 +0000745 ADD_TEST_RW(CoupledBufferedTransportsT<CoupledTransports>, \
746 totalSize, ## __VA_ARGS__); \
David Reissd4788df2010-10-06 17:10:37 +0000747 /* Test wrapping the transport with TFramedTransports */ \
David Reisse5c435c2010-10-06 17:10:38 +0000748 ADD_TEST_RW(CoupledFramedTransportsT<CoupledTransports>, \
749 totalSize, ## __VA_ARGS__); \
David Reissd4788df2010-10-06 17:10:37 +0000750 /* Test wrapping the transport with TZlibTransport */ \
David Reisse5c435c2010-10-06 17:10:38 +0000751 ADD_TEST_RW(CoupledZlibTransportsT<CoupledTransports>, \
752 totalSize, ## __VA_ARGS__); \
David Reiss35dc7692010-10-06 17:10:19 +0000753 } while (0)
754
David Reisse5c435c2010-10-06 17:10:38 +0000755#define ADD_TEST_BLOCKING(CoupledTransports) \
756 addTestBlocking< CoupledTransports >(BOOST_STRINGIZE(CoupledTransports));
757
758#define TEST_BLOCKING_BEHAVIOR(CoupledTransports) \
759 ADD_TEST_BLOCKING(CoupledTransports); \
760 ADD_TEST_BLOCKING(CoupledTTransports<CoupledTransports>); \
761 ADD_TEST_BLOCKING(CoupledBufferedTransportsT<CoupledTransports>); \
762 ADD_TEST_BLOCKING(CoupledFramedTransportsT<CoupledTransports>); \
763 ADD_TEST_BLOCKING(CoupledZlibTransportsT<CoupledTransports>);
764
David Reiss35dc7692010-10-06 17:10:19 +0000765class TransportTestGen {
766 public:
David Reiss65e62d32010-10-06 17:10:35 +0000767 TransportTestGen(boost::unit_test::test_suite* suite,
768 float sizeMultiplier) :
769 suite_(suite),
770 sizeMultiplier_(sizeMultiplier) {}
David Reiss35dc7692010-10-06 17:10:19 +0000771
772 void generate() {
773 GenericSizeGenerator rand4k(1, 4096);
774
775 /*
776 * We do the basically the same set of tests for each transport type,
777 * although we tweak the parameters in some places.
778 */
779
David Reissd4788df2010-10-06 17:10:37 +0000780 // TMemoryBuffer tests
781 TEST_RW(CoupledMemoryBuffers, 1024*1024, 0, 0);
782 TEST_RW(CoupledMemoryBuffers, 1024*256, rand4k, rand4k);
783 TEST_RW(CoupledMemoryBuffers, 1024*256, 167, 163);
784 TEST_RW(CoupledMemoryBuffers, 1024*16, 1, 1);
David Reiss35dc7692010-10-06 17:10:19 +0000785
David Reissd4788df2010-10-06 17:10:37 +0000786 TEST_RW(CoupledMemoryBuffers, 1024*256, 0, 0, rand4k, rand4k);
787 TEST_RW(CoupledMemoryBuffers, 1024*256, rand4k, rand4k, rand4k, rand4k);
788 TEST_RW(CoupledMemoryBuffers, 1024*256, 167, 163, rand4k, rand4k);
789 TEST_RW(CoupledMemoryBuffers, 1024*16, 1, 1, rand4k, rand4k);
David Reisse94fa332010-10-06 17:10:26 +0000790
David Reisse5c435c2010-10-06 17:10:38 +0000791 TEST_BLOCKING_BEHAVIOR(CoupledMemoryBuffers);
792
David Reiss35dc7692010-10-06 17:10:19 +0000793 // TFDTransport tests
794 // Since CoupledFDTransports tests with a pipe, writes will block
795 // if there is too much outstanding unread data in the pipe.
796 uint32_t fd_max_outstanding = 4096;
David Reiss65e62d32010-10-06 17:10:35 +0000797 TEST_RW(CoupledFDTransports, 1024*1024, 0, 0,
David Reiss35dc7692010-10-06 17:10:19 +0000798 0, 0, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000799 TEST_RW(CoupledFDTransports, 1024*256, rand4k, rand4k,
David Reiss35dc7692010-10-06 17:10:19 +0000800 0, 0, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000801 TEST_RW(CoupledFDTransports, 1024*256, 167, 163,
David Reiss35dc7692010-10-06 17:10:19 +0000802 0, 0, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000803 TEST_RW(CoupledFDTransports, 1024*16, 1, 1,
David Reiss35dc7692010-10-06 17:10:19 +0000804 0, 0, fd_max_outstanding);
805
David Reiss65e62d32010-10-06 17:10:35 +0000806 TEST_RW(CoupledFDTransports, 1024*256, 0, 0,
David Reiss35dc7692010-10-06 17:10:19 +0000807 rand4k, rand4k, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000808 TEST_RW(CoupledFDTransports, 1024*256, rand4k, rand4k,
David Reiss35dc7692010-10-06 17:10:19 +0000809 rand4k, rand4k, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000810 TEST_RW(CoupledFDTransports, 1024*256, 167, 163,
David Reiss35dc7692010-10-06 17:10:19 +0000811 rand4k, rand4k, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000812 TEST_RW(CoupledFDTransports, 1024*16, 1, 1,
David Reiss35dc7692010-10-06 17:10:19 +0000813 rand4k, rand4k, fd_max_outstanding);
814
David Reisse5c435c2010-10-06 17:10:38 +0000815 TEST_BLOCKING_BEHAVIOR(CoupledFDTransports);
816
David Reiss0c025e82010-10-06 17:10:36 +0000817 // TSocket tests
818 uint32_t socket_max_outstanding = 4096;
819 TEST_RW(CoupledSocketTransports, 1024*1024, 0, 0,
820 0, 0, socket_max_outstanding);
821 TEST_RW(CoupledSocketTransports, 1024*256, rand4k, rand4k,
822 0, 0, socket_max_outstanding);
823 TEST_RW(CoupledSocketTransports, 1024*256, 167, 163,
824 0, 0, socket_max_outstanding);
825 // Doh. Apparently writing to a socket has some additional overhead for
826 // each send() call. If we have more than ~400 outstanding 1-byte write
827 // requests, additional send() calls start blocking.
828 TEST_RW(CoupledSocketTransports, 1024*16, 1, 1,
829 0, 0, 400);
830 TEST_RW(CoupledSocketTransports, 1024*256, 0, 0,
831 rand4k, rand4k, socket_max_outstanding);
832 TEST_RW(CoupledSocketTransports, 1024*256, rand4k, rand4k,
833 rand4k, rand4k, socket_max_outstanding);
834 TEST_RW(CoupledSocketTransports, 1024*256, 167, 163,
835 rand4k, rand4k, socket_max_outstanding);
836 TEST_RW(CoupledSocketTransports, 1024*16, 1, 1,
837 rand4k, rand4k, 400);
838
David Reisse5c435c2010-10-06 17:10:38 +0000839 TEST_BLOCKING_BEHAVIOR(CoupledSocketTransports);
840
David Reiss35dc7692010-10-06 17:10:19 +0000841 // TFileTransport tests
842 // We use smaller buffer sizes here, since TFileTransport is fairly slow.
843 //
844 // TFileTransport can't write more than 16MB at once
845 uint32_t max_write_at_once = 1024*1024*16 - 4;
David Reiss65e62d32010-10-06 17:10:35 +0000846 TEST_RW(CoupledFileTransports, 1024*1024, max_write_at_once, 0);
847 TEST_RW(CoupledFileTransports, 1024*128, rand4k, rand4k);
848 TEST_RW(CoupledFileTransports, 1024*128, 167, 163);
849 TEST_RW(CoupledFileTransports, 1024*2, 1, 1);
David Reiss35dc7692010-10-06 17:10:19 +0000850
David Reiss65e62d32010-10-06 17:10:35 +0000851 TEST_RW(CoupledFileTransports, 1024*64, 0, 0, rand4k, rand4k);
852 TEST_RW(CoupledFileTransports, 1024*64,
David Reiss35dc7692010-10-06 17:10:19 +0000853 rand4k, rand4k, rand4k, rand4k);
David Reiss65e62d32010-10-06 17:10:35 +0000854 TEST_RW(CoupledFileTransports, 1024*64, 167, 163, rand4k, rand4k);
855 TEST_RW(CoupledFileTransports, 1024*2, 1, 1, rand4k, rand4k);
David Reissd4788df2010-10-06 17:10:37 +0000856
David Reisse5c435c2010-10-06 17:10:38 +0000857 TEST_BLOCKING_BEHAVIOR(CoupledFileTransports);
858
David Reissd4788df2010-10-06 17:10:37 +0000859 // Add some tests that access TBufferedTransport and TFramedTransport
860 // via TTransport pointers and TBufferBase pointers.
David Reisse5c435c2010-10-06 17:10:38 +0000861 ADD_TEST_RW(CoupledTTransports<CoupledBufferedTransports>,
862 1024*1024, rand4k, rand4k, rand4k, rand4k);
863 ADD_TEST_RW(CoupledBufferBases<CoupledBufferedTransports>,
864 1024*1024, rand4k, rand4k, rand4k, rand4k);
865 ADD_TEST_RW(CoupledTTransports<CoupledFramedTransports>,
866 1024*1024, rand4k, rand4k, rand4k, rand4k);
867 ADD_TEST_RW(CoupledBufferBases<CoupledFramedTransports>,
868 1024*1024, rand4k, rand4k, rand4k, rand4k);
David Reissd4788df2010-10-06 17:10:37 +0000869
870 // Test using TZlibTransport via a TTransport pointer
David Reisse5c435c2010-10-06 17:10:38 +0000871 ADD_TEST_RW(CoupledTTransports<CoupledZlibTransports>,
872 1024*1024, rand4k, rand4k, rand4k, rand4k);
David Reiss35dc7692010-10-06 17:10:19 +0000873 }
874
875 private:
876 template <class CoupledTransports>
David Reisse5c435c2010-10-06 17:10:38 +0000877 void addTestRW(const char* transport_name, uint32_t totalSize,
878 GenericSizeGenerator wSizeGen, GenericSizeGenerator rSizeGen,
879 GenericSizeGenerator wChunkSizeGen = 0,
880 GenericSizeGenerator rChunkSizeGen = 0,
881 uint32_t maxOutstanding = 0,
882 uint32_t expectedFailures = 0) {
David Reiss65e62d32010-10-06 17:10:35 +0000883 // adjust totalSize by the specified sizeMultiplier_ first
884 totalSize = static_cast<uint32_t>(totalSize * sizeMultiplier_);
885
David Reiss35dc7692010-10-06 17:10:19 +0000886 std::ostringstream name;
887 name << transport_name << "::test_rw(" << totalSize << ", " <<
888 wSizeGen.describe() << ", " << rSizeGen.describe() << ", " <<
889 wChunkSizeGen.describe() << ", " << rChunkSizeGen.describe() << ", " <<
890 maxOutstanding << ")";
891
892 boost::unit_test::callback0<> test_func =
893 std::tr1::bind(test_rw<CoupledTransports>, totalSize,
894 wSizeGen, rSizeGen, wChunkSizeGen, rChunkSizeGen,
895 maxOutstanding);
896 boost::unit_test::test_case* tc =
897 boost::unit_test::make_test_case(test_func, name.str());
898 suite_->add(tc, expectedFailures);
Roger Meier0069cc42010-10-13 18:10:18 +0000899 }
David Reiss35dc7692010-10-06 17:10:19 +0000900
David Reisse5c435c2010-10-06 17:10:38 +0000901 template <class CoupledTransports>
902 void addTestBlocking(const char* transportName,
903 uint32_t expectedFailures = 0) {
904 char name[1024];
905 boost::unit_test::test_case* tc;
906
907 snprintf(name, sizeof(name), "%s::test_read_part_available()",
908 transportName);
909 tc = boost::unit_test::make_test_case(
910 test_read_part_available<CoupledTransports>, name);
911 suite_->add(tc, expectedFailures);
912
David Reiss0a2d81e2010-10-06 17:10:40 +0000913 snprintf(name, sizeof(name), "%s::test_read_partial_midframe()",
914 transportName);
915 tc = boost::unit_test::make_test_case(
916 test_read_partial_midframe<CoupledTransports>, name);
917 suite_->add(tc, expectedFailures);
918
David Reisse5c435c2010-10-06 17:10:38 +0000919 snprintf(name, sizeof(name), "%s::test_read_none_available()",
920 transportName);
921 tc = boost::unit_test::make_test_case(
922 test_read_none_available<CoupledTransports>, name);
923 suite_->add(tc, expectedFailures);
924
925 snprintf(name, sizeof(name), "%s::test_borrow_part_available()",
926 transportName);
927 tc = boost::unit_test::make_test_case(
928 test_borrow_part_available<CoupledTransports>, name);
929 suite_->add(tc, expectedFailures);
930
931 snprintf(name, sizeof(name), "%s::test_borrow_none_available()",
932 transportName);
933 tc = boost::unit_test::make_test_case(
934 test_borrow_none_available<CoupledTransports>, name);
935 suite_->add(tc, expectedFailures);
936 }
937
David Reiss35dc7692010-10-06 17:10:19 +0000938 boost::unit_test::test_suite* suite_;
David Reiss65e62d32010-10-06 17:10:35 +0000939 // sizeMultiplier_ is configurable via the command line, and allows the
940 // user to adjust between smaller buffers that can be tested quickly,
941 // or larger buffers that more thoroughly exercise the code, but take
942 // longer.
943 float sizeMultiplier_;
David Reiss35dc7692010-10-06 17:10:19 +0000944};
945
946/**************************************************************************
947 * General Initialization
948 **************************************************************************/
949
950void print_usage(FILE* f, const char* argv0) {
951 fprintf(f, "Usage: %s [boost_options] [options]\n", argv0);
952 fprintf(f, "Options:\n");
953 fprintf(f, " --seed=<N>, -s <N>\n");
954 fprintf(f, " --tmp-dir=DIR, -t DIR\n");
955 fprintf(f, " --help\n");
956}
957
David Reiss65e62d32010-10-06 17:10:35 +0000958struct Options {
David Reiss35dc7692010-10-06 17:10:19 +0000959 int seed;
David Reiss65e62d32010-10-06 17:10:35 +0000960 bool haveSeed;
961 float sizeMultiplier;
962};
963
964void parse_args(int argc, char* argv[], Options* options) {
965 bool have_seed = false;
966 options->sizeMultiplier = 1;
David Reiss35dc7692010-10-06 17:10:19 +0000967
968 struct option long_opts[] = {
969 { "help", false, NULL, 'h' },
970 { "seed", true, NULL, 's' },
971 { "tmp-dir", true, NULL, 't' },
David Reiss65e62d32010-10-06 17:10:35 +0000972 { "size-multiplier", true, NULL, 'x' },
David Reiss35dc7692010-10-06 17:10:19 +0000973 { NULL, 0, NULL, 0 }
974 };
975
976 while (true) {
977 optopt = 1;
David Reiss65e62d32010-10-06 17:10:35 +0000978 int optchar = getopt_long(argc, argv, "hs:t:x:", long_opts, NULL);
David Reiss35dc7692010-10-06 17:10:19 +0000979 if (optchar == -1) {
980 break;
981 }
982
983 switch (optchar) {
984 case 't':
985 tmp_dir = optarg;
986 break;
987 case 's': {
988 char *endptr;
David Reiss65e62d32010-10-06 17:10:35 +0000989 options->seed = strtol(optarg, &endptr, 0);
David Reiss35dc7692010-10-06 17:10:19 +0000990 if (endptr == optarg || *endptr != '\0') {
991 fprintf(stderr, "invalid seed value \"%s\": must be an integer\n",
992 optarg);
993 exit(1);
994 }
David Reiss65e62d32010-10-06 17:10:35 +0000995 have_seed = true;
David Reiss35dc7692010-10-06 17:10:19 +0000996 break;
997 }
998 case 'h':
999 print_usage(stdout, argv[0]);
1000 exit(0);
David Reiss65e62d32010-10-06 17:10:35 +00001001 case 'x': {
1002 char *endptr;
1003 options->sizeMultiplier = strtof(optarg, &endptr);
1004 if (endptr == optarg || *endptr != '\0') {
1005 fprintf(stderr, "invalid size multiplier \"%s\": must be a number\n",
1006 optarg);
1007 exit(1);
1008 }
1009 if (options->sizeMultiplier < 0) {
1010 fprintf(stderr, "invalid size multiplier \"%s\": "
1011 "must be non-negative\n", optarg);
1012 exit(1);
1013 }
1014 break;
1015 }
David Reiss35dc7692010-10-06 17:10:19 +00001016 case '?':
1017 exit(1);
1018 default:
1019 // Only happens if someone adds another option to the optarg string,
1020 // but doesn't update the switch statement to handle it.
1021 fprintf(stderr, "unknown option \"-%c\"\n", optchar);
1022 exit(1);
1023 }
1024 }
1025
David Reiss65e62d32010-10-06 17:10:35 +00001026 if (!have_seed) {
1027 // choose a seed now if the user didn't specify one
1028 struct timespec t;
1029 clock_gettime(CLOCK_REALTIME, &t);
1030 options->seed = t.tv_sec + t.tv_nsec;
1031 }
David Reiss35dc7692010-10-06 17:10:19 +00001032}
1033
1034boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
1035 // Parse arguments
David Reiss65e62d32010-10-06 17:10:35 +00001036 Options options;
1037 parse_args(argc, argv, &options);
1038
1039 initrand(options.seed);
David Reiss35dc7692010-10-06 17:10:19 +00001040
David Reiss109693c2010-10-06 17:10:42 +00001041 boost::unit_test::test_suite* suite =
1042 &boost::unit_test::framework::master_test_suite();
1043 suite->p_name.value = "TransportTest";
David Reiss65e62d32010-10-06 17:10:35 +00001044 TransportTestGen transport_test_generator(suite, options.sizeMultiplier);
David Reiss35dc7692010-10-06 17:10:19 +00001045 transport_test_generator.generate();
1046
David Reiss109693c2010-10-06 17:10:42 +00001047 return NULL;
David Reiss35dc7692010-10-06 17:10:19 +00001048}