-
Notifications
You must be signed in to change notification settings - Fork 320
/
Copy pathbslim_testutil.t.cpp
2376 lines (2031 loc) · 84.9 KB
/
bslim_testutil.t.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// bslim_testutil.t.cpp -*-C++-*-
#include <bslim_testutil.h>
#include <bsls_assert.h>
#include <bsls_asserttest.h>
#include <bsls_platform.h>
#include <bsl_sstream.h>
#include <fcntl.h>
#include <limits.h> // 'PATH_MAX' on Linux
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // 'strlen'
#include <sys/types.h> // for 'struct stat[64]'; req~d on Sun and Windows only
#include <sys/stat.h> // (ditto)
#if defined(BSLS_PLATFORM_OS_WINDOWS)
# include <windows.h> // 'MAX_PATH'
# include <io.h> // '_dup2'
# define snprintf _snprintf
#else
# include <unistd.h>
#endif
// Ensure that the 'BSLIM_TESTUTIL_*' macros do not require:
// using namespace bsl;
using namespace BloombergLP;
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
// The component under test implements a set of macros that write to the
// standard output ('bsl::cout'), and a set of overloads for the output
// operator ('<<') to write objects of the 'bsltf' test types to output
// streams.
//
// The macros provided mirror the standard test macros normally used in test
// drivers. The intention is that the standard test macros should be
// implemented as aliases of the 'BSLIM_TESTUTIL_*' macros, as illustrated in
// the first usage example. As a result, the identifiers normally used in a
// test driver conflict with the identifiers used in the usage example.
// Therefore, this test driver avoids the standard test macros (and support
// functions), and uses the following instead:
//..
// STANDARD bslim_testutil.t.cpp
// ---------------- --------------------
// LOOP_ASSERT REALLOOP1_ASSERT
// LOOP2_ASSERT REALLOOP2_ASSERT
// LOOP3_ASSERT REALLOOP3_ASSERT
// LOOP4_ASSERT REALLOOP4_ASSERT
// LOOP5_ASSERT not used
// LOOP6_ASSERT not used
// Q not used
// P REALP
// P_ REALT_
// T_ REALT_
// L_ not used
// 'void aSsErT()' 'void realaSsErT()'
// 'int testStatus' 'int realTestStatus'
//..
// All of the methods write output to 'stdout' and do nothing more. Therefore,
// there are no Primary Manipulators or Basic Accessors to test. All of the
// tests fall under the category of Print Operations.
//
// The main difficulty with writing this test driver is capturing the output of
// the methods under test so that it can be checked for accuracy. In addition,
// error messages and other output produced by the test driver itself must
// still appear on 'stdout' for compatibility with the standard building and
// testing scripts. For this purpose, a support class named 'OutputRedirector'
// is provided. 'OutputRedirector' redirects 'stdout' to a temporary file and
// verifies that the contents of the temporary file match the character buffers
// provided by the user.
//-----------------------------------------------------------------------------
// CLASS METHODS
// [ 7] bool compareText(StringRef, StringRef, bsl::ostream&);
// [ 8] FUNCTION makeFunctionCallNonInline(FUNCTION);
//
// MACROS
// [ 6] BSLIM_TESTUTIL_ASSERT(X)
// [ 6] BSLIM_TESTUTIL_LOOP_ASSERT(I,X)
// [ 6] BSLIM_TESTUTIL_LOOP2_ASSERT(I,J,X)
// [ 6] BSLIM_TESTUTIL_LOOP3_ASSERT(I,J,K,X)
// [ 6] BSLIM_TESTUTIL_LOOP4_ASSERT(I,J,K,L,X)
// [ 6] BSLIM_TESTUTIL_LOOP5_ASSERT(I,J,K,L,M,X)
// [ 6] BSLIM_TESTUTIL_LOOP6_ASSERT(I,J,K,L,M,N,X)
// [ 6] BSLIM_TESTUTIL_ASSERTV(...)
// [ 5] BSLIM_TESTUTIL_Q(X)
// [ 4] BSLIM_TESTUTIL_P(X)
// [ 4] BSLIM_TESTUTIL_P_(X)
// [ 3] BSLIM_TESTUTIL_L_
// [ 3] BSLIM_TESTUTIL_T_
//-----------------------------------------------------------------------------
// [ 9] USAGE EXAMPLE
// [ 1] BREATHING TEST
// [ 2] TEST APPARATUS
// ============================================================================
// VARIATIONS ON STANDARD BDE ASSERT TEST MACROS
// ----------------------------------------------------------------------------
//
// In order to accommodate the use of the identifiers 'testStatus' and 'aSsErT'
// in the usage example, the rest of the test driver uses the identifiers
// 'realTestStatus' and 'realaSsErT' instead.
//
// Additionally, in order to allow capturing the output of the
// 'BSLIM_TESTUTIL_*' macros, the standard macros output to 'stderr' instead of
// 'stdout'.
static int realTestStatus = 0;
static void realaSsErT(bool b, const char *s, int i)
{
if (b) {
bsl::cerr << "Error " << __FILE__ << "(" << i << "): " << s
<< " (failed)" << bsl::endl;
if (realTestStatus >= 0 && realTestStatus <= 100) ++realTestStatus;
}
}
// The standard 'ASSERT' macro definition is deferred until after the usage
// example code:
//..
// #define ASSERT(X) { realaSsErT(!(X), #X, __LINE__); }
//..
#define REALLOOP_ASSERT(I,X) \
if (!(X)) { bsl::cerr << #I << ": " << I << "\n"; \
realaSsErT(1, #X, __LINE__); }
#define REALLOOP2_ASSERT(I,J,X) \
if (!(X)) { bsl::cerr << #I << ": " << I << "\t" \
<< #J << ": " << J << "\n"; \
realaSsErT(1, #X, __LINE__); }
#define REALLOOP3_ASSERT(I,J,K,X) \
if (!(X)) { bsl::cerr << #I << ": " << I << "\t" \
<< #J << ": " << J << "\t" \
<< #K << ": " << K << "\n"; \
realaSsErT(1, #X, __LINE__); }
#define REALLOOP4_ASSERT(I,J,K,L,X) \
if (!(X)) { bsl::cerr << #I << ": " << I << "\t" \
<< #J << ": " << J << "\t" \
<< #K << ": " << K << "\t" \
<< #L << ": " << L << "\n"; \
realaSsErT(1, #X, __LINE__); }
#define REALP(X) \
bsl::cerr << #X " = " << (X) << bsl::endl;
#define REALP_(X) \
bsl::cerr << #X " = " << (X) << ", " << bsl::flush;
#define REALT_ \
bsl::cerr << "\t" << bsl::flush;
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)
//=============================================================================
// USAGE EXAMPLE CODE
//-----------------------------------------------------------------------------
namespace {
///Example 1: Writing a Test Driver
/// - - - - - - - - - - - - - - - -
// First, we write an elided component to test, which provides a utility class:
//..
namespace bdlabc {
struct ExampleUtil {
// This utility class provides sample functionality to demonstrate how
// a test driver might be written validating its only method.
// CLASS METHODS
static int fortyTwo();
// Return the integer value 42.
};
// CLASS METHODS
inline
int ExampleUtil::fortyTwo()
{
return 42;
}
} // close namespace bdlabc
//..
// Then, we can write an elided test driver for this component. We start by
// providing the standard BDE assert test macro:
//..
//=========================================================================
// STANDARD BDE ASSERT TEST MACRO
//-------------------------------------------------------------------------
static int testStatus = 0;
static void aSsErT(int c, const char *s, int i)
{
if (c) {
bsl::cout << "Error " << __FILE__ << "(" << i << "): " << s
<< " (failed)" << bsl::endl;
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
//..
// Next, we define the standard print and 'LOOP_ASSERT' macros, as aliases to
// the macros defined by this component:
//..
//=========================================================================
// STANDARD BDE TEST DRIVER MACROS
//-------------------------------------------------------------------------
#define ASSERT BSLIM_TESTUTIL_ASSERT
#define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT
#define ASSERTV BSLIM_TESTUTIL_ASSERTV
#define Q BSLIM_TESTUTIL_Q // Quote identifier literally.
#define P BSLIM_TESTUTIL_P // Print identifier and value.
#define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLIM_TESTUTIL_L_ // current Line number
//..
// Now, using the (standard) abbreviated macro names we have just defined, we
// write a test function for the 'static' 'fortyTwo' method, to be called from
// a test case in the test driver:
//..
void testFortyTwo(bool verbose)
// Test 'bdlabc::ExampleUtil::fortyTwo' in the specified 'verbose'
// verbosity level.
{
const int value = bdlabc::ExampleUtil::fortyTwo();
if (verbose) P(value);
LOOP_ASSERT(value, 42 == value);
}
//..
// Finally, when 'testFortyTwo' is called from a test case in verbose mode we
// observe the console output:
//..
// value = 42
//..
} // close unnamed namespace
//=============================================================================
// UNDEFINE STANDARD TEST DRIVER MACROS
//-----------------------------------------------------------------------------
#undef ASSERT
#undef LOOP_ASSERT
#undef LOOP2_ASSERT
#undef LOOP3_ASSERT
#undef LOOP4_ASSERT
#undef LOOP5_ASSERT
#undef LOOP6_ASSERT
#undef ASSERTV
#undef Q
#undef P
#undef P_
#undef T_
#undef L_
#define ASSERT(X) { realaSsErT(!(X), #X, __LINE__); }
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
typedef bslim::TestUtil Obj;
enum { FORMAT_STRING_SIZE = 256 }; // Size of temporary format string buffers
// used for output formatting.
enum {
// Enumeration defining sizes for the buffers used by the output
// redirection apparatus.
OUTPUT_BUFFER_SIZE = 4096,
#ifdef BSLS_PLATFORM_OS_WINDOWS
PATH_BUFFER_SIZE = MAX_PATH
#elif defined(BSLS_PLATFORM_OS_HPUX)
PATH_BUFFER_SIZE = L_tmpnam
#else
PATH_BUFFER_SIZE = PATH_MAX
#endif
};
static bool verbose, veryVerbose, veryVeryVerbose;
//=============================================================================
// GLOBAL HELPER TYPES AND FUNCTIONS
//-----------------------------------------------------------------------------
#if defined(BSLS_PLATFORM_OS_WINDOWS) || defined(BSLS_PLATFORM_OS_DARWIN)
typedef struct stat StatType;
#else
typedef struct stat64 StatType;
#endif
inline
int fstatFunc(int fd, StatType *buf)
{
#if defined(BSLS_PLATFORM_OS_WINDOWS) || defined(BSLS_PLATFORM_OS_DARWIN)
return fstat(fd, buf);
#else
return fstat64(fd, buf);
#endif
}
//=============================================================================
// GLOBAL HELPER CLASSES FOR TESTING
//-----------------------------------------------------------------------------
namespace BSLIM_TESTUTIL_TEST_FUNCTION_CALL {
int callCount = 0;
void *testFunctionAdd(void *arg)
// Increment call counter and return the specified 'arg'.
{
++callCount;
return arg;
}
void *testFunctionSub(void *arg)
// Decrement call counter and return the specified 'arg'.
{
--callCount;
return arg;
}
} // close namespace BSLIM_TESTUTIL_TEST_FUNCTION_CALL
namespace {
bool tempFileName(char *result)
// Create a temporary file and load its name into the user-supplied buffer
// at the address pointed to by the specified 'result'. Return 'true' if
// the temporary file was successfully created, and 'false' otherwise. The
// behavior is undefined unless the buffer pointed to by 'result' is at
// least 'PATH_BUFFER_SIZE' bytes long.
{
ASSERT(result);
#ifdef BSLS_PLATFORM_OS_WINDOWS
char tmpPathBuf[MAX_PATH];
if (!GetTempPathA(MAX_PATH, tmpPathBuf)
|| !GetTempFileNameA(tmpPathBuf, "bslim", 0, result)) {
return false; // RETURN
}
#elif defined(BSLS_PLATFORM_OS_HPUX)
if(!tempnam(result, "bslim")) {
return false; // RETURN
}
#else
char *fn = tempnam(0, "bslim");
if (fn) {
strncpy(result, fn, PATH_BUFFER_SIZE);
result[PATH_BUFFER_SIZE - 1] = '\0';
free(fn);
} else {
return false; // RETURN
}
#endif
if (veryVerbose) printf("\tUse '%s' as a base filename.\n", result);
ASSERT('\0' != result[0]); // result is not empty
return true;
}
} // close unnamed namespace
class OutputRedirector {
// This class provides a facility for redirecting 'stdout' to a temporary
// file, retrieving output from the temporary file, and comparing the
// output to user-supplied character buffers. An 'OutputRedirector' object
// can exist in one of two states, un-redirected or redirected. In the
// un-redirected state, the process' 'stdout' and 'stderr' are connected to
// their normal targets. In the redirected state, the process' 'stdout' is
// connected to a temporary file, and the process' 'stderr' is connected to
// the original target of 'stdout'. The redirected state of an
// 'OutputRedirector' object can be tested by calling 'isRedirected'. An
// 'OutputRedirector' object has the concept of a scratch buffer, where
// output captured from the process' 'stdout' stream is stored when the
// 'OutputRedirector' object is in the redirected state. Throughout this
// class, the term "captured output" refers to data that has been written
// to the 'stdout' stream and is waiting to be loaded into the scratch
// buffer. Each time the 'load' method is called, the scratch buffer is
// truncated, and the captured output is moved into the scratch buffer.
// When this is done, there is no longer any captured output.
// DATA
char d_fileName[PATH_BUFFER_SIZE]; // name of temporary capture file
char d_outputBuffer[OUTPUT_BUFFER_SIZE]; // scratch buffer for holding
// captured output
bool d_isRedirectedFlag; // has 'stdout' been redirected
bool d_isFileCreatedFlag; // has a temp file been created
bool d_isOutputReadyFlag; // has output been read from the
// temp file
long d_outputSize; // size of output loaded into
// 'd_outputBuffer'
StatType d_originalStdoutStat; // status information for
// 'stdout' just before
// redirection
private:
// PRIVATE CLASS METHODS
static int redirectStream(FILE *from, FILE *to);
// Redirect the specified 'from' stream to the specified 'to' stream.
// Return 0 on success, and a negative value otherwise.
// PRIVATE MANIPULATORS
void cleanup();
// Close 'stdout', if redirected, and delete the temporary output
// capture file.
private:
// NOT IMPLEMENTED
OutputRedirector(const OutputRedirector&);
OutputRedirector& operator=(const OutputRedirector&);
public:
// CREATORS
OutputRedirector();
// Create an 'OutputRedirector' in an un-redirected state having an
// empty scratch buffer.
~OutputRedirector();
// Destroy this 'OutputRedirector' object. If the object is in a
// redirected state, 'stdout' will be closed and the temporary file to
// which 'stdout' was redirected will be removed.
// MANIPULATORS
char *buffer();
// Return the address providing modifiable access to the scratch
// buffer. Note that this method is used only for error reporting and
// to test the correctness of 'OutputRedirector'.
bool load();
// Read captured output into the scratch buffer. Return 'true' if all
// captured output was successfully loaded, and 'false' otherwise. The
// behavior is undefined unless 'redirect' has been previously called
// successfully. Note that captured output is allowed to have 0
// length.
void redirect();
// Redirect 'stdout' to a temp file, and 'stderr' to the original
// 'stdout', putting this 'OutputRedirector' object into the
// redirected state. The temp file to which 'stdout' is redirected
// will be created the first time 'redirect' is called, and will be
// removed when this object is destroyed. Subsequent calls to this
// method no effect on 'stdout' and 'stderr'. If this method fails to
// redirect either 'stdout' or 'stderr', 'std::abort' is called.
void reset();
// Reset the scratch buffer to empty. The behavior is undefined unless
// 'redirect' has been previously called successfully.
// ACCESSORS
int compare(const char *expected) const;
// Compare the specified 'expected' character buffer with any output
// that has been loaded into the scratch buffer. 'expected' is assumed
// to be an NTBS, and its length is taken to be the string length of
// the NTBS. Return 0 if 'expected' has the same length and contents
// as the scratch buffer, and non-zero otherwise. The behavior is
// undefined unless 'redirect' has been previously called successfully.
int compare(const char *expected, size_t expectedLength) const;
// Compare the specified 'expected' character buffer of the specified
// 'expectedLength' with any output that has been loaded into the
// scratch buffer. Return 0 if 'expected' has the same length and
// contents as the scratch buffer, and non-zero otherwise. The
// behavior is undefined unless 'redirect' has been previously called
// successfully. Note that 'expected' may contain embedded null
// characters.
bool isOutputReady() const;
// Return 'true' if captured output been loaded into the scratch
// buffer, and 'false' otherwise.
bool isRedirected() const;
// Return 'true' if 'stdout' and 'stderr' have been successfully
// redirected, and 'false' otherwise.
const StatType& originalStdoutStat() const;
// Return a reference providing non-modifiable access to the status
// information for 'stdout' collected just before redirection. Note
// that this method is used only to test the correctness of
// 'OutputRedirector'.
size_t outputSize() const;
// Return the number of bytes currently loaded into the scratch buffer.
};
// PRIVATE CLASS METHODS
int OutputRedirector::redirectStream(FILE *from, FILE *to)
{
ASSERT(from);
ASSERT(to);
// The canonical way to redirect 'stderr' to 'stdout' is:
//..
// freopen("/dev/stdout", "w", stderr);
//..
// but we use 'dup2' instead of 'freopen', because 'freopen' fails on AIX
// with 'errno == 13' ("Permission denied") when redirecting 'stderr'.
#if defined(BSLS_PLATFORM_OS_AIX)
int redirected = dup2(fileno(to), fileno(from));
return redirected == fileno(from) ? 0 : -1;
#elif defined(BSLS_PLATFORM_OS_WINDOWS)
return _dup2(_fileno(to), _fileno(from));
#else
return (stderr == freopen("/dev/stdout", "w", stderr)) ? 0 : -1;
#endif
}
// PRIVATE MANIPULATORS
void OutputRedirector::cleanup()
{
if (d_isRedirectedFlag) {
fclose(stdout);
}
if (d_isFileCreatedFlag) {
unlink(d_fileName);
}
}
// CREATORS
OutputRedirector::OutputRedirector()
: d_isRedirectedFlag(false)
, d_isFileCreatedFlag(false)
, d_isOutputReadyFlag(false)
, d_outputSize(0L)
{
d_fileName[0] = '\0';
memset(&d_originalStdoutStat, 0, sizeof(d_originalStdoutStat));
}
OutputRedirector::~OutputRedirector()
{
cleanup();
}
// MANIPULATORS
char *OutputRedirector::buffer()
{
return d_outputBuffer;
}
bool OutputRedirector::load()
{
ASSERT(d_isRedirectedFlag);
ASSERT(!ferror(stdout));
d_outputSize = ftell(stdout);
if (d_outputSize + 1 > OUTPUT_BUFFER_SIZE) {
// Refuse to load output if it will not all fit in the scratch buffer.
if (veryVerbose) {
REALP(d_outputSize);
fprintf(stderr,
"Error "
__FILE__
"(%d): Captured output exceeds read buffer size\n",
__LINE__);
}
d_outputSize = 0L;
return false; // RETURN
}
rewind(stdout);
long charsRead = fread(d_outputBuffer, sizeof(char), d_outputSize, stdout);
if (d_outputSize != charsRead) {
// We failed to read all output from the capture file.
if (veryVerbose) {
REALP_(d_outputSize); REALP(charsRead);
if (ferror(stdout)) {
// We encountered a file error, not 'EOF'.
perror("\tError message: ");
clearerr(stdout);
}
fprintf(stderr,
"Error "
__FILE__
"(%d): Could not read all captured output\n",
__LINE__);
}
d_outputBuffer[charsRead] = '\0';
// ... to ensure that direct inspection of buffer does not overflow
return false; // RETURN
} else {
// We have read all output from the capture file.
d_outputBuffer[d_outputSize] = '\0';
// ... to ensure that direct inspection of buffer does not overflow
}
d_isOutputReadyFlag = true;
return true;
}
void OutputRedirector::redirect()
{
if (d_isRedirectedFlag) {
// Do not redirect anything if we have already redirected.
if (veryVerbose) {
fprintf(stdout,
"Warning " __FILE__ "(%d): Output already redirected\n",
__LINE__);
}
return; // RETURN
}
// Retain information about the original 'stdout' file descriptor for use
// in later tests.
int originalStdoutFD = fileno(stdout);
ASSERT(-1 != originalStdoutFD);
ASSERT(0 == fstatFunc(originalStdoutFD, &d_originalStdoutStat));
if (0 != redirectStream(stderr, stdout)) {
// Redirect 'stderr' to 'stdout'.
// We want 'stderr' to point to 'stdout', so we have to redirect it
// before we change the meaning of 'stdout'.
if (veryVerbose) {
// Note that we print this error message on 'stdout' instead of
// 'stderr', because 'stdout' has not been redirected.
fprintf(stdout,
"Error " __FILE__ "(%d): Failed to redirect stderr\n",
__LINE__);
}
std::abort();
}
if (!tempFileName(d_fileName)) {
// Get temp file name.
if (veryVerbose) {
// Note that we print this error message on 'stdout' instead of
// 'stderr', because 'stdout' has not been redirected.
fprintf(stdout,
"Error "
__FILE__
"(%d): Failed to get temp file name for stdout capture\n",
__LINE__);
}
std::abort();
}
if (!freopen(d_fileName, "w+", stdout)) {
// Redirect 'stdout'.
if (veryVerbose) {
// Note that we print this error message on 'stderr', because we
// have just redirected 'stdout' to the capture file.
REALP(d_fileName);
fprintf(stderr,
"Error " __FILE__ "(%d): Failed to redirect stdout\n",
__LINE__);
}
cleanup();
std::abort();
}
// 'stderr' and 'stdout' have been successfully redirected.
#if defined(BSLS_PLATFORM_OS_WINDOWS)
if (-1 == _setmode(_fileno(stdout), _O_BINARY)) {
ASSERT(0 == "Failed to set stdout to binary mode.");
cleanup();
std::abort();
}
#endif
d_isFileCreatedFlag = true;
d_isRedirectedFlag = true;
if (EOF == fflush(stdout)) {
// Not flushing 'stdout' is not a fatal condition, so we print out a
// warning, but do not abort.
if (veryVerbose) {
// Note that we print this error message on 'stderr', because we
// have just redirected 'stdout' to the capture file.
perror("Error message: ");
fprintf(stderr,
"Warning " __FILE__ "(%d): Error flushing stdout\n",
__LINE__);
}
}
}
void OutputRedirector::reset()
{
ASSERT(d_isRedirectedFlag);
d_outputSize = 0L;
d_isOutputReadyFlag = false;
d_outputBuffer[0] = '\0';
rewind(stdout);
}
// ACCESSORS
int OutputRedirector::compare(const char *expected) const
{
ASSERT(expected);
return compare(expected, strlen(expected));
}
int OutputRedirector::compare(const char *expected,
size_t expectedLength) const
{
ASSERT(d_isRedirectedFlag);
ASSERT(expected || !expectedLength);
if (!d_isOutputReadyFlag) {
if (veryVerbose) {
REALP(expected);
fprintf(stderr,
"Error " __FILE__ "(%d): No captured output available\n",
__LINE__);
}
return -1; // RETURN
}
// Use 'memcmp' instead of 'strncmp' to compare 'd_outputBuffer' with
// 'expected' because 'expected' may contain embedded null characters.
return d_outputSize != static_cast<long>(expectedLength)
|| memcmp(d_outputBuffer, expected, expectedLength);
}
bool OutputRedirector::isOutputReady() const
{
return d_isOutputReadyFlag;
}
bool OutputRedirector::isRedirected() const
{
return d_isRedirectedFlag;
}
const StatType& OutputRedirector::originalStdoutStat() const
{
return d_originalStdoutStat;
}
size_t OutputRedirector::outputSize() const
{
return static_cast<size_t>(d_outputSize);
}
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
verbose = argc > 2;
veryVerbose = argc > 3;
veryVeryVerbose = argc > 4;
// Capture 'stdout', and send 'stderr' to 'stdout', unless we are running
// the usage example.
OutputRedirector output;
if (test != 8 && test != 0) {
output.redirect();
}
bsl::cerr << "TEST " << __FILE__ << " CASE " << test << bsl::endl;
switch (test) { case 0: // Zero is always the leading case.
case 9: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
//
// Concerns:
//: 1 The usage example provided in the component header file compiles,
//: links, and runs as shown.
//
// Plan:
//: 1 Incorporate usage example from header into test driver, remove
//: leading comment characters, and replace 'assert' with 'ASSERT'.
//: (C-1)
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) bsl::cerr << bsl::endl
<< "USAGE EXAMPLE" << bsl::endl
<< "=============" << bsl::endl;
testFortyTwo(verbose);
} break;
case 8: {
// --------------------------------------------------------------------
// TESTING 'makeFunctionCallNonInline'
//
// Concerns:
//: 1 A custom function with external linkage can be installed and
//: later called via 'bslim' test utility component.
//
// Plan:
//: 1 Install custom function using 'setFunc' method.
//:
//: 2 Invoke previously installed function and verify the result of
//: its invocation.
//
// Testing:
// FUNCTION makeFunctionCallNonInline(FUNCTION);
// --------------------------------------------------------------------
if (verbose) bsl::cout << "TESTING 'makeFunctionCallNonInline'\n"
<< "======================\n";
using namespace BSLIM_TESTUTIL_TEST_FUNCTION_CALL;
ASSERT(0 == callCount);
int refValue;
void *INPUT = &refValue;
void *result =
(*Obj::makeFunctionCallNonInline(testFunctionAdd))(INPUT);
ASSERT(1 == callCount);
ASSERT(&refValue == result);
result = (*Obj::makeFunctionCallNonInline(testFunctionAdd))(INPUT);
ASSERT(2 == callCount);
ASSERT(&refValue == result);
result = (*Obj::makeFunctionCallNonInline(testFunctionSub))(INPUT);
ASSERT(1 == callCount);
ASSERT(&refValue == result);
result = (*Obj::makeFunctionCallNonInline(testFunctionSub))(INPUT);
ASSERT(0 == callCount);
ASSERT(&refValue == result);
} break;
case 7: {
// --------------------------------------------------------------------
// TESTING 'compareText'
//
// Concerns:
//: 1 The function returns 'true' if the strings are both empty
//:
//: 2 The function returns 'true' if the strings have the same value
//:
//: 3 The function returns 'false' if the left string is shorter
//: than the right.
//:
//: 4 The function returns 'false' if the right string is shorter
//: than the left.
//:
//: 5 The function returns 'false' if the strings are the same length
//: but differ in their contents
//:
//: 6 The function writes a message to the supplied stream containing
//: information about the character where they differ, if the two
//: strings are not the same.
//:
//: 7 If no stream is explicitly supplied, error messages are written
//: to 'stdout'.
//:
//: 8 The function correctly handles embedded non-ascii and null
//: characters.
//
// Plan:
//: 1 Call 'compareText' with a data set containing a variety of
//: strings, and compare the results to 'strcmp'. (C-1-6)
//:
//: 2 Call 'compareText' with a data set containing embedded nulls and
//: compare the results against
//: 'bslstl::StringRef::operator=='. (C-8)
//:
//: 3 Call 'compareText' with types of un-equal strings that will
//: produce different error messages, and verify the produced error
//: message meets the expected error message. (C-7)
//
// Testing:
// bool compareText(StringRef, StringRef, bsl::ostream&);
// --------------------------------------------------------------------
if (verbose) bsl::cout << bsl::endl
<< "TESTING 'compareText'" << bsl::endl
<< "=====================" << bsl::endl;
if (verbose) bsl::cout << "Compare against 'strcmp'." << bsl::endl;
{
const char *DATA[] = {
"",
"a",
"z",
"A",
"Z",
"\x01",
"\x20",
"\x40",
"\x60",
"\x80",
"\xA0",
"\xC0",
"\xE0",
"\xF0",
" a",
" z",
" A",
" Z",
" \x01",
" \x50",
" \xA0",
" \xF0",
"aa",
"az",
"aA",
"aZ",
"a\x01",
"a\x50",
"a\xA0",
"a\xF0",
"Za",
"Zz",
"ZA",
"ZZ",
"Z\x01",
"Z\x50",
"Z\xA0",
"Z\xF0",
"\xA0""a",
"\xA0""z",
"\xA0""A",
"\xA0""Z",