blob: dceb708d3839f75bd4a3049a066382c471e03c09 [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.
363 uint8_t buf[info->writeLength];
364 memset(buf, 'b', info->writeLength);
365 info->transport->write(buf, info->writeLength);
366 info->transport->flush();
367
368 delete info;
369}
370
371void set_alarm() {
372 if (triggerInfo == NULL) {
373 // clear any alarm
374 alarm(0);
375 return;
376 }
377
378 struct sigaction action;
379 memset(&action, 0, sizeof(action));
380 action.sa_handler = alarm_handler;
381 action.sa_flags = SA_ONESHOT;
382 sigemptyset(&action.sa_mask);
383 sigaction(SIGALRM, &action, NULL);
384
385 alarm(triggerInfo->timeoutSeconds);
386}
387
388/**
389 * Add a trigger to be scheduled "seconds" seconds after the
390 * last currently scheduled trigger.
391 *
392 * (Note that this is not "seconds" from now. That might be more logical, but
393 * would require slightly more complicated sorting, rather than just appending
394 * to the end.)
395 */
396void add_trigger(unsigned int seconds,
397 const boost::shared_ptr<TTransport> &transport,
398 uint32_t write_len) {
399 TriggerInfo* info = new TriggerInfo(seconds, transport, write_len);
400
401 if (triggerInfo == NULL) {
402 // This is the first trigger.
403 // Set triggerInfo, and schedule the alarm
404 triggerInfo = info;
405 set_alarm();
406 } else {
407 // Add this trigger to the end of the list
408 TriggerInfo* prev = triggerInfo;
409 while (prev->next) {
410 prev = prev->next;
411 }
412
413 prev->next = info;
414 }
415}
416
417void clear_triggers() {
418 TriggerInfo *info = triggerInfo;
419 alarm(0);
420 triggerInfo = NULL;
421 numTriggersFired = 0;
422
423 while (info != NULL) {
424 TriggerInfo* next = info->next;
425 delete info;
426 info = next;
427 }
428}
429
430void set_trigger(unsigned int seconds,
431 const boost::shared_ptr<TTransport> &transport,
432 uint32_t write_len) {
433 clear_triggers();
434 add_trigger(seconds, transport, write_len);
435}
436
437/**************************************************************************
438 * Test functions
David Reiss35dc7692010-10-06 17:10:19 +0000439 **************************************************************************/
440
441/**
442 * Test interleaved write and read calls.
443 *
444 * Generates a buffer totalSize bytes long, then writes it to the transport,
445 * and verifies the written data can be read back correctly.
446 *
447 * Mode of operation:
448 * - call wChunkGenerator to figure out how large of a chunk to write
449 * - call wSizeGenerator to get the size for individual write() calls,
450 * and do this repeatedly until the entire chunk is written.
451 * - call rChunkGenerator to figure out how large of a chunk to read
452 * - call rSizeGenerator to get the size for individual read() calls,
453 * and do this repeatedly until the entire chunk is read.
454 * - repeat until the full buffer is written and read back,
455 * then compare the data read back against the original buffer
456 *
457 *
458 * - If any of the size generators return 0, this means to use the maximum
459 * possible size.
460 *
461 * - If maxOutstanding is non-zero, write chunk sizes will be chosen such that
462 * there are never more than maxOutstanding bytes waiting to be read back.
463 */
464template <class CoupledTransports>
465void test_rw(uint32_t totalSize,
466 SizeGenerator& wSizeGenerator,
467 SizeGenerator& rSizeGenerator,
468 SizeGenerator& wChunkGenerator,
469 SizeGenerator& rChunkGenerator,
470 uint32_t maxOutstanding) {
471 CoupledTransports transports;
472 BOOST_REQUIRE(transports.in != NULL);
473 BOOST_REQUIRE(transports.out != NULL);
474
475 boost::shared_array<uint8_t> wbuf =
476 boost::shared_array<uint8_t>(new uint8_t[totalSize]);
477 boost::shared_array<uint8_t> rbuf =
478 boost::shared_array<uint8_t>(new uint8_t[totalSize]);
479
480 // store some data in wbuf
481 for (uint32_t n = 0; n < totalSize; ++n) {
482 wbuf[n] = (n & 0xff);
483 }
484 // clear rbuf
485 memset(rbuf.get(), 0, totalSize);
486
487 uint32_t total_written = 0;
488 uint32_t total_read = 0;
489 while (total_read < totalSize) {
490 // Determine how large a chunk of data to write
491 uint32_t wchunk_size = wChunkGenerator.nextSize();
492 if (wchunk_size == 0 || wchunk_size > totalSize - total_written) {
493 wchunk_size = totalSize - total_written;
494 }
495
496 // Make sure (total_written - total_read) + wchunk_size
497 // is less than maxOutstanding
498 if (maxOutstanding > 0 &&
499 wchunk_size > maxOutstanding - (total_written - total_read)) {
500 wchunk_size = maxOutstanding - (total_written - total_read);
501 }
502
503 // Write the chunk
504 uint32_t chunk_written = 0;
505 while (chunk_written < wchunk_size) {
506 uint32_t write_size = wSizeGenerator.nextSize();
507 if (write_size == 0 || write_size > wchunk_size - chunk_written) {
508 write_size = wchunk_size - chunk_written;
509 }
510
511 transports.out->write(wbuf.get() + total_written, write_size);
512 chunk_written += write_size;
513 total_written += write_size;
514 }
515
516 // Flush the data, so it will be available in the read transport
517 // Don't flush if wchunk_size is 0. (This should only happen if
518 // total_written == totalSize already, and we're only reading now.)
519 if (wchunk_size > 0) {
520 transports.out->flush();
521 }
522
523 // Determine how large a chunk of data to read back
524 uint32_t rchunk_size = rChunkGenerator.nextSize();
525 if (rchunk_size == 0 || rchunk_size > total_written - total_read) {
526 rchunk_size = total_written - total_read;
527 }
528
529 // Read the chunk
530 uint32_t chunk_read = 0;
531 while (chunk_read < rchunk_size) {
532 uint32_t read_size = rSizeGenerator.nextSize();
533 if (read_size == 0 || read_size > rchunk_size - chunk_read) {
534 read_size = rchunk_size - chunk_read;
535 }
536
David Reisse94fa332010-10-06 17:10:26 +0000537 int bytes_read = -1;
538 try {
539 bytes_read = transports.in->read(rbuf.get() + total_read, read_size);
540 } catch (TTransportException& e) {
541 BOOST_FAIL("read(pos=" << total_read << ", size=" << read_size <<
542 ") threw exception \"" << e.what() <<
543 "\"; written so far: " << total_written << " / " <<
544 totalSize << " bytes");
545 }
546
David Reiss35dc7692010-10-06 17:10:19 +0000547 BOOST_REQUIRE_MESSAGE(bytes_read > 0,
548 "read(pos=" << total_read << ", size=" <<
549 read_size << ") returned " << bytes_read <<
550 "; written so far: " << total_written << " / " <<
551 totalSize << " bytes");
552 chunk_read += bytes_read;
553 total_read += bytes_read;
554 }
555 }
556
557 // make sure the data read back is identical to the data written
558 BOOST_CHECK_EQUAL(memcmp(rbuf.get(), wbuf.get(), totalSize), 0);
559}
560
David Reisse5c435c2010-10-06 17:10:38 +0000561template <class CoupledTransports>
562void test_read_part_available() {
563 CoupledTransports transports;
564 BOOST_REQUIRE(transports.in != NULL);
565 BOOST_REQUIRE(transports.out != NULL);
566
567 uint8_t write_buf[16];
568 uint8_t read_buf[16];
569 memset(write_buf, 'a', sizeof(write_buf));
570
571 // Attemping to read 10 bytes when only 9 are available should return 9
572 // immediately.
573 transports.out->write(write_buf, 9);
574 transports.out->flush();
575 set_trigger(3, transports.out, 1);
576 uint32_t bytes_read = transports.in->read(read_buf, 10);
577 BOOST_CHECK_EQUAL(numTriggersFired, 0);
578 BOOST_CHECK_EQUAL(bytes_read, 9);
579
580 clear_triggers();
581}
582
583template <class CoupledTransports>
David Reiss0a2d81e2010-10-06 17:10:40 +0000584void test_read_partial_midframe() {
585 CoupledTransports transports;
586 BOOST_REQUIRE(transports.in != NULL);
587 BOOST_REQUIRE(transports.out != NULL);
588
589 uint8_t write_buf[16];
590 uint8_t read_buf[16];
591 memset(write_buf, 'a', sizeof(write_buf));
592
593 // Attempt to read 10 bytes, when only 9 are available, but after we have
594 // already read part of the data that is available. This exercises a
595 // different code path for several of the transports.
596 //
597 // For transports that add their own framing (e.g., TFramedTransport and
598 // TFileTransport), the two flush calls break up the data in to a 10 byte
599 // frame and a 3 byte frame. The first read then puts us partway through the
600 // first frame, and then we attempt to read past the end of that frame, and
601 // through the next frame, too.
602 //
603 // For buffered transports that perform read-ahead (e.g.,
604 // TBufferedTransport), the read-ahead will most likely see all 13 bytes
605 // written on the first read. The next read will then attempt to read past
606 // the end of the read-ahead buffer.
607 //
608 // Flush 10 bytes, then 3 bytes. This creates 2 separate frames for
609 // transports that track framing internally.
610 transports.out->write(write_buf, 10);
611 transports.out->flush();
612 transports.out->write(write_buf, 3);
613 transports.out->flush();
614
615 // Now read 4 bytes, so that we are partway through the written data.
616 uint32_t bytes_read = transports.in->read(read_buf, 4);
617 BOOST_CHECK_EQUAL(bytes_read, 4);
618
619 // Now attempt to read 10 bytes. Only 9 more are available.
620 //
621 // We should be able to get all 9 bytes, but it might take multiple read
622 // calls, since it is valid for read() to return fewer bytes than requested.
623 // (Most transports do immediately return 9 bytes, but the framing transports
624 // tend to only return to the end of the current frame, which is 6 bytes in
625 // this case.)
626 uint32_t total_read = 0;
627 while (total_read < 9) {
628 set_trigger(3, transports.out, 1);
629 bytes_read = transports.in->read(read_buf, 10);
630 BOOST_REQUIRE_EQUAL(numTriggersFired, 0);
631 BOOST_REQUIRE_GT(bytes_read, 0);
632 total_read += bytes_read;
633 BOOST_REQUIRE_LE(total_read, 9);
634 }
635
636 BOOST_CHECK_EQUAL(total_read, 9);
637
638 clear_triggers();
639}
640
641template <class CoupledTransports>
David Reisse5c435c2010-10-06 17:10:38 +0000642void test_borrow_part_available() {
643 CoupledTransports transports;
644 BOOST_REQUIRE(transports.in != NULL);
645 BOOST_REQUIRE(transports.out != NULL);
646
647 uint8_t write_buf[16];
648 uint8_t read_buf[16];
649 memset(write_buf, 'a', sizeof(write_buf));
650
651 // Attemping to borrow 10 bytes when only 9 are available should return NULL
652 // immediately.
653 transports.out->write(write_buf, 9);
654 transports.out->flush();
655 set_trigger(3, transports.out, 1);
656 uint32_t borrow_len = 10;
657 const uint8_t* borrowed_buf = transports.in->borrow(read_buf, &borrow_len);
658 BOOST_CHECK_EQUAL(numTriggersFired, 0);
659 BOOST_CHECK(borrowed_buf == NULL);
660
661 clear_triggers();
662}
663
664template <class CoupledTransports>
665void test_read_none_available() {
666 CoupledTransports transports;
667 BOOST_REQUIRE(transports.in != NULL);
668 BOOST_REQUIRE(transports.out != NULL);
669
670 uint8_t write_buf[16];
671 uint8_t read_buf[16];
672 memset(write_buf, 'a', sizeof(write_buf));
673
674 // Attempting to read when no data is available should either block until
675 // some data is available, or fail immediately. (e.g., TSocket blocks,
676 // TMemoryBuffer just fails.)
677 //
678 // If the transport blocks, it should succeed once some data is available,
679 // even if less than the amount requested becomes available.
680 set_trigger(1, transports.out, 2);
681 add_trigger(1, transports.out, 8);
682 uint32_t bytes_read = transports.in->read(read_buf, 10);
683 if (bytes_read == 0) {
684 BOOST_CHECK_EQUAL(numTriggersFired, 0);
685 clear_triggers();
686 } else {
687 BOOST_CHECK_EQUAL(numTriggersFired, 1);
688 BOOST_CHECK_EQUAL(bytes_read, 2);
689 }
690
691 clear_triggers();
692}
693
694template <class CoupledTransports>
695void test_borrow_none_available() {
696 CoupledTransports transports;
697 BOOST_REQUIRE(transports.in != NULL);
698 BOOST_REQUIRE(transports.out != NULL);
699
700 uint8_t write_buf[16];
701 memset(write_buf, 'a', sizeof(write_buf));
702
703 // Attempting to borrow when no data is available should fail immediately
704 set_trigger(1, transports.out, 10);
705 uint32_t borrow_len = 10;
706 const uint8_t* borrowed_buf = transports.in->borrow(NULL, &borrow_len);
707 BOOST_CHECK(borrowed_buf == NULL);
708 BOOST_CHECK_EQUAL(numTriggersFired, 0);
709
710 clear_triggers();
711}
712
David Reiss35dc7692010-10-06 17:10:19 +0000713/**************************************************************************
714 * Test case generation
715 *
716 * Pretty ugly and annoying. This would be much easier if we the unit test
717 * framework didn't force each test to be a separate function.
718 * - Writing a completely separate function definition for each of these would
719 * result in a lot of repetitive boilerplate code.
720 * - Combining many tests into a single function makes it more difficult to
721 * tell precisely which tests failed. It also means you can't get a progress
722 * update after each test, and the tests are already fairly slow.
723 * - Similar registration could be acheived with BOOST_TEST_CASE_TEMPLATE,
724 * but it requires a lot of awkward MPL code, and results in useless test
725 * case names. (The names are generated from std::type_info::name(), which
726 * is compiler-dependent. gcc returns mangled names.)
727 **************************************************************************/
728
David Reisse5c435c2010-10-06 17:10:38 +0000729#define ADD_TEST_RW(CoupledTransports, totalSize, ...) \
730 addTestRW< CoupledTransports >(BOOST_STRINGIZE(CoupledTransports), \
731 totalSize, ## __VA_ARGS__);
David Reissd4788df2010-10-06 17:10:37 +0000732
David Reiss35dc7692010-10-06 17:10:19 +0000733#define TEST_RW(CoupledTransports, totalSize, ...) \
734 do { \
735 /* Add the test as specified, to test the non-virtual function calls */ \
David Reisse5c435c2010-10-06 17:10:38 +0000736 ADD_TEST_RW(CoupledTransports, totalSize, ## __VA_ARGS__); \
David Reiss35dc7692010-10-06 17:10:19 +0000737 /* \
738 * Also test using the transport as a TTransport*, to test \
739 * the read_virt()/write_virt() calls \
740 */ \
David Reisse5c435c2010-10-06 17:10:38 +0000741 ADD_TEST_RW(CoupledTTransports<CoupledTransports>, \
742 totalSize, ## __VA_ARGS__); \
David Reissd4788df2010-10-06 17:10:37 +0000743 /* Test wrapping the transport with TBufferedTransport */ \
David Reisse5c435c2010-10-06 17:10:38 +0000744 ADD_TEST_RW(CoupledBufferedTransportsT<CoupledTransports>, \
745 totalSize, ## __VA_ARGS__); \
David Reissd4788df2010-10-06 17:10:37 +0000746 /* Test wrapping the transport with TFramedTransports */ \
David Reisse5c435c2010-10-06 17:10:38 +0000747 ADD_TEST_RW(CoupledFramedTransportsT<CoupledTransports>, \
748 totalSize, ## __VA_ARGS__); \
David Reissd4788df2010-10-06 17:10:37 +0000749 /* Test wrapping the transport with TZlibTransport */ \
David Reisse5c435c2010-10-06 17:10:38 +0000750 ADD_TEST_RW(CoupledZlibTransportsT<CoupledTransports>, \
751 totalSize, ## __VA_ARGS__); \
David Reiss35dc7692010-10-06 17:10:19 +0000752 } while (0)
753
David Reisse5c435c2010-10-06 17:10:38 +0000754#define ADD_TEST_BLOCKING(CoupledTransports) \
755 addTestBlocking< CoupledTransports >(BOOST_STRINGIZE(CoupledTransports));
756
757#define TEST_BLOCKING_BEHAVIOR(CoupledTransports) \
758 ADD_TEST_BLOCKING(CoupledTransports); \
759 ADD_TEST_BLOCKING(CoupledTTransports<CoupledTransports>); \
760 ADD_TEST_BLOCKING(CoupledBufferedTransportsT<CoupledTransports>); \
761 ADD_TEST_BLOCKING(CoupledFramedTransportsT<CoupledTransports>); \
762 ADD_TEST_BLOCKING(CoupledZlibTransportsT<CoupledTransports>);
763
David Reiss35dc7692010-10-06 17:10:19 +0000764class TransportTestGen {
765 public:
David Reiss65e62d32010-10-06 17:10:35 +0000766 TransportTestGen(boost::unit_test::test_suite* suite,
767 float sizeMultiplier) :
768 suite_(suite),
769 sizeMultiplier_(sizeMultiplier) {}
David Reiss35dc7692010-10-06 17:10:19 +0000770
771 void generate() {
772 GenericSizeGenerator rand4k(1, 4096);
773
774 /*
775 * We do the basically the same set of tests for each transport type,
776 * although we tweak the parameters in some places.
777 */
778
David Reissd4788df2010-10-06 17:10:37 +0000779 // TMemoryBuffer tests
780 TEST_RW(CoupledMemoryBuffers, 1024*1024, 0, 0);
781 TEST_RW(CoupledMemoryBuffers, 1024*256, rand4k, rand4k);
782 TEST_RW(CoupledMemoryBuffers, 1024*256, 167, 163);
783 TEST_RW(CoupledMemoryBuffers, 1024*16, 1, 1);
David Reiss35dc7692010-10-06 17:10:19 +0000784
David Reissd4788df2010-10-06 17:10:37 +0000785 TEST_RW(CoupledMemoryBuffers, 1024*256, 0, 0, rand4k, rand4k);
786 TEST_RW(CoupledMemoryBuffers, 1024*256, rand4k, rand4k, rand4k, rand4k);
787 TEST_RW(CoupledMemoryBuffers, 1024*256, 167, 163, rand4k, rand4k);
788 TEST_RW(CoupledMemoryBuffers, 1024*16, 1, 1, rand4k, rand4k);
David Reisse94fa332010-10-06 17:10:26 +0000789
David Reisse5c435c2010-10-06 17:10:38 +0000790 TEST_BLOCKING_BEHAVIOR(CoupledMemoryBuffers);
791
David Reiss35dc7692010-10-06 17:10:19 +0000792 // TFDTransport tests
793 // Since CoupledFDTransports tests with a pipe, writes will block
794 // if there is too much outstanding unread data in the pipe.
795 uint32_t fd_max_outstanding = 4096;
David Reiss65e62d32010-10-06 17:10:35 +0000796 TEST_RW(CoupledFDTransports, 1024*1024, 0, 0,
David Reiss35dc7692010-10-06 17:10:19 +0000797 0, 0, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000798 TEST_RW(CoupledFDTransports, 1024*256, rand4k, rand4k,
David Reiss35dc7692010-10-06 17:10:19 +0000799 0, 0, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000800 TEST_RW(CoupledFDTransports, 1024*256, 167, 163,
David Reiss35dc7692010-10-06 17:10:19 +0000801 0, 0, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000802 TEST_RW(CoupledFDTransports, 1024*16, 1, 1,
David Reiss35dc7692010-10-06 17:10:19 +0000803 0, 0, fd_max_outstanding);
804
David Reiss65e62d32010-10-06 17:10:35 +0000805 TEST_RW(CoupledFDTransports, 1024*256, 0, 0,
David Reiss35dc7692010-10-06 17:10:19 +0000806 rand4k, rand4k, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000807 TEST_RW(CoupledFDTransports, 1024*256, rand4k, rand4k,
David Reiss35dc7692010-10-06 17:10:19 +0000808 rand4k, rand4k, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000809 TEST_RW(CoupledFDTransports, 1024*256, 167, 163,
David Reiss35dc7692010-10-06 17:10:19 +0000810 rand4k, rand4k, fd_max_outstanding);
David Reiss65e62d32010-10-06 17:10:35 +0000811 TEST_RW(CoupledFDTransports, 1024*16, 1, 1,
David Reiss35dc7692010-10-06 17:10:19 +0000812 rand4k, rand4k, fd_max_outstanding);
813
David Reisse5c435c2010-10-06 17:10:38 +0000814 TEST_BLOCKING_BEHAVIOR(CoupledFDTransports);
815
David Reiss0c025e82010-10-06 17:10:36 +0000816 // TSocket tests
817 uint32_t socket_max_outstanding = 4096;
818 TEST_RW(CoupledSocketTransports, 1024*1024, 0, 0,
819 0, 0, socket_max_outstanding);
820 TEST_RW(CoupledSocketTransports, 1024*256, rand4k, rand4k,
821 0, 0, socket_max_outstanding);
822 TEST_RW(CoupledSocketTransports, 1024*256, 167, 163,
823 0, 0, socket_max_outstanding);
824 // Doh. Apparently writing to a socket has some additional overhead for
825 // each send() call. If we have more than ~400 outstanding 1-byte write
826 // requests, additional send() calls start blocking.
827 TEST_RW(CoupledSocketTransports, 1024*16, 1, 1,
828 0, 0, 400);
829 TEST_RW(CoupledSocketTransports, 1024*256, 0, 0,
830 rand4k, rand4k, socket_max_outstanding);
831 TEST_RW(CoupledSocketTransports, 1024*256, rand4k, rand4k,
832 rand4k, rand4k, socket_max_outstanding);
833 TEST_RW(CoupledSocketTransports, 1024*256, 167, 163,
834 rand4k, rand4k, socket_max_outstanding);
835 TEST_RW(CoupledSocketTransports, 1024*16, 1, 1,
836 rand4k, rand4k, 400);
837
David Reisse5c435c2010-10-06 17:10:38 +0000838 TEST_BLOCKING_BEHAVIOR(CoupledSocketTransports);
839
David Reiss35dc7692010-10-06 17:10:19 +0000840 // TFileTransport tests
841 // We use smaller buffer sizes here, since TFileTransport is fairly slow.
842 //
843 // TFileTransport can't write more than 16MB at once
844 uint32_t max_write_at_once = 1024*1024*16 - 4;
David Reiss65e62d32010-10-06 17:10:35 +0000845 TEST_RW(CoupledFileTransports, 1024*1024, max_write_at_once, 0);
846 TEST_RW(CoupledFileTransports, 1024*128, rand4k, rand4k);
847 TEST_RW(CoupledFileTransports, 1024*128, 167, 163);
848 TEST_RW(CoupledFileTransports, 1024*2, 1, 1);
David Reiss35dc7692010-10-06 17:10:19 +0000849
David Reiss65e62d32010-10-06 17:10:35 +0000850 TEST_RW(CoupledFileTransports, 1024*64, 0, 0, rand4k, rand4k);
851 TEST_RW(CoupledFileTransports, 1024*64,
David Reiss35dc7692010-10-06 17:10:19 +0000852 rand4k, rand4k, rand4k, rand4k);
David Reiss65e62d32010-10-06 17:10:35 +0000853 TEST_RW(CoupledFileTransports, 1024*64, 167, 163, rand4k, rand4k);
854 TEST_RW(CoupledFileTransports, 1024*2, 1, 1, rand4k, rand4k);
David Reissd4788df2010-10-06 17:10:37 +0000855
David Reisse5c435c2010-10-06 17:10:38 +0000856 TEST_BLOCKING_BEHAVIOR(CoupledFileTransports);
857
David Reissd4788df2010-10-06 17:10:37 +0000858 // Add some tests that access TBufferedTransport and TFramedTransport
859 // via TTransport pointers and TBufferBase pointers.
David Reisse5c435c2010-10-06 17:10:38 +0000860 ADD_TEST_RW(CoupledTTransports<CoupledBufferedTransports>,
861 1024*1024, rand4k, rand4k, rand4k, rand4k);
862 ADD_TEST_RW(CoupledBufferBases<CoupledBufferedTransports>,
863 1024*1024, rand4k, rand4k, rand4k, rand4k);
864 ADD_TEST_RW(CoupledTTransports<CoupledFramedTransports>,
865 1024*1024, rand4k, rand4k, rand4k, rand4k);
866 ADD_TEST_RW(CoupledBufferBases<CoupledFramedTransports>,
867 1024*1024, rand4k, rand4k, rand4k, rand4k);
David Reissd4788df2010-10-06 17:10:37 +0000868
869 // Test using TZlibTransport via a TTransport pointer
David Reisse5c435c2010-10-06 17:10:38 +0000870 ADD_TEST_RW(CoupledTTransports<CoupledZlibTransports>,
871 1024*1024, rand4k, rand4k, rand4k, rand4k);
David Reiss35dc7692010-10-06 17:10:19 +0000872 }
873
874 private:
875 template <class CoupledTransports>
David Reisse5c435c2010-10-06 17:10:38 +0000876 void addTestRW(const char* transport_name, uint32_t totalSize,
877 GenericSizeGenerator wSizeGen, GenericSizeGenerator rSizeGen,
878 GenericSizeGenerator wChunkSizeGen = 0,
879 GenericSizeGenerator rChunkSizeGen = 0,
880 uint32_t maxOutstanding = 0,
881 uint32_t expectedFailures = 0) {
David Reiss65e62d32010-10-06 17:10:35 +0000882 // adjust totalSize by the specified sizeMultiplier_ first
883 totalSize = static_cast<uint32_t>(totalSize * sizeMultiplier_);
884
David Reiss35dc7692010-10-06 17:10:19 +0000885 std::ostringstream name;
886 name << transport_name << "::test_rw(" << totalSize << ", " <<
887 wSizeGen.describe() << ", " << rSizeGen.describe() << ", " <<
888 wChunkSizeGen.describe() << ", " << rChunkSizeGen.describe() << ", " <<
889 maxOutstanding << ")";
890
891 boost::unit_test::callback0<> test_func =
892 std::tr1::bind(test_rw<CoupledTransports>, totalSize,
893 wSizeGen, rSizeGen, wChunkSizeGen, rChunkSizeGen,
894 maxOutstanding);
895 boost::unit_test::test_case* tc =
896 boost::unit_test::make_test_case(test_func, name.str());
897 suite_->add(tc, expectedFailures);
898 };
899
David Reisse5c435c2010-10-06 17:10:38 +0000900 template <class CoupledTransports>
901 void addTestBlocking(const char* transportName,
902 uint32_t expectedFailures = 0) {
903 char name[1024];
904 boost::unit_test::test_case* tc;
905
906 snprintf(name, sizeof(name), "%s::test_read_part_available()",
907 transportName);
908 tc = boost::unit_test::make_test_case(
909 test_read_part_available<CoupledTransports>, name);
910 suite_->add(tc, expectedFailures);
911
David Reiss0a2d81e2010-10-06 17:10:40 +0000912 snprintf(name, sizeof(name), "%s::test_read_partial_midframe()",
913 transportName);
914 tc = boost::unit_test::make_test_case(
915 test_read_partial_midframe<CoupledTransports>, name);
916 suite_->add(tc, expectedFailures);
917
David Reisse5c435c2010-10-06 17:10:38 +0000918 snprintf(name, sizeof(name), "%s::test_read_none_available()",
919 transportName);
920 tc = boost::unit_test::make_test_case(
921 test_read_none_available<CoupledTransports>, name);
922 suite_->add(tc, expectedFailures);
923
924 snprintf(name, sizeof(name), "%s::test_borrow_part_available()",
925 transportName);
926 tc = boost::unit_test::make_test_case(
927 test_borrow_part_available<CoupledTransports>, name);
928 suite_->add(tc, expectedFailures);
929
930 snprintf(name, sizeof(name), "%s::test_borrow_none_available()",
931 transportName);
932 tc = boost::unit_test::make_test_case(
933 test_borrow_none_available<CoupledTransports>, name);
934 suite_->add(tc, expectedFailures);
935 }
936
David Reiss35dc7692010-10-06 17:10:19 +0000937 boost::unit_test::test_suite* suite_;
David Reiss65e62d32010-10-06 17:10:35 +0000938 // sizeMultiplier_ is configurable via the command line, and allows the
939 // user to adjust between smaller buffers that can be tested quickly,
940 // or larger buffers that more thoroughly exercise the code, but take
941 // longer.
942 float sizeMultiplier_;
David Reiss35dc7692010-10-06 17:10:19 +0000943};
944
945/**************************************************************************
946 * General Initialization
947 **************************************************************************/
948
949void print_usage(FILE* f, const char* argv0) {
950 fprintf(f, "Usage: %s [boost_options] [options]\n", argv0);
951 fprintf(f, "Options:\n");
952 fprintf(f, " --seed=<N>, -s <N>\n");
953 fprintf(f, " --tmp-dir=DIR, -t DIR\n");
954 fprintf(f, " --help\n");
955}
956
David Reiss65e62d32010-10-06 17:10:35 +0000957struct Options {
David Reiss35dc7692010-10-06 17:10:19 +0000958 int seed;
David Reiss65e62d32010-10-06 17:10:35 +0000959 bool haveSeed;
960 float sizeMultiplier;
961};
962
963void parse_args(int argc, char* argv[], Options* options) {
964 bool have_seed = false;
965 options->sizeMultiplier = 1;
David Reiss35dc7692010-10-06 17:10:19 +0000966
967 struct option long_opts[] = {
968 { "help", false, NULL, 'h' },
969 { "seed", true, NULL, 's' },
970 { "tmp-dir", true, NULL, 't' },
David Reiss65e62d32010-10-06 17:10:35 +0000971 { "size-multiplier", true, NULL, 'x' },
David Reiss35dc7692010-10-06 17:10:19 +0000972 { NULL, 0, NULL, 0 }
973 };
974
975 while (true) {
976 optopt = 1;
David Reiss65e62d32010-10-06 17:10:35 +0000977 int optchar = getopt_long(argc, argv, "hs:t:x:", long_opts, NULL);
David Reiss35dc7692010-10-06 17:10:19 +0000978 if (optchar == -1) {
979 break;
980 }
981
982 switch (optchar) {
983 case 't':
984 tmp_dir = optarg;
985 break;
986 case 's': {
987 char *endptr;
David Reiss65e62d32010-10-06 17:10:35 +0000988 options->seed = strtol(optarg, &endptr, 0);
David Reiss35dc7692010-10-06 17:10:19 +0000989 if (endptr == optarg || *endptr != '\0') {
990 fprintf(stderr, "invalid seed value \"%s\": must be an integer\n",
991 optarg);
992 exit(1);
993 }
David Reiss65e62d32010-10-06 17:10:35 +0000994 have_seed = true;
David Reiss35dc7692010-10-06 17:10:19 +0000995 break;
996 }
997 case 'h':
998 print_usage(stdout, argv[0]);
999 exit(0);
David Reiss65e62d32010-10-06 17:10:35 +00001000 case 'x': {
1001 char *endptr;
1002 options->sizeMultiplier = strtof(optarg, &endptr);
1003 if (endptr == optarg || *endptr != '\0') {
1004 fprintf(stderr, "invalid size multiplier \"%s\": must be a number\n",
1005 optarg);
1006 exit(1);
1007 }
1008 if (options->sizeMultiplier < 0) {
1009 fprintf(stderr, "invalid size multiplier \"%s\": "
1010 "must be non-negative\n", optarg);
1011 exit(1);
1012 }
1013 break;
1014 }
David Reiss35dc7692010-10-06 17:10:19 +00001015 case '?':
1016 exit(1);
1017 default:
1018 // Only happens if someone adds another option to the optarg string,
1019 // but doesn't update the switch statement to handle it.
1020 fprintf(stderr, "unknown option \"-%c\"\n", optchar);
1021 exit(1);
1022 }
1023 }
1024
David Reiss65e62d32010-10-06 17:10:35 +00001025 if (!have_seed) {
1026 // choose a seed now if the user didn't specify one
1027 struct timespec t;
1028 clock_gettime(CLOCK_REALTIME, &t);
1029 options->seed = t.tv_sec + t.tv_nsec;
1030 }
David Reiss35dc7692010-10-06 17:10:19 +00001031}
1032
1033boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
1034 // Parse arguments
David Reiss65e62d32010-10-06 17:10:35 +00001035 Options options;
1036 parse_args(argc, argv, &options);
1037
1038 initrand(options.seed);
David Reiss35dc7692010-10-06 17:10:19 +00001039
David Reiss109693c2010-10-06 17:10:42 +00001040 boost::unit_test::test_suite* suite =
1041 &boost::unit_test::framework::master_test_suite();
1042 suite->p_name.value = "TransportTest";
David Reiss65e62d32010-10-06 17:10:35 +00001043 TransportTestGen transport_test_generator(suite, options.sizeMultiplier);
David Reiss35dc7692010-10-06 17:10:19 +00001044 transport_test_generator.generate();
1045
David Reiss109693c2010-10-06 17:10:42 +00001046 return NULL;
David Reiss35dc7692010-10-06 17:10:19 +00001047}