Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/ts/src/ts_gtest.cpp
16337 views
1
// Copyright 2008, Google Inc.
2
// All rights reserved.
3
//
4
// Redistribution and use in source and binary forms, with or without
5
// modification, are permitted provided that the following conditions are
6
// met:
7
//
8
// * Redistributions of source code must retain the above copyright
9
// notice, this list of conditions and the following disclaimer.
10
// * Redistributions in binary form must reproduce the above
11
// copyright notice, this list of conditions and the following disclaimer
12
// in the documentation and/or other materials provided with the
13
// distribution.
14
// * Neither the name of Google Inc. nor the names of its
15
// contributors may be used to endorse or promote products derived from
16
// this software without specific prior written permission.
17
//
18
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30
//
31
// Google C++ Testing and Mocking Framework (Google Test)
32
//
33
// Sometimes it's desirable to build Google Test by compiling a single file.
34
// This file serves this purpose.
35
36
// This line ensures that gtest.h can be compiled on its own, even
37
// when it's fused.
38
#include "precomp.hpp"
39
40
#ifdef __GNUC__
41
# pragma GCC diagnostic ignored "-Wmissing-declarations"
42
# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
43
# if __GNUC__ >= 5
44
# pragma GCC diagnostic ignored "-Wsuggest-override"
45
# endif
46
#endif
47
48
// The following lines pull in the real gtest *.cc files.
49
// Copyright 2005, Google Inc.
50
// All rights reserved.
51
//
52
// Redistribution and use in source and binary forms, with or without
53
// modification, are permitted provided that the following conditions are
54
// met:
55
//
56
// * Redistributions of source code must retain the above copyright
57
// notice, this list of conditions and the following disclaimer.
58
// * Redistributions in binary form must reproduce the above
59
// copyright notice, this list of conditions and the following disclaimer
60
// in the documentation and/or other materials provided with the
61
// distribution.
62
// * Neither the name of Google Inc. nor the names of its
63
// contributors may be used to endorse or promote products derived from
64
// this software without specific prior written permission.
65
//
66
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
67
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
68
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
69
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
70
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
71
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
72
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
73
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
74
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
75
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
76
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
77
78
//
79
// The Google C++ Testing and Mocking Framework (Google Test)
80
81
// Copyright 2007, Google Inc.
82
// All rights reserved.
83
//
84
// Redistribution and use in source and binary forms, with or without
85
// modification, are permitted provided that the following conditions are
86
// met:
87
//
88
// * Redistributions of source code must retain the above copyright
89
// notice, this list of conditions and the following disclaimer.
90
// * Redistributions in binary form must reproduce the above
91
// copyright notice, this list of conditions and the following disclaimer
92
// in the documentation and/or other materials provided with the
93
// distribution.
94
// * Neither the name of Google Inc. nor the names of its
95
// contributors may be used to endorse or promote products derived from
96
// this software without specific prior written permission.
97
//
98
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
99
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
100
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
101
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
102
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
103
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
104
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
105
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
106
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
107
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
108
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
109
110
//
111
// Utilities for testing Google Test itself and code that uses Google Test
112
// (e.g. frameworks built on top of Google Test).
113
114
// GOOGLETEST_CM0004 DO NOT DELETE
115
116
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
117
#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
118
119
120
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
121
/* class A needs to have dll-interface to be used by clients of class B */)
122
123
namespace testing {
124
125
// This helper class can be used to mock out Google Test failure reporting
126
// so that we can test Google Test or code that builds on Google Test.
127
//
128
// An object of this class appends a TestPartResult object to the
129
// TestPartResultArray object given in the constructor whenever a Google Test
130
// failure is reported. It can either intercept only failures that are
131
// generated in the same thread that created this object or it can intercept
132
// all generated failures. The scope of this mock object can be controlled with
133
// the second argument to the two arguments constructor.
134
class GTEST_API_ ScopedFakeTestPartResultReporter
135
: public TestPartResultReporterInterface {
136
public:
137
// The two possible mocking modes of this object.
138
enum InterceptMode {
139
INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
140
INTERCEPT_ALL_THREADS // Intercepts all failures.
141
};
142
143
// The c'tor sets this object as the test part result reporter used
144
// by Google Test. The 'result' parameter specifies where to report the
145
// results. This reporter will only catch failures generated in the current
146
// thread. DEPRECATED
147
explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
148
149
// Same as above, but you can choose the interception scope of this object.
150
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
151
TestPartResultArray* result);
152
153
// The d'tor restores the previous test part result reporter.
154
virtual ~ScopedFakeTestPartResultReporter();
155
156
// Appends the TestPartResult object to the TestPartResultArray
157
// received in the constructor.
158
//
159
// This method is from the TestPartResultReporterInterface
160
// interface.
161
virtual void ReportTestPartResult(const TestPartResult& result);
162
private:
163
void Init();
164
165
const InterceptMode intercept_mode_;
166
TestPartResultReporterInterface* old_reporter_;
167
TestPartResultArray* const result_;
168
169
GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
170
};
171
172
namespace internal {
173
174
// A helper class for implementing EXPECT_FATAL_FAILURE() and
175
// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
176
// TestPartResultArray contains exactly one failure that has the given
177
// type and contains the given substring. If that's not the case, a
178
// non-fatal failure will be generated.
179
class GTEST_API_ SingleFailureChecker {
180
public:
181
// The constructor remembers the arguments.
182
SingleFailureChecker(const TestPartResultArray* results,
183
TestPartResult::Type type, const std::string& substr);
184
~SingleFailureChecker();
185
private:
186
const TestPartResultArray* const results_;
187
const TestPartResult::Type type_;
188
const std::string substr_;
189
190
GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
191
};
192
193
} // namespace internal
194
195
} // namespace testing
196
197
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
198
199
// A set of macros for testing Google Test assertions or code that's expected
200
// to generate Google Test fatal failures. It verifies that the given
201
// statement will cause exactly one fatal Google Test failure with 'substr'
202
// being part of the failure message.
203
//
204
// There are two different versions of this macro. EXPECT_FATAL_FAILURE only
205
// affects and considers failures generated in the current thread and
206
// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
207
//
208
// The verification of the assertion is done correctly even when the statement
209
// throws an exception or aborts the current function.
210
//
211
// Known restrictions:
212
// - 'statement' cannot reference local non-static variables or
213
// non-static members of the current object.
214
// - 'statement' cannot return a value.
215
// - You cannot stream a failure message to this macro.
216
//
217
// Note that even though the implementations of the following two
218
// macros are much alike, we cannot refactor them to use a common
219
// helper macro, due to some peculiarity in how the preprocessor
220
// works. The AcceptsMacroThatExpandsToUnprotectedComma test in
221
// gtest_unittest.cc will fail to compile if we do that.
222
#define EXPECT_FATAL_FAILURE(statement, substr) \
223
do { \
224
class GTestExpectFatalFailureHelper {\
225
public:\
226
static void Execute() { statement; }\
227
};\
228
::testing::TestPartResultArray gtest_failures;\
229
::testing::internal::SingleFailureChecker gtest_checker(\
230
&gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
231
{\
232
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
233
::testing::ScopedFakeTestPartResultReporter:: \
234
INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
235
GTestExpectFatalFailureHelper::Execute();\
236
}\
237
} while (::testing::internal::AlwaysFalse())
238
239
#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
240
do { \
241
class GTestExpectFatalFailureHelper {\
242
public:\
243
static void Execute() { statement; }\
244
};\
245
::testing::TestPartResultArray gtest_failures;\
246
::testing::internal::SingleFailureChecker gtest_checker(\
247
&gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
248
{\
249
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
250
::testing::ScopedFakeTestPartResultReporter:: \
251
INTERCEPT_ALL_THREADS, &gtest_failures);\
252
GTestExpectFatalFailureHelper::Execute();\
253
}\
254
} while (::testing::internal::AlwaysFalse())
255
256
// A macro for testing Google Test assertions or code that's expected to
257
// generate Google Test non-fatal failures. It asserts that the given
258
// statement will cause exactly one non-fatal Google Test failure with 'substr'
259
// being part of the failure message.
260
//
261
// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
262
// affects and considers failures generated in the current thread and
263
// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
264
//
265
// 'statement' is allowed to reference local variables and members of
266
// the current object.
267
//
268
// The verification of the assertion is done correctly even when the statement
269
// throws an exception or aborts the current function.
270
//
271
// Known restrictions:
272
// - You cannot stream a failure message to this macro.
273
//
274
// Note that even though the implementations of the following two
275
// macros are much alike, we cannot refactor them to use a common
276
// helper macro, due to some peculiarity in how the preprocessor
277
// works. If we do that, the code won't compile when the user gives
278
// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
279
// expands to code containing an unprotected comma. The
280
// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
281
// catches that.
282
//
283
// For the same reason, we have to write
284
// if (::testing::internal::AlwaysTrue()) { statement; }
285
// instead of
286
// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
287
// to avoid an MSVC warning on unreachable code.
288
#define EXPECT_NONFATAL_FAILURE(statement, substr) \
289
do {\
290
::testing::TestPartResultArray gtest_failures;\
291
::testing::internal::SingleFailureChecker gtest_checker(\
292
&gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
293
(substr));\
294
{\
295
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
296
::testing::ScopedFakeTestPartResultReporter:: \
297
INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
298
if (::testing::internal::AlwaysTrue()) { statement; }\
299
}\
300
} while (::testing::internal::AlwaysFalse())
301
302
#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
303
do {\
304
::testing::TestPartResultArray gtest_failures;\
305
::testing::internal::SingleFailureChecker gtest_checker(\
306
&gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
307
(substr));\
308
{\
309
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
310
::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
311
&gtest_failures);\
312
if (::testing::internal::AlwaysTrue()) { statement; }\
313
}\
314
} while (::testing::internal::AlwaysFalse())
315
316
#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
317
318
#include <ctype.h>
319
#include <math.h>
320
#include <stdarg.h>
321
#include <stdio.h>
322
#include <stdlib.h>
323
#include <time.h>
324
#include <wchar.h>
325
#include <wctype.h>
326
327
#include <algorithm>
328
#include <iomanip>
329
#include <limits>
330
#include <list>
331
#include <map>
332
#include <ostream> // NOLINT
333
#include <sstream>
334
#include <vector>
335
336
#if GTEST_OS_LINUX
337
338
// FIXME: Use autoconf to detect availability of
339
// gettimeofday().
340
# define GTEST_HAS_GETTIMEOFDAY_ 1
341
342
# include <fcntl.h> // NOLINT
343
# include <limits.h> // NOLINT
344
# include <sched.h> // NOLINT
345
// Declares vsnprintf(). This header is not available on Windows.
346
# include <strings.h> // NOLINT
347
# include <sys/mman.h> // NOLINT
348
# include <sys/time.h> // NOLINT
349
# include <unistd.h> // NOLINT
350
# include <string>
351
352
#elif GTEST_OS_SYMBIAN
353
# define GTEST_HAS_GETTIMEOFDAY_ 1
354
# include <sys/time.h> // NOLINT
355
356
#elif GTEST_OS_ZOS
357
# define GTEST_HAS_GETTIMEOFDAY_ 1
358
# include <sys/time.h> // NOLINT
359
360
// On z/OS we additionally need strings.h for strcasecmp.
361
# include <strings.h> // NOLINT
362
363
#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
364
365
# include <windows.h> // NOLINT
366
# undef min
367
368
#elif GTEST_OS_WINDOWS // We are on Windows proper.
369
370
# include <io.h> // NOLINT
371
# include <sys/timeb.h> // NOLINT
372
# include <sys/types.h> // NOLINT
373
# include <sys/stat.h> // NOLINT
374
375
# if GTEST_OS_WINDOWS_MINGW
376
// MinGW has gettimeofday() but not _ftime64().
377
// FIXME: Use autoconf to detect availability of
378
// gettimeofday().
379
// FIXME: There are other ways to get the time on
380
// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
381
// supports these. consider using them instead.
382
# define GTEST_HAS_GETTIMEOFDAY_ 1
383
# include <sys/time.h> // NOLINT
384
# endif // GTEST_OS_WINDOWS_MINGW
385
386
// cpplint thinks that the header is already included, so we want to
387
// silence it.
388
# include <windows.h> // NOLINT
389
# undef min
390
391
#else
392
393
// Assume other platforms have gettimeofday().
394
// FIXME: Use autoconf to detect availability of
395
// gettimeofday().
396
# define GTEST_HAS_GETTIMEOFDAY_ 1
397
398
// cpplint thinks that the header is already included, so we want to
399
// silence it.
400
# include <sys/time.h> // NOLINT
401
# include <unistd.h> // NOLINT
402
403
#endif // GTEST_OS_LINUX
404
405
#if GTEST_HAS_EXCEPTIONS
406
# include <stdexcept>
407
#endif
408
409
#if GTEST_CAN_STREAM_RESULTS_
410
# include <arpa/inet.h> // NOLINT
411
# include <netdb.h> // NOLINT
412
# include <sys/socket.h> // NOLINT
413
# include <sys/types.h> // NOLINT
414
#endif
415
416
// Copyright 2005, Google Inc.
417
// All rights reserved.
418
//
419
// Redistribution and use in source and binary forms, with or without
420
// modification, are permitted provided that the following conditions are
421
// met:
422
//
423
// * Redistributions of source code must retain the above copyright
424
// notice, this list of conditions and the following disclaimer.
425
// * Redistributions in binary form must reproduce the above
426
// copyright notice, this list of conditions and the following disclaimer
427
// in the documentation and/or other materials provided with the
428
// distribution.
429
// * Neither the name of Google Inc. nor the names of its
430
// contributors may be used to endorse or promote products derived from
431
// this software without specific prior written permission.
432
//
433
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
434
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
435
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
436
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
437
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
438
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
439
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
440
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
441
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
442
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
443
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
444
445
// Utility functions and classes used by the Google C++ testing framework.//
446
// This file contains purely Google Test's internal implementation. Please
447
// DO NOT #INCLUDE IT IN A USER PROGRAM.
448
449
#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
450
#define GTEST_SRC_GTEST_INTERNAL_INL_H_
451
452
#ifndef _WIN32_WCE
453
# include <errno.h>
454
#endif // !_WIN32_WCE
455
#include <stddef.h>
456
#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
457
#include <string.h> // For memmove.
458
459
#include <algorithm>
460
#include <string>
461
#include <vector>
462
463
464
#if GTEST_CAN_STREAM_RESULTS_
465
# include <arpa/inet.h> // NOLINT
466
# include <netdb.h> // NOLINT
467
#endif
468
469
#if GTEST_OS_WINDOWS
470
# include <windows.h> // NOLINT
471
#endif // GTEST_OS_WINDOWS
472
473
474
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
475
/* class A needs to have dll-interface to be used by clients of class B */)
476
477
namespace testing {
478
479
// Declares the flags.
480
//
481
// We don't want the users to modify this flag in the code, but want
482
// Google Test's own unit tests to be able to access it. Therefore we
483
// declare it here as opposed to in gtest.h.
484
GTEST_DECLARE_bool_(death_test_use_fork);
485
486
namespace internal {
487
488
// The value of GetTestTypeId() as seen from within the Google Test
489
// library. This is solely for testing GetTestTypeId().
490
GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
491
492
// Names of the flags (needed for parsing Google Test flags).
493
const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
494
const char kBreakOnFailureFlag[] = "break_on_failure";
495
const char kCatchExceptionsFlag[] = "catch_exceptions";
496
const char kColorFlag[] = "color";
497
const char kFilterFlag[] = "filter";
498
const char kParamFilterFlag[] = "param_filter";
499
const char kListTestsFlag[] = "list_tests";
500
const char kOutputFlag[] = "output";
501
const char kPrintTimeFlag[] = "print_time";
502
const char kPrintUTF8Flag[] = "print_utf8";
503
const char kRandomSeedFlag[] = "random_seed";
504
const char kRepeatFlag[] = "repeat";
505
const char kShuffleFlag[] = "shuffle";
506
const char kStackTraceDepthFlag[] = "stack_trace_depth";
507
const char kStreamResultToFlag[] = "stream_result_to";
508
const char kThrowOnFailureFlag[] = "throw_on_failure";
509
const char kFlagfileFlag[] = "flagfile";
510
511
// A valid random seed must be in [1, kMaxRandomSeed].
512
const int kMaxRandomSeed = 99999;
513
514
// g_help_flag is true iff the --help flag or an equivalent form is
515
// specified on the command line.
516
GTEST_API_ extern bool g_help_flag;
517
518
// Returns the current time in milliseconds.
519
GTEST_API_ TimeInMillis GetTimeInMillis();
520
521
// Returns true iff Google Test should use colors in the output.
522
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
523
524
// Formats the given time in milliseconds as seconds.
525
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
526
527
// Converts the given time in milliseconds to a date string in the ISO 8601
528
// format, without the timezone information. N.B.: due to the use the
529
// non-reentrant localtime() function, this function is not thread safe. Do
530
// not use it in any code that can be called from multiple threads.
531
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
532
533
// Parses a string for an Int32 flag, in the form of "--flag=value".
534
//
535
// On success, stores the value of the flag in *value, and returns
536
// true. On failure, returns false without changing *value.
537
GTEST_API_ bool ParseInt32Flag(
538
const char* str, const char* flag, Int32* value);
539
540
// Returns a random seed in range [1, kMaxRandomSeed] based on the
541
// given --gtest_random_seed flag value.
542
inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
543
const unsigned int raw_seed = (random_seed_flag == 0) ?
544
static_cast<unsigned int>(GetTimeInMillis()) :
545
static_cast<unsigned int>(random_seed_flag);
546
547
// Normalizes the actual seed to range [1, kMaxRandomSeed] such that
548
// it's easy to type.
549
const int normalized_seed =
550
static_cast<int>((raw_seed - 1U) %
551
static_cast<unsigned int>(kMaxRandomSeed)) + 1;
552
return normalized_seed;
553
}
554
555
// Returns the first valid random seed after 'seed'. The behavior is
556
// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
557
// considered to be 1.
558
inline int GetNextRandomSeed(int seed) {
559
GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
560
<< "Invalid random seed " << seed << " - must be in [1, "
561
<< kMaxRandomSeed << "].";
562
const int next_seed = seed + 1;
563
return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
564
}
565
566
// This class saves the values of all Google Test flags in its c'tor, and
567
// restores them in its d'tor.
568
class GTestFlagSaver {
569
public:
570
// The c'tor.
571
GTestFlagSaver() {
572
also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
573
break_on_failure_ = GTEST_FLAG(break_on_failure);
574
catch_exceptions_ = GTEST_FLAG(catch_exceptions);
575
color_ = GTEST_FLAG(color);
576
death_test_style_ = GTEST_FLAG(death_test_style);
577
death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
578
filter_ = GTEST_FLAG(filter);
579
param_filter_ = GTEST_FLAG(param_filter);
580
internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
581
list_tests_ = GTEST_FLAG(list_tests);
582
output_ = GTEST_FLAG(output);
583
print_time_ = GTEST_FLAG(print_time);
584
print_utf8_ = GTEST_FLAG(print_utf8);
585
random_seed_ = GTEST_FLAG(random_seed);
586
repeat_ = GTEST_FLAG(repeat);
587
shuffle_ = GTEST_FLAG(shuffle);
588
stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
589
stream_result_to_ = GTEST_FLAG(stream_result_to);
590
throw_on_failure_ = GTEST_FLAG(throw_on_failure);
591
}
592
593
// The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
594
~GTestFlagSaver() {
595
GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
596
GTEST_FLAG(break_on_failure) = break_on_failure_;
597
GTEST_FLAG(catch_exceptions) = catch_exceptions_;
598
GTEST_FLAG(color) = color_;
599
GTEST_FLAG(death_test_style) = death_test_style_;
600
GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
601
GTEST_FLAG(filter) = filter_;
602
GTEST_FLAG(param_filter) = param_filter_;
603
GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
604
GTEST_FLAG(list_tests) = list_tests_;
605
GTEST_FLAG(output) = output_;
606
GTEST_FLAG(print_time) = print_time_;
607
GTEST_FLAG(print_utf8) = print_utf8_;
608
GTEST_FLAG(random_seed) = random_seed_;
609
GTEST_FLAG(repeat) = repeat_;
610
GTEST_FLAG(shuffle) = shuffle_;
611
GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
612
GTEST_FLAG(stream_result_to) = stream_result_to_;
613
GTEST_FLAG(throw_on_failure) = throw_on_failure_;
614
}
615
616
private:
617
// Fields for saving the original values of flags.
618
bool also_run_disabled_tests_;
619
bool break_on_failure_;
620
bool catch_exceptions_;
621
std::string color_;
622
std::string death_test_style_;
623
bool death_test_use_fork_;
624
std::string filter_;
625
std::string param_filter_;
626
std::string internal_run_death_test_;
627
bool list_tests_;
628
std::string output_;
629
bool print_time_;
630
bool print_utf8_;
631
internal::Int32 random_seed_;
632
internal::Int32 repeat_;
633
bool shuffle_;
634
internal::Int32 stack_trace_depth_;
635
std::string stream_result_to_;
636
bool throw_on_failure_;
637
} GTEST_ATTRIBUTE_UNUSED_;
638
639
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
640
// code_point parameter is of type UInt32 because wchar_t may not be
641
// wide enough to contain a code point.
642
// If the code_point is not a valid Unicode code point
643
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
644
// to "(Invalid Unicode 0xXXXXXXXX)".
645
GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
646
647
// Converts a wide string to a narrow string in UTF-8 encoding.
648
// The wide string is assumed to have the following encoding:
649
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
650
// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
651
// Parameter str points to a null-terminated wide string.
652
// Parameter num_chars may additionally limit the number
653
// of wchar_t characters processed. -1 is used when the entire string
654
// should be processed.
655
// If the string contains code points that are not valid Unicode code points
656
// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
657
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
658
// and contains invalid UTF-16 surrogate pairs, values in those pairs
659
// will be encoded as individual Unicode characters from Basic Normal Plane.
660
GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
661
662
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
663
// if the variable is present. If a file already exists at this location, this
664
// function will write over it. If the variable is present, but the file cannot
665
// be created, prints an error and exits.
666
void WriteToShardStatusFileIfNeeded();
667
668
// Checks whether sharding is enabled by examining the relevant
669
// environment variable values. If the variables are present,
670
// but inconsistent (e.g., shard_index >= total_shards), prints
671
// an error and exits. If in_subprocess_for_death_test, sharding is
672
// disabled because it must only be applied to the original test
673
// process. Otherwise, we could filter out death tests we intended to execute.
674
GTEST_API_ bool ShouldShard(const char* total_shards_str,
675
const char* shard_index_str,
676
bool in_subprocess_for_death_test);
677
678
// Parses the environment variable var as an Int32. If it is unset,
679
// returns default_val. If it is not an Int32, prints an error and
680
// and aborts.
681
GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
682
683
// Given the total number of shards, the shard index, and the test id,
684
// returns true iff the test should be run on this shard. The test id is
685
// some arbitrary but unique non-negative integer assigned to each test
686
// method. Assumes that 0 <= shard_index < total_shards.
687
GTEST_API_ bool ShouldRunTestOnShard(
688
int total_shards, int shard_index, int test_id);
689
690
// STL container utilities.
691
692
// Returns the number of elements in the given container that satisfy
693
// the given predicate.
694
template <class Container, typename Predicate>
695
inline int CountIf(const Container& c, Predicate predicate) {
696
// Implemented as an explicit loop since std::count_if() in libCstd on
697
// Solaris has a non-standard signature.
698
int count = 0;
699
for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
700
if (predicate(*it))
701
++count;
702
}
703
return count;
704
}
705
706
// Applies a function/functor to each element in the container.
707
template <class Container, typename Functor>
708
void ForEach(const Container& c, Functor functor) {
709
std::for_each(c.begin(), c.end(), functor);
710
}
711
712
// Returns the i-th element of the vector, or default_value if i is not
713
// in range [0, v.size()).
714
template <typename E>
715
inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
716
return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
717
}
718
719
// Performs an in-place shuffle of a range of the vector's elements.
720
// 'begin' and 'end' are element indices as an STL-style range;
721
// i.e. [begin, end) are shuffled, where 'end' == size() means to
722
// shuffle to the end of the vector.
723
template <typename E>
724
void ShuffleRange(internal::Random* random, int begin, int end,
725
std::vector<E>* v) {
726
const int size = static_cast<int>(v->size());
727
GTEST_CHECK_(0 <= begin && begin <= size)
728
<< "Invalid shuffle range start " << begin << ": must be in range [0, "
729
<< size << "].";
730
GTEST_CHECK_(begin <= end && end <= size)
731
<< "Invalid shuffle range finish " << end << ": must be in range ["
732
<< begin << ", " << size << "].";
733
734
// Fisher-Yates shuffle, from
735
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
736
for (int range_width = end - begin; range_width >= 2; range_width--) {
737
const int last_in_range = begin + range_width - 1;
738
const int selected = begin + random->Generate(range_width);
739
std::swap((*v)[selected], (*v)[last_in_range]);
740
}
741
}
742
743
// Performs an in-place shuffle of the vector's elements.
744
template <typename E>
745
inline void Shuffle(internal::Random* random, std::vector<E>* v) {
746
ShuffleRange(random, 0, static_cast<int>(v->size()), v);
747
}
748
749
// A function for deleting an object. Handy for being used as a
750
// functor.
751
template <typename T>
752
static void Delete(T* x) {
753
delete x;
754
}
755
756
// A predicate that checks the key of a TestProperty against a known key.
757
//
758
// TestPropertyKeyIs is copyable.
759
class TestPropertyKeyIs {
760
public:
761
// Constructor.
762
//
763
// TestPropertyKeyIs has NO default constructor.
764
explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
765
766
// Returns true iff the test name of test property matches on key_.
767
bool operator()(const TestProperty& test_property) const {
768
return test_property.key() == key_;
769
}
770
771
private:
772
std::string key_;
773
};
774
775
// Class UnitTestOptions.
776
//
777
// This class contains functions for processing options the user
778
// specifies when running the tests. It has only static members.
779
//
780
// In most cases, the user can specify an option using either an
781
// environment variable or a command line flag. E.g. you can set the
782
// test filter using either GTEST_FILTER or --gtest_filter. If both
783
// the variable and the flag are present, the latter overrides the
784
// former.
785
class GTEST_API_ UnitTestOptions {
786
public:
787
// Functions for processing the gtest_output flag.
788
789
// Returns the output format, or "" for normal printed output.
790
static std::string GetOutputFormat();
791
792
// Returns the absolute path of the requested output file, or the
793
// default (test_detail.xml in the original working directory) if
794
// none was explicitly specified.
795
static std::string GetAbsolutePathToOutputFile();
796
797
// Functions for processing the gtest_filter flag.
798
799
// Returns true iff the wildcard pattern matches the string. The
800
// first ':' or '\0' character in pattern marks the end of it.
801
//
802
// This recursive algorithm isn't very efficient, but is clear and
803
// works well enough for matching test names, which are short.
804
static bool PatternMatchesString(const char *pattern, const char *str);
805
806
// Returns true iff the user-specified filter matches the test case
807
// name and the test name.
808
static bool FilterMatchesTest(const std::string &test_case_name,
809
const std::string &test_name);
810
811
#if GTEST_OS_WINDOWS
812
// Function for supporting the gtest_catch_exception flag.
813
814
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
815
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
816
// This function is useful as an __except condition.
817
static int GTestShouldProcessSEH(DWORD exception_code);
818
#endif // GTEST_OS_WINDOWS
819
820
// Returns true if "name" matches the ':' separated list of glob-style
821
// filters in "filter".
822
static bool MatchesFilter(const std::string& name, const char* filter);
823
};
824
825
// Returns the current application's name, removing directory path if that
826
// is present. Used by UnitTestOptions::GetOutputFile.
827
GTEST_API_ FilePath GetCurrentExecutableName();
828
829
// The role interface for getting the OS stack trace as a string.
830
class OsStackTraceGetterInterface {
831
public:
832
OsStackTraceGetterInterface() {}
833
virtual ~OsStackTraceGetterInterface() {}
834
835
// Returns the current OS stack trace as an std::string. Parameters:
836
//
837
// max_depth - the maximum number of stack frames to be included
838
// in the trace.
839
// skip_count - the number of top frames to be skipped; doesn't count
840
// against max_depth.
841
virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
842
843
// UponLeavingGTest() should be called immediately before Google Test calls
844
// user code. It saves some information about the current stack that
845
// CurrentStackTrace() will use to find and hide Google Test stack frames.
846
virtual void UponLeavingGTest() = 0;
847
848
// This string is inserted in place of stack frames that are part of
849
// Google Test's implementation.
850
static const char* const kElidedFramesMarker;
851
852
private:
853
GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
854
};
855
856
// A working implementation of the OsStackTraceGetterInterface interface.
857
class OsStackTraceGetter : public OsStackTraceGetterInterface {
858
public:
859
OsStackTraceGetter() {}
860
861
virtual std::string CurrentStackTrace(int max_depth, int skip_count);
862
virtual void UponLeavingGTest();
863
864
private:
865
#if GTEST_HAS_ABSL
866
Mutex mutex_; // Protects all internal state.
867
868
// We save the stack frame below the frame that calls user code.
869
// We do this because the address of the frame immediately below
870
// the user code changes between the call to UponLeavingGTest()
871
// and any calls to the stack trace code from within the user code.
872
void* caller_frame_ = nullptr;
873
#endif // GTEST_HAS_ABSL
874
875
GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
876
};
877
878
// Information about a Google Test trace point.
879
struct TraceInfo {
880
const char* file;
881
int line;
882
std::string message;
883
};
884
885
// This is the default global test part result reporter used in UnitTestImpl.
886
// This class should only be used by UnitTestImpl.
887
class DefaultGlobalTestPartResultReporter
888
: public TestPartResultReporterInterface {
889
public:
890
explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
891
// Implements the TestPartResultReporterInterface. Reports the test part
892
// result in the current test.
893
virtual void ReportTestPartResult(const TestPartResult& result);
894
895
private:
896
UnitTestImpl* const unit_test_;
897
898
GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
899
};
900
901
// This is the default per thread test part result reporter used in
902
// UnitTestImpl. This class should only be used by UnitTestImpl.
903
class DefaultPerThreadTestPartResultReporter
904
: public TestPartResultReporterInterface {
905
public:
906
explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
907
// Implements the TestPartResultReporterInterface. The implementation just
908
// delegates to the current global test part result reporter of *unit_test_.
909
virtual void ReportTestPartResult(const TestPartResult& result);
910
911
private:
912
UnitTestImpl* const unit_test_;
913
914
GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
915
};
916
917
// The private implementation of the UnitTest class. We don't protect
918
// the methods under a mutex, as this class is not accessible by a
919
// user and the UnitTest class that delegates work to this class does
920
// proper locking.
921
class GTEST_API_ UnitTestImpl {
922
public:
923
explicit UnitTestImpl(UnitTest* parent);
924
virtual ~UnitTestImpl();
925
926
// There are two different ways to register your own TestPartResultReporter.
927
// You can register your own repoter to listen either only for test results
928
// from the current thread or for results from all threads.
929
// By default, each per-thread test result repoter just passes a new
930
// TestPartResult to the global test result reporter, which registers the
931
// test part result for the currently running test.
932
933
// Returns the global test part result reporter.
934
TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
935
936
// Sets the global test part result reporter.
937
void SetGlobalTestPartResultReporter(
938
TestPartResultReporterInterface* reporter);
939
940
// Returns the test part result reporter for the current thread.
941
TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
942
943
// Sets the test part result reporter for the current thread.
944
void SetTestPartResultReporterForCurrentThread(
945
TestPartResultReporterInterface* reporter);
946
947
// Gets the number of successful test cases.
948
int successful_test_case_count() const;
949
950
// Gets the number of failed test cases.
951
int failed_test_case_count() const;
952
953
// Gets the number of all test cases.
954
int total_test_case_count() const;
955
956
// Gets the number of all test cases that contain at least one test
957
// that should run.
958
int test_case_to_run_count() const;
959
960
// Gets the number of successful tests.
961
int successful_test_count() const;
962
963
// Gets the number of failed tests.
964
int failed_test_count() const;
965
966
// Gets the number of disabled tests that will be reported in the XML report.
967
int reportable_disabled_test_count() const;
968
969
// Gets the number of disabled tests.
970
int disabled_test_count() const;
971
972
// Gets the number of tests to be printed in the XML report.
973
int reportable_test_count() const;
974
975
// Gets the number of all tests.
976
int total_test_count() const;
977
978
// Gets the number of tests that should run.
979
int test_to_run_count() const;
980
981
// Gets the time of the test program start, in ms from the start of the
982
// UNIX epoch.
983
TimeInMillis start_timestamp() const { return start_timestamp_; }
984
985
// Gets the elapsed time, in milliseconds.
986
TimeInMillis elapsed_time() const { return elapsed_time_; }
987
988
// Returns true iff the unit test passed (i.e. all test cases passed).
989
bool Passed() const { return !Failed(); }
990
991
// Returns true iff the unit test failed (i.e. some test case failed
992
// or something outside of all tests failed).
993
bool Failed() const {
994
return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
995
}
996
997
// Gets the i-th test case among all the test cases. i can range from 0 to
998
// total_test_case_count() - 1. If i is not in that range, returns NULL.
999
const TestCase* GetTestCase(int i) const {
1000
const int index = GetElementOr(test_case_indices_, i, -1);
1001
return index < 0 ? NULL : test_cases_[i];
1002
}
1003
1004
// Gets the i-th test case among all the test cases. i can range from 0 to
1005
// total_test_case_count() - 1. If i is not in that range, returns NULL.
1006
TestCase* GetMutableTestCase(int i) {
1007
const int index = GetElementOr(test_case_indices_, i, -1);
1008
return index < 0 ? NULL : test_cases_[index];
1009
}
1010
1011
// Provides access to the event listener list.
1012
TestEventListeners* listeners() { return &listeners_; }
1013
1014
// Returns the TestResult for the test that's currently running, or
1015
// the TestResult for the ad hoc test if no test is running.
1016
TestResult* current_test_result();
1017
1018
// Returns the TestResult for the ad hoc test.
1019
const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1020
1021
// Sets the OS stack trace getter.
1022
//
1023
// Does nothing if the input and the current OS stack trace getter
1024
// are the same; otherwise, deletes the old getter and makes the
1025
// input the current getter.
1026
void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1027
1028
// Returns the current OS stack trace getter if it is not NULL;
1029
// otherwise, creates an OsStackTraceGetter, makes it the current
1030
// getter, and returns it.
1031
OsStackTraceGetterInterface* os_stack_trace_getter();
1032
1033
// Returns the current OS stack trace as an std::string.
1034
//
1035
// The maximum number of stack frames to be included is specified by
1036
// the gtest_stack_trace_depth flag. The skip_count parameter
1037
// specifies the number of top frames to be skipped, which doesn't
1038
// count against the number of frames to be included.
1039
//
1040
// For example, if Foo() calls Bar(), which in turn calls
1041
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1042
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1043
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1044
1045
// Finds and returns a TestCase with the given name. If one doesn't
1046
// exist, creates one and returns it.
1047
//
1048
// Arguments:
1049
//
1050
// test_case_name: name of the test case
1051
// type_param: the name of the test's type parameter, or NULL if
1052
// this is not a typed or a type-parameterized test.
1053
// set_up_tc: pointer to the function that sets up the test case
1054
// tear_down_tc: pointer to the function that tears down the test case
1055
TestCase* GetTestCase(const char* test_case_name,
1056
const char* type_param,
1057
Test::SetUpTestCaseFunc set_up_tc,
1058
Test::TearDownTestCaseFunc tear_down_tc);
1059
1060
// Adds a TestInfo to the unit test.
1061
//
1062
// Arguments:
1063
//
1064
// set_up_tc: pointer to the function that sets up the test case
1065
// tear_down_tc: pointer to the function that tears down the test case
1066
// test_info: the TestInfo object
1067
void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1068
Test::TearDownTestCaseFunc tear_down_tc,
1069
TestInfo* test_info) {
1070
// In order to support thread-safe death tests, we need to
1071
// remember the original working directory when the test program
1072
// was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1073
// the user may have changed the current directory before calling
1074
// RUN_ALL_TESTS(). Therefore we capture the current directory in
1075
// AddTestInfo(), which is called to register a TEST or TEST_F
1076
// before main() is reached.
1077
if (original_working_dir_.IsEmpty()) {
1078
original_working_dir_.Set(FilePath::GetCurrentDir());
1079
GTEST_CHECK_(!original_working_dir_.IsEmpty())
1080
<< "Failed to get the current working directory.";
1081
}
1082
1083
GetTestCase(test_info->test_case_name(),
1084
test_info->type_param(),
1085
set_up_tc,
1086
tear_down_tc)->AddTestInfo(test_info);
1087
}
1088
1089
// Returns ParameterizedTestCaseRegistry object used to keep track of
1090
// value-parameterized tests and instantiate and register them.
1091
internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1092
return parameterized_test_registry_;
1093
}
1094
1095
// Sets the TestCase object for the test that's currently running.
1096
void set_current_test_case(TestCase* a_current_test_case) {
1097
current_test_case_ = a_current_test_case;
1098
}
1099
1100
// Sets the TestInfo object for the test that's currently running. If
1101
// current_test_info is NULL, the assertion results will be stored in
1102
// ad_hoc_test_result_.
1103
void set_current_test_info(TestInfo* a_current_test_info) {
1104
current_test_info_ = a_current_test_info;
1105
}
1106
1107
// Registers all parameterized tests defined using TEST_P and
1108
// INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1109
// combination. This method can be called more then once; it has guards
1110
// protecting from registering the tests more then once. If
1111
// value-parameterized tests are disabled, RegisterParameterizedTests is
1112
// present but does nothing.
1113
void RegisterParameterizedTests();
1114
1115
// Runs all tests in this UnitTest object, prints the result, and
1116
// returns true if all tests are successful. If any exception is
1117
// thrown during a test, this test is considered to be failed, but
1118
// the rest of the tests will still be run.
1119
bool RunAllTests();
1120
1121
// Clears the results of all tests, except the ad hoc tests.
1122
void ClearNonAdHocTestResult() {
1123
ForEach(test_cases_, TestCase::ClearTestCaseResult);
1124
}
1125
1126
// Clears the results of ad-hoc test assertions.
1127
void ClearAdHocTestResult() {
1128
ad_hoc_test_result_.Clear();
1129
}
1130
1131
// Adds a TestProperty to the current TestResult object when invoked in a
1132
// context of a test or a test case, or to the global property set. If the
1133
// result already contains a property with the same key, the value will be
1134
// updated.
1135
void RecordProperty(const TestProperty& test_property);
1136
1137
enum ReactionToSharding {
1138
HONOR_SHARDING_PROTOCOL,
1139
IGNORE_SHARDING_PROTOCOL
1140
};
1141
1142
// Matches the full name of each test against the user-specified
1143
// filter to decide whether the test should run, then records the
1144
// result in each TestCase and TestInfo object.
1145
// If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1146
// based on sharding variables in the environment.
1147
// Returns the number of tests that should run.
1148
int FilterTests(ReactionToSharding shard_tests);
1149
1150
// Prints the names of the tests matching the user-specified filter flag.
1151
void ListTestsMatchingFilter();
1152
1153
const TestCase* current_test_case() const { return current_test_case_; }
1154
TestInfo* current_test_info() { return current_test_info_; }
1155
const TestInfo* current_test_info() const { return current_test_info_; }
1156
1157
// Returns the vector of environments that need to be set-up/torn-down
1158
// before/after the tests are run.
1159
std::vector<Environment*>& environments() { return environments_; }
1160
1161
// Getters for the per-thread Google Test trace stack.
1162
std::vector<TraceInfo>& gtest_trace_stack() {
1163
return *(gtest_trace_stack_.pointer());
1164
}
1165
const std::vector<TraceInfo>& gtest_trace_stack() const {
1166
return gtest_trace_stack_.get();
1167
}
1168
1169
#if GTEST_HAS_DEATH_TEST
1170
void InitDeathTestSubprocessControlInfo() {
1171
internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1172
}
1173
// Returns a pointer to the parsed --gtest_internal_run_death_test
1174
// flag, or NULL if that flag was not specified.
1175
// This information is useful only in a death test child process.
1176
// Must not be called before a call to InitGoogleTest.
1177
const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1178
return internal_run_death_test_flag_.get();
1179
}
1180
1181
// Returns a pointer to the current death test factory.
1182
internal::DeathTestFactory* death_test_factory() {
1183
return death_test_factory_.get();
1184
}
1185
1186
void SuppressTestEventsIfInSubprocess();
1187
1188
friend class ReplaceDeathTestFactory;
1189
#endif // GTEST_HAS_DEATH_TEST
1190
1191
// Initializes the event listener performing XML output as specified by
1192
// UnitTestOptions. Must not be called before InitGoogleTest.
1193
void ConfigureXmlOutput();
1194
1195
#if GTEST_CAN_STREAM_RESULTS_
1196
// Initializes the event listener for streaming test results to a socket.
1197
// Must not be called before InitGoogleTest.
1198
void ConfigureStreamingOutput();
1199
#endif
1200
1201
// Performs initialization dependent upon flag values obtained in
1202
// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1203
// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1204
// this function is also called from RunAllTests. Since this function can be
1205
// called more than once, it has to be idempotent.
1206
void PostFlagParsingInit();
1207
1208
// Gets the random seed used at the start of the current test iteration.
1209
int random_seed() const { return random_seed_; }
1210
1211
// Gets the random number generator.
1212
internal::Random* random() { return &random_; }
1213
1214
// Shuffles all test cases, and the tests within each test case,
1215
// making sure that death tests are still run first.
1216
void ShuffleTests();
1217
1218
// Restores the test cases and tests to their order before the first shuffle.
1219
void UnshuffleTests();
1220
1221
// Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1222
// UnitTest::Run() starts.
1223
bool catch_exceptions() const { return catch_exceptions_; }
1224
1225
private:
1226
friend class ::testing::UnitTest;
1227
1228
// Used by UnitTest::Run() to capture the state of
1229
// GTEST_FLAG(catch_exceptions) at the moment it starts.
1230
void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1231
1232
// The UnitTest object that owns this implementation object.
1233
UnitTest* const parent_;
1234
1235
// The working directory when the first TEST() or TEST_F() was
1236
// executed.
1237
internal::FilePath original_working_dir_;
1238
1239
// The default test part result reporters.
1240
DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1241
DefaultPerThreadTestPartResultReporter
1242
default_per_thread_test_part_result_reporter_;
1243
1244
// Points to (but doesn't own) the global test part result reporter.
1245
TestPartResultReporterInterface* global_test_part_result_repoter_;
1246
1247
// Protects read and write access to global_test_part_result_reporter_.
1248
internal::Mutex global_test_part_result_reporter_mutex_;
1249
1250
// Points to (but doesn't own) the per-thread test part result reporter.
1251
internal::ThreadLocal<TestPartResultReporterInterface*>
1252
per_thread_test_part_result_reporter_;
1253
1254
// The vector of environments that need to be set-up/torn-down
1255
// before/after the tests are run.
1256
std::vector<Environment*> environments_;
1257
1258
// The vector of TestCases in their original order. It owns the
1259
// elements in the vector.
1260
std::vector<TestCase*> test_cases_;
1261
1262
// Provides a level of indirection for the test case list to allow
1263
// easy shuffling and restoring the test case order. The i-th
1264
// element of this vector is the index of the i-th test case in the
1265
// shuffled order.
1266
std::vector<int> test_case_indices_;
1267
1268
// ParameterizedTestRegistry object used to register value-parameterized
1269
// tests.
1270
internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1271
1272
// Indicates whether RegisterParameterizedTests() has been called already.
1273
bool parameterized_tests_registered_;
1274
1275
// Index of the last death test case registered. Initially -1.
1276
int last_death_test_case_;
1277
1278
// This points to the TestCase for the currently running test. It
1279
// changes as Google Test goes through one test case after another.
1280
// When no test is running, this is set to NULL and Google Test
1281
// stores assertion results in ad_hoc_test_result_. Initially NULL.
1282
TestCase* current_test_case_;
1283
1284
// This points to the TestInfo for the currently running test. It
1285
// changes as Google Test goes through one test after another. When
1286
// no test is running, this is set to NULL and Google Test stores
1287
// assertion results in ad_hoc_test_result_. Initially NULL.
1288
TestInfo* current_test_info_;
1289
1290
// Normally, a user only writes assertions inside a TEST or TEST_F,
1291
// or inside a function called by a TEST or TEST_F. Since Google
1292
// Test keeps track of which test is current running, it can
1293
// associate such an assertion with the test it belongs to.
1294
//
1295
// If an assertion is encountered when no TEST or TEST_F is running,
1296
// Google Test attributes the assertion result to an imaginary "ad hoc"
1297
// test, and records the result in ad_hoc_test_result_.
1298
TestResult ad_hoc_test_result_;
1299
1300
// The list of event listeners that can be used to track events inside
1301
// Google Test.
1302
TestEventListeners listeners_;
1303
1304
// The OS stack trace getter. Will be deleted when the UnitTest
1305
// object is destructed. By default, an OsStackTraceGetter is used,
1306
// but the user can set this field to use a custom getter if that is
1307
// desired.
1308
OsStackTraceGetterInterface* os_stack_trace_getter_;
1309
1310
// True iff PostFlagParsingInit() has been called.
1311
bool post_flag_parse_init_performed_;
1312
1313
// The random number seed used at the beginning of the test run.
1314
int random_seed_;
1315
1316
// Our random number generator.
1317
internal::Random random_;
1318
1319
// The time of the test program start, in ms from the start of the
1320
// UNIX epoch.
1321
TimeInMillis start_timestamp_;
1322
1323
// How long the test took to run, in milliseconds.
1324
TimeInMillis elapsed_time_;
1325
1326
#if GTEST_HAS_DEATH_TEST
1327
// The decomposed components of the gtest_internal_run_death_test flag,
1328
// parsed when RUN_ALL_TESTS is called.
1329
internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1330
internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1331
#endif // GTEST_HAS_DEATH_TEST
1332
1333
// A per-thread stack of traces created by the SCOPED_TRACE() macro.
1334
internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1335
1336
// The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1337
// starts.
1338
bool catch_exceptions_;
1339
1340
GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1341
}; // class UnitTestImpl
1342
1343
// Convenience function for accessing the global UnitTest
1344
// implementation object.
1345
inline UnitTestImpl* GetUnitTestImpl() {
1346
return UnitTest::GetInstance()->impl();
1347
}
1348
1349
#if GTEST_USES_SIMPLE_RE
1350
1351
// Internal helper functions for implementing the simple regular
1352
// expression matcher.
1353
GTEST_API_ bool IsInSet(char ch, const char* str);
1354
GTEST_API_ bool IsAsciiDigit(char ch);
1355
GTEST_API_ bool IsAsciiPunct(char ch);
1356
GTEST_API_ bool IsRepeat(char ch);
1357
GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1358
GTEST_API_ bool IsAsciiWordChar(char ch);
1359
GTEST_API_ bool IsValidEscape(char ch);
1360
GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1361
GTEST_API_ bool ValidateRegex(const char* regex);
1362
GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1363
GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1364
bool escaped, char ch, char repeat, const char* regex, const char* str);
1365
GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1366
1367
#endif // GTEST_USES_SIMPLE_RE
1368
1369
// Parses the command line for Google Test flags, without initializing
1370
// other parts of Google Test.
1371
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1372
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1373
1374
#if GTEST_HAS_DEATH_TEST
1375
1376
// Returns the message describing the last system error, regardless of the
1377
// platform.
1378
GTEST_API_ std::string GetLastErrnoDescription();
1379
1380
// Attempts to parse a string into a positive integer pointed to by the
1381
// number parameter. Returns true if that is possible.
1382
// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1383
// it here.
1384
template <typename Integer>
1385
bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1386
// Fail fast if the given string does not begin with a digit;
1387
// this bypasses strtoXXX's "optional leading whitespace and plus
1388
// or minus sign" semantics, which are undesirable here.
1389
if (str.empty() || !IsDigit(str[0])) {
1390
return false;
1391
}
1392
errno = 0;
1393
1394
char* end;
1395
// BiggestConvertible is the largest integer type that system-provided
1396
// string-to-number conversion routines can return.
1397
1398
# if GTEST_OS_WINDOWS && !defined(__GNUC__)
1399
1400
// MSVC and C++ Builder define __int64 instead of the standard long long.
1401
typedef unsigned __int64 BiggestConvertible;
1402
const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1403
1404
# else
1405
1406
typedef unsigned long long BiggestConvertible; // NOLINT
1407
const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1408
1409
# endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1410
1411
const bool parse_success = *end == '\0' && errno == 0;
1412
1413
// FIXME: Convert this to compile time assertion when it is
1414
// available.
1415
GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1416
1417
const Integer result = static_cast<Integer>(parsed);
1418
if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1419
*number = result;
1420
return true;
1421
}
1422
return false;
1423
}
1424
#endif // GTEST_HAS_DEATH_TEST
1425
1426
// TestResult contains some private methods that should be hidden from
1427
// Google Test user but are required for testing. This class allow our tests
1428
// to access them.
1429
//
1430
// This class is supplied only for the purpose of testing Google Test's own
1431
// constructs. Do not use it in user tests, either directly or indirectly.
1432
class TestResultAccessor {
1433
public:
1434
static void RecordProperty(TestResult* test_result,
1435
const std::string& xml_element,
1436
const TestProperty& property) {
1437
test_result->RecordProperty(xml_element, property);
1438
}
1439
1440
static void ClearTestPartResults(TestResult* test_result) {
1441
test_result->ClearTestPartResults();
1442
}
1443
1444
static const std::vector<testing::TestPartResult>& test_part_results(
1445
const TestResult& test_result) {
1446
return test_result.test_part_results();
1447
}
1448
};
1449
1450
#if GTEST_CAN_STREAM_RESULTS_
1451
1452
// Streams test results to the given port on the given host machine.
1453
class StreamingListener : public EmptyTestEventListener {
1454
public:
1455
// Abstract base class for writing strings to a socket.
1456
class AbstractSocketWriter {
1457
public:
1458
virtual ~AbstractSocketWriter() {}
1459
1460
// Sends a string to the socket.
1461
virtual void Send(const std::string& message) = 0;
1462
1463
// Closes the socket.
1464
virtual void CloseConnection() {}
1465
1466
// Sends a string and a newline to the socket.
1467
void SendLn(const std::string& message) { Send(message + "\n"); }
1468
};
1469
1470
// Concrete class for actually writing strings to a socket.
1471
class SocketWriter : public AbstractSocketWriter {
1472
public:
1473
SocketWriter(const std::string& host, const std::string& port)
1474
: sockfd_(-1), host_name_(host), port_num_(port) {
1475
MakeConnection();
1476
}
1477
1478
virtual ~SocketWriter() {
1479
if (sockfd_ != -1)
1480
CloseConnection();
1481
}
1482
1483
// Sends a string to the socket.
1484
virtual void Send(const std::string& message) {
1485
GTEST_CHECK_(sockfd_ != -1)
1486
<< "Send() can be called only when there is a connection.";
1487
1488
const int len = static_cast<int>(message.length());
1489
if (write(sockfd_, message.c_str(), len) != len) {
1490
GTEST_LOG_(WARNING)
1491
<< "stream_result_to: failed to stream to "
1492
<< host_name_ << ":" << port_num_;
1493
}
1494
}
1495
1496
private:
1497
// Creates a client socket and connects to the server.
1498
void MakeConnection();
1499
1500
// Closes the socket.
1501
void CloseConnection() {
1502
GTEST_CHECK_(sockfd_ != -1)
1503
<< "CloseConnection() can be called only when there is a connection.";
1504
1505
close(sockfd_);
1506
sockfd_ = -1;
1507
}
1508
1509
int sockfd_; // socket file descriptor
1510
const std::string host_name_;
1511
const std::string port_num_;
1512
1513
GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1514
}; // class SocketWriter
1515
1516
// Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1517
static std::string UrlEncode(const char* str);
1518
1519
StreamingListener(const std::string& host, const std::string& port)
1520
: socket_writer_(new SocketWriter(host, port)) {
1521
Start();
1522
}
1523
1524
explicit StreamingListener(AbstractSocketWriter* socket_writer)
1525
: socket_writer_(socket_writer) { Start(); }
1526
1527
void OnTestProgramStart(const UnitTest& /* unit_test */) {
1528
SendLn("event=TestProgramStart");
1529
}
1530
1531
void OnTestProgramEnd(const UnitTest& unit_test) {
1532
// Note that Google Test current only report elapsed time for each
1533
// test iteration, not for the entire test program.
1534
SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1535
1536
// Notify the streaming server to stop.
1537
socket_writer_->CloseConnection();
1538
}
1539
1540
void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1541
SendLn("event=TestIterationStart&iteration=" +
1542
StreamableToString(iteration));
1543
}
1544
1545
void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1546
SendLn("event=TestIterationEnd&passed=" +
1547
FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1548
StreamableToString(unit_test.elapsed_time()) + "ms");
1549
}
1550
1551
void OnTestCaseStart(const TestCase& test_case) {
1552
SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1553
}
1554
1555
void OnTestCaseEnd(const TestCase& test_case) {
1556
SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1557
+ "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
1558
+ "ms");
1559
}
1560
1561
void OnTestStart(const TestInfo& test_info) {
1562
SendLn(std::string("event=TestStart&name=") + test_info.name());
1563
}
1564
1565
void OnTestEnd(const TestInfo& test_info) {
1566
SendLn("event=TestEnd&passed=" +
1567
FormatBool((test_info.result())->Passed()) +
1568
"&elapsed_time=" +
1569
StreamableToString((test_info.result())->elapsed_time()) + "ms");
1570
}
1571
1572
void OnTestPartResult(const TestPartResult& test_part_result) {
1573
const char* file_name = test_part_result.file_name();
1574
if (file_name == NULL)
1575
file_name = "";
1576
SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1577
"&line=" + StreamableToString(test_part_result.line_number()) +
1578
"&message=" + UrlEncode(test_part_result.message()));
1579
}
1580
1581
private:
1582
// Sends the given message and a newline to the socket.
1583
void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
1584
1585
// Called at the start of streaming to notify the receiver what
1586
// protocol we are using.
1587
void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1588
1589
std::string FormatBool(bool value) { return value ? "1" : "0"; }
1590
1591
const scoped_ptr<AbstractSocketWriter> socket_writer_;
1592
1593
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1594
}; // class StreamingListener
1595
1596
#endif // GTEST_CAN_STREAM_RESULTS_
1597
1598
} // namespace internal
1599
} // namespace testing
1600
1601
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1602
1603
#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1604
1605
#if GTEST_OS_WINDOWS
1606
# define vsnprintf _vsnprintf
1607
#endif // GTEST_OS_WINDOWS
1608
1609
#if GTEST_OS_MAC
1610
#ifndef GTEST_OS_IOS
1611
#include <crt_externs.h>
1612
#endif
1613
#endif
1614
1615
#if GTEST_HAS_ABSL
1616
#include "absl/debugging/failure_signal_handler.h"
1617
#include "absl/debugging/stacktrace.h"
1618
#include "absl/debugging/symbolize.h"
1619
#include "absl/strings/str_cat.h"
1620
#endif // GTEST_HAS_ABSL
1621
1622
namespace testing {
1623
1624
using internal::CountIf;
1625
using internal::ForEach;
1626
using internal::GetElementOr;
1627
using internal::Shuffle;
1628
1629
// Constants.
1630
1631
// A test whose test case name or test name matches this filter is
1632
// disabled and not run.
1633
static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1634
1635
// A test case whose name matches this filter is considered a death
1636
// test case and will be run before test cases whose name doesn't
1637
// match this filter.
1638
static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1639
1640
// A test filter that matches everything.
1641
static const char kUniversalFilter[] = "*";
1642
1643
// The default output format.
1644
static const char kDefaultOutputFormat[] = "xml";
1645
// The default output file.
1646
static const char kDefaultOutputFile[] = "test_detail";
1647
1648
// The environment variable name for the test shard index.
1649
static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1650
// The environment variable name for the total number of test shards.
1651
static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1652
// The environment variable name for the test shard status file.
1653
static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1654
1655
namespace internal {
1656
1657
// The text used in failure messages to indicate the start of the
1658
// stack trace.
1659
const char kStackTraceMarker[] = "\nStack trace:\n";
1660
1661
// g_help_flag is true iff the --help flag or an equivalent form is
1662
// specified on the command line.
1663
bool g_help_flag = false;
1664
1665
// Utilty function to Open File for Writing
1666
static FILE* OpenFileForWriting(const std::string& output_file) {
1667
FILE* fileout = NULL;
1668
FilePath output_file_path(output_file);
1669
FilePath output_dir(output_file_path.RemoveFileName());
1670
1671
if (output_dir.CreateDirectoriesRecursively()) {
1672
fileout = posix::FOpen(output_file.c_str(), "w");
1673
}
1674
if (fileout == NULL) {
1675
GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
1676
}
1677
return fileout;
1678
}
1679
1680
} // namespace internal
1681
1682
// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
1683
// environment variable.
1684
static const char* GetDefaultFilter() {
1685
const char* const testbridge_test_only =
1686
internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
1687
if (testbridge_test_only != NULL) {
1688
return testbridge_test_only;
1689
}
1690
return kUniversalFilter;
1691
}
1692
1693
GTEST_DEFINE_bool_(
1694
also_run_disabled_tests,
1695
internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1696
"Run disabled tests too, in addition to the tests normally being run.");
1697
1698
GTEST_DEFINE_bool_(
1699
break_on_failure,
1700
internal::BoolFromGTestEnv("break_on_failure", false),
1701
"True iff a failed assertion should be a debugger break-point.");
1702
1703
GTEST_DEFINE_bool_(
1704
catch_exceptions,
1705
internal::BoolFromGTestEnv("catch_exceptions", true),
1706
"True iff " GTEST_NAME_
1707
" should catch exceptions and treat them as test failures.");
1708
1709
GTEST_DEFINE_string_(
1710
color,
1711
internal::StringFromGTestEnv("color", "auto"),
1712
"Whether to use colors in the output. Valid values: yes, no, "
1713
"and auto. 'auto' means to use colors if the output is "
1714
"being sent to a terminal and the TERM environment variable "
1715
"is set to a terminal type that supports colors.");
1716
1717
GTEST_DEFINE_string_(
1718
filter,
1719
internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1720
"A colon-separated list of glob (not regex) patterns "
1721
"for filtering the tests to run, optionally followed by a "
1722
"'-' and a : separated list of negative patterns (tests to "
1723
"exclude). A test is run if it matches one of the positive "
1724
"patterns and does not match any of the negative patterns.");
1725
1726
GTEST_DEFINE_bool_(
1727
install_failure_signal_handler,
1728
internal::BoolFromGTestEnv("install_failure_signal_handler", false),
1729
"If true and supported on the current platform, " GTEST_NAME_ " should "
1730
"install a signal handler that dumps debugging information when fatal "
1731
"signals are raised.");
1732
1733
GTEST_DEFINE_string_(
1734
param_filter,
1735
internal::StringFromGTestEnv("param_filter", GetDefaultFilter()),
1736
"Same syntax and semantics as for param, but these patterns "
1737
"have to match the test's parameters.");
1738
1739
GTEST_DEFINE_bool_(list_tests, false,
1740
"List all tests without running them.");
1741
1742
// The net priority order after flag processing is thus:
1743
// --gtest_output command line flag
1744
// GTEST_OUTPUT environment variable
1745
// XML_OUTPUT_FILE environment variable
1746
// ''
1747
GTEST_DEFINE_string_(
1748
output,
1749
internal::StringFromGTestEnv("output",
1750
internal::OutputFlagAlsoCheckEnvVar().c_str()),
1751
"A format (defaults to \"xml\" but can be specified to be \"json\"), "
1752
"optionally followed by a colon and an output file name or directory. "
1753
"A directory is indicated by a trailing pathname separator. "
1754
"Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1755
"If a directory is specified, output files will be created "
1756
"within that directory, with file-names based on the test "
1757
"executable's name and, if necessary, made unique by adding "
1758
"digits.");
1759
1760
GTEST_DEFINE_bool_(
1761
print_time,
1762
internal::BoolFromGTestEnv("print_time", true),
1763
"True iff " GTEST_NAME_
1764
" should display elapsed time in text output.");
1765
1766
GTEST_DEFINE_bool_(
1767
print_utf8,
1768
internal::BoolFromGTestEnv("print_utf8", true),
1769
"True iff " GTEST_NAME_
1770
" prints UTF8 characters as text.");
1771
1772
GTEST_DEFINE_int32_(
1773
random_seed,
1774
internal::Int32FromGTestEnv("random_seed", 0),
1775
"Random number seed to use when shuffling test orders. Must be in range "
1776
"[1, 99999], or 0 to use a seed based on the current time.");
1777
1778
GTEST_DEFINE_int32_(
1779
repeat,
1780
internal::Int32FromGTestEnv("repeat", 1),
1781
"How many times to repeat each test. Specify a negative number "
1782
"for repeating forever. Useful for shaking out flaky tests.");
1783
1784
GTEST_DEFINE_bool_(
1785
show_internal_stack_frames, false,
1786
"True iff " GTEST_NAME_ " should include internal stack frames when "
1787
"printing test failure stack traces.");
1788
1789
GTEST_DEFINE_bool_(
1790
shuffle,
1791
internal::BoolFromGTestEnv("shuffle", false),
1792
"True iff " GTEST_NAME_
1793
" should randomize tests' order on every run.");
1794
1795
GTEST_DEFINE_int32_(
1796
stack_trace_depth,
1797
internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1798
"The maximum number of stack frames to print when an "
1799
"assertion fails. The valid range is 0 through 100, inclusive.");
1800
1801
GTEST_DEFINE_string_(
1802
stream_result_to,
1803
internal::StringFromGTestEnv("stream_result_to", ""),
1804
"This flag specifies the host name and the port number on which to stream "
1805
"test results. Example: \"localhost:555\". The flag is effective only on "
1806
"Linux.");
1807
1808
GTEST_DEFINE_bool_(
1809
throw_on_failure,
1810
internal::BoolFromGTestEnv("throw_on_failure", false),
1811
"When this flag is specified, a failed assertion will throw an exception "
1812
"if exceptions are enabled or exit the program with a non-zero code "
1813
"otherwise. For use with an external test framework.");
1814
1815
#if GTEST_USE_OWN_FLAGFILE_FLAG_
1816
GTEST_DEFINE_string_(
1817
flagfile,
1818
internal::StringFromGTestEnv("flagfile", ""),
1819
"This flag specifies the flagfile to read command-line flags from.");
1820
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
1821
1822
namespace internal {
1823
1824
// Generates a random number from [0, range), using a Linear
1825
// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1826
// than kMaxRange.
1827
UInt32 Random::Generate(UInt32 range) {
1828
// These constants are the same as are used in glibc's rand(3).
1829
// Use wider types than necessary to prevent unsigned overflow diagnostics.
1830
state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
1831
1832
GTEST_CHECK_(range > 0)
1833
<< "Cannot generate a number in the range [0, 0).";
1834
GTEST_CHECK_(range <= kMaxRange)
1835
<< "Generation of a number in [0, " << range << ") was requested, "
1836
<< "but this can only generate numbers in [0, " << kMaxRange << ").";
1837
1838
// Converting via modulus introduces a bit of downward bias, but
1839
// it's simple, and a linear congruential generator isn't too good
1840
// to begin with.
1841
return state_ % range;
1842
}
1843
1844
// GTestIsInitialized() returns true iff the user has initialized
1845
// Google Test. Useful for catching the user mistake of not initializing
1846
// Google Test before calling RUN_ALL_TESTS().
1847
static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
1848
1849
// Iterates over a vector of TestCases, keeping a running sum of the
1850
// results of calling a given int-returning method on each.
1851
// Returns the sum.
1852
static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1853
int (TestCase::*method)() const) {
1854
int sum = 0;
1855
for (size_t i = 0; i < case_list.size(); i++) {
1856
sum += (case_list[i]->*method)();
1857
}
1858
return sum;
1859
}
1860
1861
// Returns true iff the test case passed.
1862
static bool TestCasePassed(const TestCase* test_case) {
1863
return test_case->should_run() && test_case->Passed();
1864
}
1865
1866
// Returns true iff the test case failed.
1867
static bool TestCaseFailed(const TestCase* test_case) {
1868
return test_case->should_run() && test_case->Failed();
1869
}
1870
1871
// Returns true iff test_case contains at least one test that should
1872
// run.
1873
static bool ShouldRunTestCase(const TestCase* test_case) {
1874
return test_case->should_run();
1875
}
1876
1877
// AssertHelper constructor.
1878
AssertHelper::AssertHelper(TestPartResult::Type type,
1879
const char* file,
1880
int line,
1881
const char* message)
1882
: data_(new AssertHelperData(type, file, line, message)) {
1883
}
1884
1885
AssertHelper::~AssertHelper() {
1886
delete data_;
1887
}
1888
1889
// Message assignment, for assertion streaming support.
1890
void AssertHelper::operator=(const Message& message) const {
1891
UnitTest::GetInstance()->
1892
AddTestPartResult(data_->type, data_->file, data_->line,
1893
AppendUserMessage(data_->message, message),
1894
UnitTest::GetInstance()->impl()
1895
->CurrentOsStackTraceExceptTop(1)
1896
// Skips the stack frame for this function itself.
1897
); // NOLINT
1898
}
1899
1900
// Mutex for linked pointers.
1901
GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1902
1903
// A copy of all command line arguments. Set by InitGoogleTest().
1904
static ::std::vector<std::string> g_argvs;
1905
1906
::std::vector<std::string> GetArgvs() {
1907
#if defined(GTEST_CUSTOM_GET_ARGVS_)
1908
// GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
1909
// ::string. This code converts it to the appropriate type.
1910
const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
1911
return ::std::vector<std::string>(custom.begin(), custom.end());
1912
#else // defined(GTEST_CUSTOM_GET_ARGVS_)
1913
return g_argvs;
1914
#endif // defined(GTEST_CUSTOM_GET_ARGVS_)
1915
}
1916
1917
// Returns the current application's name, removing directory path if that
1918
// is present.
1919
FilePath GetCurrentExecutableName() {
1920
FilePath result;
1921
1922
#if GTEST_OS_WINDOWS
1923
result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
1924
#else
1925
result.Set(FilePath(GetArgvs()[0]));
1926
#endif // GTEST_OS_WINDOWS
1927
1928
return result.RemoveDirectoryName();
1929
}
1930
1931
// Functions for processing the gtest_output flag.
1932
1933
// Returns the output format, or "" for normal printed output.
1934
std::string UnitTestOptions::GetOutputFormat() {
1935
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1936
const char* const colon = strchr(gtest_output_flag, ':');
1937
return (colon == NULL) ?
1938
std::string(gtest_output_flag) :
1939
std::string(gtest_output_flag, colon - gtest_output_flag);
1940
}
1941
1942
// Returns the name of the requested output file, or the default if none
1943
// was explicitly specified.
1944
std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1945
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1946
1947
std::string format = GetOutputFormat();
1948
if (format.empty())
1949
format = std::string(kDefaultOutputFormat);
1950
1951
const char* const colon = strchr(gtest_output_flag, ':');
1952
if (colon == NULL)
1953
return internal::FilePath::MakeFileName(
1954
internal::FilePath(
1955
UnitTest::GetInstance()->original_working_dir()),
1956
internal::FilePath(kDefaultOutputFile), 0,
1957
format.c_str()).string();
1958
1959
internal::FilePath output_name(colon + 1);
1960
if (!output_name.IsAbsolutePath())
1961
// FIXME: on Windows \some\path is not an absolute
1962
// path (as its meaning depends on the current drive), yet the
1963
// following logic for turning it into an absolute path is wrong.
1964
// Fix it.
1965
output_name = internal::FilePath::ConcatPaths(
1966
internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1967
internal::FilePath(colon + 1));
1968
1969
if (!output_name.IsDirectory())
1970
return output_name.string();
1971
1972
internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1973
output_name, internal::GetCurrentExecutableName(),
1974
GetOutputFormat().c_str()));
1975
return result.string();
1976
}
1977
1978
// Returns true iff the wildcard pattern matches the string. The
1979
// first ':' or '\0' character in pattern marks the end of it.
1980
//
1981
// This recursive algorithm isn't very efficient, but is clear and
1982
// works well enough for matching test names, which are short.
1983
bool UnitTestOptions::PatternMatchesString(const char *pattern,
1984
const char *str) {
1985
switch (*pattern) {
1986
case '\0':
1987
case ':': // Either ':' or '\0' marks the end of the pattern.
1988
return *str == '\0';
1989
case '?': // Matches any single character.
1990
return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1991
case '*': // Matches any string (possibly empty) of characters.
1992
return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1993
PatternMatchesString(pattern + 1, str);
1994
default: // Non-special character. Matches itself.
1995
return *pattern == *str &&
1996
PatternMatchesString(pattern + 1, str + 1);
1997
}
1998
}
1999
2000
bool UnitTestOptions::MatchesFilter(
2001
const std::string& name, const char* filter) {
2002
const char *cur_pattern = filter;
2003
for (;;) {
2004
if (PatternMatchesString(cur_pattern, name.c_str())) {
2005
return true;
2006
}
2007
2008
// Finds the next pattern in the filter.
2009
cur_pattern = strchr(cur_pattern, ':');
2010
2011
// Returns if no more pattern can be found.
2012
if (cur_pattern == NULL) {
2013
return false;
2014
}
2015
2016
// Skips the pattern separater (the ':' character).
2017
cur_pattern++;
2018
}
2019
}
2020
2021
// Returns true iff the user-specified filter matches the test case
2022
// name and the test name.
2023
bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
2024
const std::string &test_name) {
2025
const std::string& full_name = test_case_name + "." + test_name.c_str();
2026
2027
// Split --gtest_filter at '-', if there is one, to separate into
2028
// positive filter and negative filter portions
2029
const char* const p = GTEST_FLAG(filter).c_str();
2030
const char* const dash = strchr(p, '-');
2031
std::string positive;
2032
std::string negative;
2033
if (dash == NULL) {
2034
positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
2035
negative = "";
2036
} else {
2037
positive = std::string(p, dash); // Everything up to the dash
2038
negative = std::string(dash + 1); // Everything after the dash
2039
if (positive.empty()) {
2040
// Treat '-test1' as the same as '*-test1'
2041
positive = kUniversalFilter;
2042
}
2043
}
2044
2045
// A filter is a colon-separated list of patterns. It matches a
2046
// test if any pattern in it matches the test.
2047
return (MatchesFilter(full_name, positive.c_str()) &&
2048
!MatchesFilter(full_name, negative.c_str()));
2049
}
2050
2051
#if GTEST_HAS_SEH
2052
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
2053
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
2054
// This function is useful as an __except condition.
2055
int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
2056
// Google Test should handle a SEH exception if:
2057
// 1. the user wants it to, AND
2058
// 2. this is not a breakpoint exception, AND
2059
// 3. this is not a C++ exception (VC++ implements them via SEH,
2060
// apparently).
2061
//
2062
// SEH exception code for C++ exceptions.
2063
// (see http://support.microsoft.com/kb/185294 for more information).
2064
const DWORD kCxxExceptionCode = 0xe06d7363;
2065
2066
bool should_handle = true;
2067
2068
if (!GTEST_FLAG(catch_exceptions))
2069
should_handle = false;
2070
else if (exception_code == EXCEPTION_BREAKPOINT)
2071
should_handle = false;
2072
else if (exception_code == kCxxExceptionCode)
2073
should_handle = false;
2074
2075
return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2076
}
2077
#endif // GTEST_HAS_SEH
2078
2079
} // namespace internal
2080
2081
// The c'tor sets this object as the test part result reporter used by
2082
// Google Test. The 'result' parameter specifies where to report the
2083
// results. Intercepts only failures from the current thread.
2084
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2085
TestPartResultArray* result)
2086
: intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2087
result_(result) {
2088
Init();
2089
}
2090
2091
// The c'tor sets this object as the test part result reporter used by
2092
// Google Test. The 'result' parameter specifies where to report the
2093
// results.
2094
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2095
InterceptMode intercept_mode, TestPartResultArray* result)
2096
: intercept_mode_(intercept_mode),
2097
result_(result) {
2098
Init();
2099
}
2100
2101
void ScopedFakeTestPartResultReporter::Init() {
2102
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2103
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2104
old_reporter_ = impl->GetGlobalTestPartResultReporter();
2105
impl->SetGlobalTestPartResultReporter(this);
2106
} else {
2107
old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2108
impl->SetTestPartResultReporterForCurrentThread(this);
2109
}
2110
}
2111
2112
// The d'tor restores the test part result reporter used by Google Test
2113
// before.
2114
ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2115
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2116
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2117
impl->SetGlobalTestPartResultReporter(old_reporter_);
2118
} else {
2119
impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2120
}
2121
}
2122
2123
// Increments the test part result count and remembers the result.
2124
// This method is from the TestPartResultReporterInterface interface.
2125
void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2126
const TestPartResult& result) {
2127
result_->Append(result);
2128
}
2129
2130
namespace internal {
2131
2132
// Returns the type ID of ::testing::Test. We should always call this
2133
// instead of GetTypeId< ::testing::Test>() to get the type ID of
2134
// testing::Test. This is to work around a suspected linker bug when
2135
// using Google Test as a framework on Mac OS X. The bug causes
2136
// GetTypeId< ::testing::Test>() to return different values depending
2137
// on whether the call is from the Google Test framework itself or
2138
// from user test code. GetTestTypeId() is guaranteed to always
2139
// return the same value, as it always calls GetTypeId<>() from the
2140
// gtest.cc, which is within the Google Test framework.
2141
TypeId GetTestTypeId() {
2142
return GetTypeId<Test>();
2143
}
2144
2145
// The value of GetTestTypeId() as seen from within the Google Test
2146
// library. This is solely for testing GetTestTypeId().
2147
extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2148
2149
// This predicate-formatter checks that 'results' contains a test part
2150
// failure of the given type and that the failure message contains the
2151
// given substring.
2152
static AssertionResult HasOneFailure(const char* /* results_expr */,
2153
const char* /* type_expr */,
2154
const char* /* substr_expr */,
2155
const TestPartResultArray& results,
2156
TestPartResult::Type type,
2157
const std::string& substr) {
2158
const std::string expected(type == TestPartResult::kFatalFailure ?
2159
"1 fatal failure" :
2160
"1 non-fatal failure");
2161
Message msg;
2162
if (results.size() != 1) {
2163
msg << "Expected: " << expected << "\n"
2164
<< " Actual: " << results.size() << " failures";
2165
for (int i = 0; i < results.size(); i++) {
2166
msg << "\n" << results.GetTestPartResult(i);
2167
}
2168
return AssertionFailure() << msg;
2169
}
2170
2171
const TestPartResult& r = results.GetTestPartResult(0);
2172
if (r.type() != type) {
2173
return AssertionFailure() << "Expected: " << expected << "\n"
2174
<< " Actual:\n"
2175
<< r;
2176
}
2177
2178
if (strstr(r.message(), substr.c_str()) == NULL) {
2179
return AssertionFailure() << "Expected: " << expected << " containing \""
2180
<< substr << "\"\n"
2181
<< " Actual:\n"
2182
<< r;
2183
}
2184
2185
return AssertionSuccess();
2186
}
2187
2188
// The constructor of SingleFailureChecker remembers where to look up
2189
// test part results, what type of failure we expect, and what
2190
// substring the failure message should contain.
2191
SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
2192
TestPartResult::Type type,
2193
const std::string& substr)
2194
: results_(results), type_(type), substr_(substr) {}
2195
2196
// The destructor of SingleFailureChecker verifies that the given
2197
// TestPartResultArray contains exactly one failure that has the given
2198
// type and contains the given substring. If that's not the case, a
2199
// non-fatal failure will be generated.
2200
SingleFailureChecker::~SingleFailureChecker() {
2201
EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2202
}
2203
2204
DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2205
UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2206
2207
void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2208
const TestPartResult& result) {
2209
unit_test_->current_test_result()->AddTestPartResult(result);
2210
unit_test_->listeners()->repeater()->OnTestPartResult(result);
2211
}
2212
2213
DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2214
UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2215
2216
void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2217
const TestPartResult& result) {
2218
unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2219
}
2220
2221
// Returns the global test part result reporter.
2222
TestPartResultReporterInterface*
2223
UnitTestImpl::GetGlobalTestPartResultReporter() {
2224
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2225
return global_test_part_result_repoter_;
2226
}
2227
2228
// Sets the global test part result reporter.
2229
void UnitTestImpl::SetGlobalTestPartResultReporter(
2230
TestPartResultReporterInterface* reporter) {
2231
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2232
global_test_part_result_repoter_ = reporter;
2233
}
2234
2235
// Returns the test part result reporter for the current thread.
2236
TestPartResultReporterInterface*
2237
UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2238
return per_thread_test_part_result_reporter_.get();
2239
}
2240
2241
// Sets the test part result reporter for the current thread.
2242
void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2243
TestPartResultReporterInterface* reporter) {
2244
per_thread_test_part_result_reporter_.set(reporter);
2245
}
2246
2247
// Gets the number of successful test cases.
2248
int UnitTestImpl::successful_test_case_count() const {
2249
return CountIf(test_cases_, TestCasePassed);
2250
}
2251
2252
// Gets the number of failed test cases.
2253
int UnitTestImpl::failed_test_case_count() const {
2254
return CountIf(test_cases_, TestCaseFailed);
2255
}
2256
2257
// Gets the number of all test cases.
2258
int UnitTestImpl::total_test_case_count() const {
2259
return static_cast<int>(test_cases_.size());
2260
}
2261
2262
// Gets the number of all test cases that contain at least one test
2263
// that should run.
2264
int UnitTestImpl::test_case_to_run_count() const {
2265
return CountIf(test_cases_, ShouldRunTestCase);
2266
}
2267
2268
// Gets the number of successful tests.
2269
int UnitTestImpl::successful_test_count() const {
2270
return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2271
}
2272
2273
// Gets the number of failed tests.
2274
int UnitTestImpl::failed_test_count() const {
2275
return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2276
}
2277
2278
// Gets the number of disabled tests that will be reported in the XML report.
2279
int UnitTestImpl::reportable_disabled_test_count() const {
2280
return SumOverTestCaseList(test_cases_,
2281
&TestCase::reportable_disabled_test_count);
2282
}
2283
2284
// Gets the number of disabled tests.
2285
int UnitTestImpl::disabled_test_count() const {
2286
return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2287
}
2288
2289
// Gets the number of tests to be printed in the XML report.
2290
int UnitTestImpl::reportable_test_count() const {
2291
return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
2292
}
2293
2294
// Gets the number of all tests.
2295
int UnitTestImpl::total_test_count() const {
2296
return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2297
}
2298
2299
// Gets the number of tests that should run.
2300
int UnitTestImpl::test_to_run_count() const {
2301
return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2302
}
2303
2304
// Returns the current OS stack trace as an std::string.
2305
//
2306
// The maximum number of stack frames to be included is specified by
2307
// the gtest_stack_trace_depth flag. The skip_count parameter
2308
// specifies the number of top frames to be skipped, which doesn't
2309
// count against the number of frames to be included.
2310
//
2311
// For example, if Foo() calls Bar(), which in turn calls
2312
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2313
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2314
std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2315
return os_stack_trace_getter()->CurrentStackTrace(
2316
static_cast<int>(GTEST_FLAG(stack_trace_depth)),
2317
skip_count + 1
2318
// Skips the user-specified number of frames plus this function
2319
// itself.
2320
); // NOLINT
2321
}
2322
2323
// Returns the current time in milliseconds.
2324
TimeInMillis GetTimeInMillis() {
2325
#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2326
// Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2327
// http://analogous.blogspot.com/2005/04/epoch.html
2328
const TimeInMillis kJavaEpochToWinFileTimeDelta =
2329
static_cast<TimeInMillis>(116444736UL) * 100000UL;
2330
const DWORD kTenthMicrosInMilliSecond = 10000;
2331
2332
SYSTEMTIME now_systime;
2333
FILETIME now_filetime;
2334
ULARGE_INTEGER now_int64;
2335
// FIXME: Shouldn't this just use
2336
// GetSystemTimeAsFileTime()?
2337
GetSystemTime(&now_systime);
2338
if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2339
now_int64.LowPart = now_filetime.dwLowDateTime;
2340
now_int64.HighPart = now_filetime.dwHighDateTime;
2341
now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2342
kJavaEpochToWinFileTimeDelta;
2343
return now_int64.QuadPart;
2344
}
2345
return 0;
2346
#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2347
__timeb64 now;
2348
2349
// MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2350
// (deprecated function) there.
2351
// FIXME: Use GetTickCount()? Or use
2352
// SystemTimeToFileTime()
2353
GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
2354
_ftime64(&now);
2355
GTEST_DISABLE_MSC_DEPRECATED_POP_()
2356
2357
return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2358
#elif GTEST_HAS_GETTIMEOFDAY_
2359
struct timeval now;
2360
gettimeofday(&now, NULL);
2361
return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2362
#else
2363
# error "Don't know how to get the current time on your system."
2364
#endif
2365
}
2366
2367
// Utilities
2368
2369
// class String.
2370
2371
#if GTEST_OS_WINDOWS_MOBILE
2372
// Creates a UTF-16 wide string from the given ANSI string, allocating
2373
// memory using new. The caller is responsible for deleting the return
2374
// value using delete[]. Returns the wide string, or NULL if the
2375
// input is NULL.
2376
LPCWSTR String::AnsiToUtf16(const char* ansi) {
2377
if (!ansi) return NULL;
2378
const int length = strlen(ansi);
2379
const int unicode_length =
2380
MultiByteToWideChar(CP_ACP, 0, ansi, length,
2381
NULL, 0);
2382
WCHAR* unicode = new WCHAR[unicode_length + 1];
2383
MultiByteToWideChar(CP_ACP, 0, ansi, length,
2384
unicode, unicode_length);
2385
unicode[unicode_length] = 0;
2386
return unicode;
2387
}
2388
2389
// Creates an ANSI string from the given wide string, allocating
2390
// memory using new. The caller is responsible for deleting the return
2391
// value using delete[]. Returns the ANSI string, or NULL if the
2392
// input is NULL.
2393
const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2394
if (!utf16_str) return NULL;
2395
const int ansi_length =
2396
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2397
NULL, 0, NULL, NULL);
2398
char* ansi = new char[ansi_length + 1];
2399
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2400
ansi, ansi_length, NULL, NULL);
2401
ansi[ansi_length] = 0;
2402
return ansi;
2403
}
2404
2405
#endif // GTEST_OS_WINDOWS_MOBILE
2406
2407
// Compares two C strings. Returns true iff they have the same content.
2408
//
2409
// Unlike strcmp(), this function can handle NULL argument(s). A NULL
2410
// C string is considered different to any non-NULL C string,
2411
// including the empty string.
2412
bool String::CStringEquals(const char * lhs, const char * rhs) {
2413
if ( lhs == NULL ) return rhs == NULL;
2414
2415
if ( rhs == NULL ) return false;
2416
2417
return strcmp(lhs, rhs) == 0;
2418
}
2419
2420
#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2421
2422
// Converts an array of wide chars to a narrow string using the UTF-8
2423
// encoding, and streams the result to the given Message object.
2424
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2425
Message* msg) {
2426
for (size_t i = 0; i != length; ) { // NOLINT
2427
if (wstr[i] != L'\0') {
2428
*msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2429
while (i != length && wstr[i] != L'\0')
2430
i++;
2431
} else {
2432
*msg << '\0';
2433
i++;
2434
}
2435
}
2436
}
2437
2438
#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2439
2440
void SplitString(const ::std::string& str, char delimiter,
2441
::std::vector< ::std::string>* dest) {
2442
::std::vector< ::std::string> parsed;
2443
::std::string::size_type pos = 0;
2444
while (::testing::internal::AlwaysTrue()) {
2445
const ::std::string::size_type colon = str.find(delimiter, pos);
2446
if (colon == ::std::string::npos) {
2447
parsed.push_back(str.substr(pos));
2448
break;
2449
} else {
2450
parsed.push_back(str.substr(pos, colon - pos));
2451
pos = colon + 1;
2452
}
2453
}
2454
dest->swap(parsed);
2455
}
2456
2457
} // namespace internal
2458
2459
// Constructs an empty Message.
2460
// We allocate the stringstream separately because otherwise each use of
2461
// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2462
// stack frame leading to huge stack frames in some cases; gcc does not reuse
2463
// the stack space.
2464
Message::Message() : ss_(new ::std::stringstream) {
2465
// By default, we want there to be enough precision when printing
2466
// a double to a Message.
2467
*ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2468
}
2469
2470
// These two overloads allow streaming a wide C string to a Message
2471
// using the UTF-8 encoding.
2472
Message& Message::operator <<(const wchar_t* wide_c_str) {
2473
return *this << internal::String::ShowWideCString(wide_c_str);
2474
}
2475
Message& Message::operator <<(wchar_t* wide_c_str) {
2476
return *this << internal::String::ShowWideCString(wide_c_str);
2477
}
2478
2479
#if GTEST_HAS_STD_WSTRING
2480
// Converts the given wide string to a narrow string using the UTF-8
2481
// encoding, and streams the result to this Message object.
2482
Message& Message::operator <<(const ::std::wstring& wstr) {
2483
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2484
return *this;
2485
}
2486
#endif // GTEST_HAS_STD_WSTRING
2487
2488
#if GTEST_HAS_GLOBAL_WSTRING
2489
// Converts the given wide string to a narrow string using the UTF-8
2490
// encoding, and streams the result to this Message object.
2491
Message& Message::operator <<(const ::wstring& wstr) {
2492
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2493
return *this;
2494
}
2495
#endif // GTEST_HAS_GLOBAL_WSTRING
2496
2497
// Gets the text streamed to this object so far as an std::string.
2498
// Each '\0' character in the buffer is replaced with "\\0".
2499
std::string Message::GetString() const {
2500
return internal::StringStreamToString(ss_.get());
2501
}
2502
2503
// AssertionResult constructors.
2504
// Used in EXPECT_TRUE/FALSE(assertion_result).
2505
AssertionResult::AssertionResult(const AssertionResult& other)
2506
: success_(other.success_),
2507
message_(other.message_.get() != NULL ?
2508
new ::std::string(*other.message_) :
2509
static_cast< ::std::string*>(NULL)) {
2510
}
2511
2512
// Swaps two AssertionResults.
2513
void AssertionResult::swap(AssertionResult& other) {
2514
using std::swap;
2515
swap(success_, other.success_);
2516
swap(message_, other.message_);
2517
}
2518
2519
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2520
AssertionResult AssertionResult::operator!() const {
2521
AssertionResult negation(!success_);
2522
if (message_.get() != NULL)
2523
negation << *message_;
2524
return negation;
2525
}
2526
2527
// Makes a successful assertion result.
2528
AssertionResult AssertionSuccess() {
2529
return AssertionResult(true);
2530
}
2531
2532
// Makes a failed assertion result.
2533
AssertionResult AssertionFailure() {
2534
return AssertionResult(false);
2535
}
2536
2537
// Makes a failed assertion result with the given failure message.
2538
// Deprecated; use AssertionFailure() << message.
2539
AssertionResult AssertionFailure(const Message& message) {
2540
return AssertionFailure() << message;
2541
}
2542
2543
namespace internal {
2544
2545
namespace edit_distance {
2546
std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
2547
const std::vector<size_t>& right) {
2548
std::vector<std::vector<double> > costs(
2549
left.size() + 1, std::vector<double>(right.size() + 1));
2550
std::vector<std::vector<EditType> > best_move(
2551
left.size() + 1, std::vector<EditType>(right.size() + 1));
2552
2553
// Populate for empty right.
2554
for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
2555
costs[l_i][0] = static_cast<double>(l_i);
2556
best_move[l_i][0] = kRemove;
2557
}
2558
// Populate for empty left.
2559
for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2560
costs[0][r_i] = static_cast<double>(r_i);
2561
best_move[0][r_i] = kAdd;
2562
}
2563
2564
for (size_t l_i = 0; l_i < left.size(); ++l_i) {
2565
for (size_t r_i = 0; r_i < right.size(); ++r_i) {
2566
if (left[l_i] == right[r_i]) {
2567
// Found a match. Consume it.
2568
costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2569
best_move[l_i + 1][r_i + 1] = kMatch;
2570
continue;
2571
}
2572
2573
const double add = costs[l_i + 1][r_i];
2574
const double remove = costs[l_i][r_i + 1];
2575
const double replace = costs[l_i][r_i];
2576
if (add < remove && add < replace) {
2577
costs[l_i + 1][r_i + 1] = add + 1;
2578
best_move[l_i + 1][r_i + 1] = kAdd;
2579
} else if (remove < add && remove < replace) {
2580
costs[l_i + 1][r_i + 1] = remove + 1;
2581
best_move[l_i + 1][r_i + 1] = kRemove;
2582
} else {
2583
// We make replace a little more expensive than add/remove to lower
2584
// their priority.
2585
costs[l_i + 1][r_i + 1] = replace + 1.00001;
2586
best_move[l_i + 1][r_i + 1] = kReplace;
2587
}
2588
}
2589
}
2590
2591
// Reconstruct the best path. We do it in reverse order.
2592
std::vector<EditType> best_path;
2593
for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2594
EditType move = best_move[l_i][r_i];
2595
best_path.push_back(move);
2596
l_i -= move != kAdd;
2597
r_i -= move != kRemove;
2598
}
2599
std::reverse(best_path.begin(), best_path.end());
2600
return best_path;
2601
}
2602
2603
namespace {
2604
2605
// Helper class to convert string into ids with deduplication.
2606
class InternalStrings {
2607
public:
2608
size_t GetId(const std::string& str) {
2609
IdMap::iterator it = ids_.find(str);
2610
if (it != ids_.end()) return it->second;
2611
size_t id = ids_.size();
2612
return ids_[str] = id;
2613
}
2614
2615
private:
2616
typedef std::map<std::string, size_t> IdMap;
2617
IdMap ids_;
2618
};
2619
2620
} // namespace
2621
2622
std::vector<EditType> CalculateOptimalEdits(
2623
const std::vector<std::string>& left,
2624
const std::vector<std::string>& right) {
2625
std::vector<size_t> left_ids, right_ids;
2626
{
2627
InternalStrings intern_table;
2628
for (size_t i = 0; i < left.size(); ++i) {
2629
left_ids.push_back(intern_table.GetId(left[i]));
2630
}
2631
for (size_t i = 0; i < right.size(); ++i) {
2632
right_ids.push_back(intern_table.GetId(right[i]));
2633
}
2634
}
2635
return CalculateOptimalEdits(left_ids, right_ids);
2636
}
2637
2638
namespace {
2639
2640
// Helper class that holds the state for one hunk and prints it out to the
2641
// stream.
2642
// It reorders adds/removes when possible to group all removes before all
2643
// adds. It also adds the hunk header before printint into the stream.
2644
class Hunk {
2645
public:
2646
Hunk(size_t left_start, size_t right_start)
2647
: left_start_(left_start),
2648
right_start_(right_start),
2649
adds_(),
2650
removes_(),
2651
common_() {}
2652
2653
void PushLine(char edit, const char* line) {
2654
switch (edit) {
2655
case ' ':
2656
++common_;
2657
FlushEdits();
2658
hunk_.push_back(std::make_pair(' ', line));
2659
break;
2660
case '-':
2661
++removes_;
2662
hunk_removes_.push_back(std::make_pair('-', line));
2663
break;
2664
case '+':
2665
++adds_;
2666
hunk_adds_.push_back(std::make_pair('+', line));
2667
break;
2668
}
2669
}
2670
2671
void PrintTo(std::ostream* os) {
2672
PrintHeader(os);
2673
FlushEdits();
2674
for (std::list<std::pair<char, const char*> >::const_iterator it =
2675
hunk_.begin();
2676
it != hunk_.end(); ++it) {
2677
*os << it->first << it->second << "\n";
2678
}
2679
}
2680
2681
bool has_edits() const { return adds_ || removes_; }
2682
2683
private:
2684
void FlushEdits() {
2685
hunk_.splice(hunk_.end(), hunk_removes_);
2686
hunk_.splice(hunk_.end(), hunk_adds_);
2687
}
2688
2689
// Print a unified diff header for one hunk.
2690
// The format is
2691
// "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
2692
// where the left/right parts are omitted if unnecessary.
2693
void PrintHeader(std::ostream* ss) const {
2694
*ss << "@@ ";
2695
if (removes_) {
2696
*ss << "-" << left_start_ << "," << (removes_ + common_);
2697
}
2698
if (removes_ && adds_) {
2699
*ss << " ";
2700
}
2701
if (adds_) {
2702
*ss << "+" << right_start_ << "," << (adds_ + common_);
2703
}
2704
*ss << " @@\n";
2705
}
2706
2707
size_t left_start_, right_start_;
2708
size_t adds_, removes_, common_;
2709
std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
2710
};
2711
2712
} // namespace
2713
2714
// Create a list of diff hunks in Unified diff format.
2715
// Each hunk has a header generated by PrintHeader above plus a body with
2716
// lines prefixed with ' ' for no change, '-' for deletion and '+' for
2717
// addition.
2718
// 'context' represents the desired unchanged prefix/suffix around the diff.
2719
// If two hunks are close enough that their contexts overlap, then they are
2720
// joined into one hunk.
2721
std::string CreateUnifiedDiff(const std::vector<std::string>& left,
2722
const std::vector<std::string>& right,
2723
size_t context) {
2724
const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
2725
2726
size_t l_i = 0, r_i = 0, edit_i = 0;
2727
std::stringstream ss;
2728
while (edit_i < edits.size()) {
2729
// Find first edit.
2730
while (edit_i < edits.size() && edits[edit_i] == kMatch) {
2731
++l_i;
2732
++r_i;
2733
++edit_i;
2734
}
2735
2736
// Find the first line to include in the hunk.
2737
const size_t prefix_context = std::min(l_i, context);
2738
Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2739
for (size_t i = prefix_context; i > 0; --i) {
2740
hunk.PushLine(' ', left[l_i - i].c_str());
2741
}
2742
2743
// Iterate the edits until we found enough suffix for the hunk or the input
2744
// is over.
2745
size_t n_suffix = 0;
2746
for (; edit_i < edits.size(); ++edit_i) {
2747
if (n_suffix >= context) {
2748
// Continue only if the next hunk is very close.
2749
std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
2750
while (it != edits.end() && *it == kMatch) ++it;
2751
if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
2752
// There is no next edit or it is too far away.
2753
break;
2754
}
2755
}
2756
2757
EditType edit = edits[edit_i];
2758
// Reset count when a non match is found.
2759
n_suffix = edit == kMatch ? n_suffix + 1 : 0;
2760
2761
if (edit == kMatch || edit == kRemove || edit == kReplace) {
2762
hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
2763
}
2764
if (edit == kAdd || edit == kReplace) {
2765
hunk.PushLine('+', right[r_i].c_str());
2766
}
2767
2768
// Advance indices, depending on edit type.
2769
l_i += edit != kAdd;
2770
r_i += edit != kRemove;
2771
}
2772
2773
if (!hunk.has_edits()) {
2774
// We are done. We don't want this hunk.
2775
break;
2776
}
2777
2778
hunk.PrintTo(&ss);
2779
}
2780
return ss.str();
2781
}
2782
2783
} // namespace edit_distance
2784
2785
namespace {
2786
2787
// The string representation of the values received in EqFailure() are already
2788
// escaped. Split them on escaped '\n' boundaries. Leave all other escaped
2789
// characters the same.
2790
std::vector<std::string> SplitEscapedString(const std::string& str) {
2791
std::vector<std::string> lines;
2792
size_t start = 0, end = str.size();
2793
if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
2794
++start;
2795
--end;
2796
}
2797
bool escaped = false;
2798
for (size_t i = start; i + 1 < end; ++i) {
2799
if (escaped) {
2800
escaped = false;
2801
if (str[i] == 'n') {
2802
lines.push_back(str.substr(start, i - start - 1));
2803
start = i + 1;
2804
}
2805
} else {
2806
escaped = str[i] == '\\';
2807
}
2808
}
2809
lines.push_back(str.substr(start, end - start));
2810
return lines;
2811
}
2812
2813
} // namespace
2814
2815
// Constructs and returns the message for an equality assertion
2816
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2817
//
2818
// The first four parameters are the expressions used in the assertion
2819
// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2820
// where foo is 5 and bar is 6, we have:
2821
//
2822
// lhs_expression: "foo"
2823
// rhs_expression: "bar"
2824
// lhs_value: "5"
2825
// rhs_value: "6"
2826
//
2827
// The ignoring_case parameter is true iff the assertion is a
2828
// *_STRCASEEQ*. When it's true, the string "Ignoring case" will
2829
// be inserted into the message.
2830
AssertionResult EqFailure(const char* lhs_expression,
2831
const char* rhs_expression,
2832
const std::string& lhs_value,
2833
const std::string& rhs_value,
2834
bool ignoring_case) {
2835
Message msg;
2836
msg << "Expected equality of these values:";
2837
msg << "\n " << lhs_expression;
2838
if (lhs_value != lhs_expression) {
2839
msg << "\n Which is: " << lhs_value;
2840
}
2841
msg << "\n " << rhs_expression;
2842
if (rhs_value != rhs_expression) {
2843
msg << "\n Which is: " << rhs_value;
2844
}
2845
2846
if (ignoring_case) {
2847
msg << "\nIgnoring case";
2848
}
2849
2850
if (!lhs_value.empty() && !rhs_value.empty()) {
2851
const std::vector<std::string> lhs_lines =
2852
SplitEscapedString(lhs_value);
2853
const std::vector<std::string> rhs_lines =
2854
SplitEscapedString(rhs_value);
2855
if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
2856
msg << "\nWith diff:\n"
2857
<< edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
2858
}
2859
}
2860
2861
return AssertionFailure() << msg;
2862
}
2863
2864
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2865
std::string GetBoolAssertionFailureMessage(
2866
const AssertionResult& assertion_result,
2867
const char* expression_text,
2868
const char* actual_predicate_value,
2869
const char* expected_predicate_value) {
2870
const char* actual_message = assertion_result.message();
2871
Message msg;
2872
msg << "Value of: " << expression_text
2873
<< "\n Actual: " << actual_predicate_value;
2874
if (actual_message[0] != '\0')
2875
msg << " (" << actual_message << ")";
2876
msg << "\nExpected: " << expected_predicate_value;
2877
return msg.GetString();
2878
}
2879
2880
// Helper function for implementing ASSERT_NEAR.
2881
AssertionResult DoubleNearPredFormat(const char* expr1,
2882
const char* expr2,
2883
const char* abs_error_expr,
2884
double val1,
2885
double val2,
2886
double abs_error) {
2887
const double diff = fabs(val1 - val2);
2888
if (diff <= abs_error) return AssertionSuccess();
2889
2890
// FIXME: do not print the value of an expression if it's
2891
// already a literal.
2892
return AssertionFailure()
2893
<< "The difference between " << expr1 << " and " << expr2
2894
<< " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2895
<< expr1 << " evaluates to " << val1 << ",\n"
2896
<< expr2 << " evaluates to " << val2 << ", and\n"
2897
<< abs_error_expr << " evaluates to " << abs_error << ".";
2898
}
2899
2900
2901
// Helper template for implementing FloatLE() and DoubleLE().
2902
template <typename RawType>
2903
AssertionResult FloatingPointLE(const char* expr1,
2904
const char* expr2,
2905
RawType val1,
2906
RawType val2) {
2907
// Returns success if val1 is less than val2,
2908
if (val1 < val2) {
2909
return AssertionSuccess();
2910
}
2911
2912
// or if val1 is almost equal to val2.
2913
const FloatingPoint<RawType> lhs(val1), rhs(val2);
2914
if (lhs.AlmostEquals(rhs)) {
2915
return AssertionSuccess();
2916
}
2917
2918
// Note that the above two checks will both fail if either val1 or
2919
// val2 is NaN, as the IEEE floating-point standard requires that
2920
// any predicate involving a NaN must return false.
2921
2922
::std::stringstream val1_ss;
2923
val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2924
<< val1;
2925
2926
::std::stringstream val2_ss;
2927
val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2928
<< val2;
2929
2930
return AssertionFailure()
2931
<< "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2932
<< " Actual: " << StringStreamToString(&val1_ss) << " vs "
2933
<< StringStreamToString(&val2_ss);
2934
}
2935
2936
} // namespace internal
2937
2938
// Asserts that val1 is less than, or almost equal to, val2. Fails
2939
// otherwise. In particular, it fails if either val1 or val2 is NaN.
2940
AssertionResult FloatLE(const char* expr1, const char* expr2,
2941
float val1, float val2) {
2942
return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2943
}
2944
2945
// Asserts that val1 is less than, or almost equal to, val2. Fails
2946
// otherwise. In particular, it fails if either val1 or val2 is NaN.
2947
AssertionResult DoubleLE(const char* expr1, const char* expr2,
2948
double val1, double val2) {
2949
return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2950
}
2951
2952
namespace internal {
2953
2954
// The helper function for {ASSERT|EXPECT}_EQ with int or enum
2955
// arguments.
2956
AssertionResult CmpHelperEQ(const char* lhs_expression,
2957
const char* rhs_expression,
2958
BiggestInt lhs,
2959
BiggestInt rhs) {
2960
if (lhs == rhs) {
2961
return AssertionSuccess();
2962
}
2963
2964
return EqFailure(lhs_expression,
2965
rhs_expression,
2966
FormatForComparisonFailureMessage(lhs, rhs),
2967
FormatForComparisonFailureMessage(rhs, lhs),
2968
false);
2969
}
2970
2971
// A macro for implementing the helper functions needed to implement
2972
// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2973
// just to avoid copy-and-paste of similar code.
2974
#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2975
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2976
BiggestInt val1, BiggestInt val2) {\
2977
if (val1 op val2) {\
2978
return AssertionSuccess();\
2979
} else {\
2980
return AssertionFailure() \
2981
<< "Expected: (" << expr1 << ") " #op " (" << expr2\
2982
<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2983
<< " vs " << FormatForComparisonFailureMessage(val2, val1);\
2984
}\
2985
}
2986
2987
// Implements the helper function for {ASSERT|EXPECT}_NE with int or
2988
// enum arguments.
2989
GTEST_IMPL_CMP_HELPER_(NE, !=)
2990
// Implements the helper function for {ASSERT|EXPECT}_LE with int or
2991
// enum arguments.
2992
GTEST_IMPL_CMP_HELPER_(LE, <=)
2993
// Implements the helper function for {ASSERT|EXPECT}_LT with int or
2994
// enum arguments.
2995
GTEST_IMPL_CMP_HELPER_(LT, < )
2996
// Implements the helper function for {ASSERT|EXPECT}_GE with int or
2997
// enum arguments.
2998
GTEST_IMPL_CMP_HELPER_(GE, >=)
2999
// Implements the helper function for {ASSERT|EXPECT}_GT with int or
3000
// enum arguments.
3001
GTEST_IMPL_CMP_HELPER_(GT, > )
3002
3003
#undef GTEST_IMPL_CMP_HELPER_
3004
3005
// The helper function for {ASSERT|EXPECT}_STREQ.
3006
AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3007
const char* rhs_expression,
3008
const char* lhs,
3009
const char* rhs) {
3010
if (String::CStringEquals(lhs, rhs)) {
3011
return AssertionSuccess();
3012
}
3013
3014
return EqFailure(lhs_expression,
3015
rhs_expression,
3016
PrintToString(lhs),
3017
PrintToString(rhs),
3018
false);
3019
}
3020
3021
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
3022
AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
3023
const char* rhs_expression,
3024
const char* lhs,
3025
const char* rhs) {
3026
if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
3027
return AssertionSuccess();
3028
}
3029
3030
return EqFailure(lhs_expression,
3031
rhs_expression,
3032
PrintToString(lhs),
3033
PrintToString(rhs),
3034
true);
3035
}
3036
3037
// The helper function for {ASSERT|EXPECT}_STRNE.
3038
AssertionResult CmpHelperSTRNE(const char* s1_expression,
3039
const char* s2_expression,
3040
const char* s1,
3041
const char* s2) {
3042
if (!String::CStringEquals(s1, s2)) {
3043
return AssertionSuccess();
3044
} else {
3045
return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3046
<< s2_expression << "), actual: \""
3047
<< s1 << "\" vs \"" << s2 << "\"";
3048
}
3049
}
3050
3051
// The helper function for {ASSERT|EXPECT}_STRCASENE.
3052
AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
3053
const char* s2_expression,
3054
const char* s1,
3055
const char* s2) {
3056
if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
3057
return AssertionSuccess();
3058
} else {
3059
return AssertionFailure()
3060
<< "Expected: (" << s1_expression << ") != ("
3061
<< s2_expression << ") (ignoring case), actual: \""
3062
<< s1 << "\" vs \"" << s2 << "\"";
3063
}
3064
}
3065
3066
} // namespace internal
3067
3068
namespace {
3069
3070
// Helper functions for implementing IsSubString() and IsNotSubstring().
3071
3072
// This group of overloaded functions return true iff needle is a
3073
// substring of haystack. NULL is considered a substring of itself
3074
// only.
3075
3076
bool IsSubstringPred(const char* needle, const char* haystack) {
3077
if (needle == NULL || haystack == NULL)
3078
return needle == haystack;
3079
3080
return strstr(haystack, needle) != NULL;
3081
}
3082
3083
bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
3084
if (needle == NULL || haystack == NULL)
3085
return needle == haystack;
3086
3087
return wcsstr(haystack, needle) != NULL;
3088
}
3089
3090
// StringType here can be either ::std::string or ::std::wstring.
3091
template <typename StringType>
3092
bool IsSubstringPred(const StringType& needle,
3093
const StringType& haystack) {
3094
return haystack.find(needle) != StringType::npos;
3095
}
3096
3097
// This function implements either IsSubstring() or IsNotSubstring(),
3098
// depending on the value of the expected_to_be_substring parameter.
3099
// StringType here can be const char*, const wchar_t*, ::std::string,
3100
// or ::std::wstring.
3101
template <typename StringType>
3102
AssertionResult IsSubstringImpl(
3103
bool expected_to_be_substring,
3104
const char* needle_expr, const char* haystack_expr,
3105
const StringType& needle, const StringType& haystack) {
3106
if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3107
return AssertionSuccess();
3108
3109
const bool is_wide_string = sizeof(needle[0]) > 1;
3110
const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
3111
return AssertionFailure()
3112
<< "Value of: " << needle_expr << "\n"
3113
<< " Actual: " << begin_string_quote << needle << "\"\n"
3114
<< "Expected: " << (expected_to_be_substring ? "" : "not ")
3115
<< "a substring of " << haystack_expr << "\n"
3116
<< "Which is: " << begin_string_quote << haystack << "\"";
3117
}
3118
3119
} // namespace
3120
3121
// IsSubstring() and IsNotSubstring() check whether needle is a
3122
// substring of haystack (NULL is considered a substring of itself
3123
// only), and return an appropriate error message when they fail.
3124
3125
AssertionResult IsSubstring(
3126
const char* needle_expr, const char* haystack_expr,
3127
const char* needle, const char* haystack) {
3128
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3129
}
3130
3131
AssertionResult IsSubstring(
3132
const char* needle_expr, const char* haystack_expr,
3133
const wchar_t* needle, const wchar_t* haystack) {
3134
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3135
}
3136
3137
AssertionResult IsNotSubstring(
3138
const char* needle_expr, const char* haystack_expr,
3139
const char* needle, const char* haystack) {
3140
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3141
}
3142
3143
AssertionResult IsNotSubstring(
3144
const char* needle_expr, const char* haystack_expr,
3145
const wchar_t* needle, const wchar_t* haystack) {
3146
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3147
}
3148
3149
AssertionResult IsSubstring(
3150
const char* needle_expr, const char* haystack_expr,
3151
const ::std::string& needle, const ::std::string& haystack) {
3152
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3153
}
3154
3155
AssertionResult IsNotSubstring(
3156
const char* needle_expr, const char* haystack_expr,
3157
const ::std::string& needle, const ::std::string& haystack) {
3158
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3159
}
3160
3161
#if GTEST_HAS_STD_WSTRING
3162
AssertionResult IsSubstring(
3163
const char* needle_expr, const char* haystack_expr,
3164
const ::std::wstring& needle, const ::std::wstring& haystack) {
3165
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3166
}
3167
3168
AssertionResult IsNotSubstring(
3169
const char* needle_expr, const char* haystack_expr,
3170
const ::std::wstring& needle, const ::std::wstring& haystack) {
3171
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3172
}
3173
#endif // GTEST_HAS_STD_WSTRING
3174
3175
namespace internal {
3176
3177
#if GTEST_OS_WINDOWS
3178
3179
namespace {
3180
3181
// Helper function for IsHRESULT{SuccessFailure} predicates
3182
AssertionResult HRESULTFailureHelper(const char* expr,
3183
const char* expected,
3184
long hr) { // NOLINT
3185
# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
3186
3187
// Windows CE doesn't support FormatMessage.
3188
const char error_text[] = "";
3189
3190
# else
3191
3192
// Looks up the human-readable system message for the HRESULT code
3193
// and since we're not passing any params to FormatMessage, we don't
3194
// want inserts expanded.
3195
const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3196
FORMAT_MESSAGE_IGNORE_INSERTS;
3197
const DWORD kBufSize = 4096;
3198
// Gets the system's human readable message string for this HRESULT.
3199
char error_text[kBufSize] = { '\0' };
3200
DWORD message_length = ::FormatMessageA(kFlags,
3201
0, // no source, we're asking system
3202
hr, // the error
3203
0, // no line width restrictions
3204
error_text, // output buffer
3205
kBufSize, // buf size
3206
NULL); // no arguments for inserts
3207
// Trims tailing white space (FormatMessage leaves a trailing CR-LF)
3208
for (; message_length && IsSpace(error_text[message_length - 1]);
3209
--message_length) {
3210
error_text[message_length - 1] = '\0';
3211
}
3212
3213
# endif // GTEST_OS_WINDOWS_MOBILE
3214
3215
const std::string error_hex("0x" + String::FormatHexInt(hr));
3216
return ::testing::AssertionFailure()
3217
<< "Expected: " << expr << " " << expected << ".\n"
3218
<< " Actual: " << error_hex << " " << error_text << "\n";
3219
}
3220
3221
} // namespace
3222
3223
AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
3224
if (SUCCEEDED(hr)) {
3225
return AssertionSuccess();
3226
}
3227
return HRESULTFailureHelper(expr, "succeeds", hr);
3228
}
3229
3230
AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
3231
if (FAILED(hr)) {
3232
return AssertionSuccess();
3233
}
3234
return HRESULTFailureHelper(expr, "fails", hr);
3235
}
3236
3237
#endif // GTEST_OS_WINDOWS
3238
3239
// Utility functions for encoding Unicode text (wide strings) in
3240
// UTF-8.
3241
3242
// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
3243
// like this:
3244
//
3245
// Code-point length Encoding
3246
// 0 - 7 bits 0xxxxxxx
3247
// 8 - 11 bits 110xxxxx 10xxxxxx
3248
// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
3249
// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
3250
3251
// The maximum code-point a one-byte UTF-8 sequence can represent.
3252
const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
3253
3254
// The maximum code-point a two-byte UTF-8 sequence can represent.
3255
const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
3256
3257
// The maximum code-point a three-byte UTF-8 sequence can represent.
3258
const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
3259
3260
// The maximum code-point a four-byte UTF-8 sequence can represent.
3261
const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
3262
3263
// Chops off the n lowest bits from a bit pattern. Returns the n
3264
// lowest bits. As a side effect, the original bit pattern will be
3265
// shifted to the right by n bits.
3266
inline UInt32 ChopLowBits(UInt32* bits, int n) {
3267
const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
3268
*bits >>= n;
3269
return low_bits;
3270
}
3271
3272
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
3273
// code_point parameter is of type UInt32 because wchar_t may not be
3274
// wide enough to contain a code point.
3275
// If the code_point is not a valid Unicode code point
3276
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
3277
// to "(Invalid Unicode 0xXXXXXXXX)".
3278
std::string CodePointToUtf8(UInt32 code_point) {
3279
if (code_point > kMaxCodePoint4) {
3280
return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
3281
}
3282
3283
char str[5]; // Big enough for the largest valid code point.
3284
if (code_point <= kMaxCodePoint1) {
3285
str[1] = '\0';
3286
str[0] = static_cast<char>(code_point); // 0xxxxxxx
3287
} else if (code_point <= kMaxCodePoint2) {
3288
str[2] = '\0';
3289
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3290
str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
3291
} else if (code_point <= kMaxCodePoint3) {
3292
str[3] = '\0';
3293
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3294
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3295
str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
3296
} else { // code_point <= kMaxCodePoint4
3297
str[4] = '\0';
3298
str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3299
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3300
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3301
str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
3302
}
3303
return str;
3304
}
3305
3306
// The following two functions only make sense if the system
3307
// uses UTF-16 for wide string encoding. All supported systems
3308
// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
3309
3310
// Determines if the arguments constitute UTF-16 surrogate pair
3311
// and thus should be combined into a single Unicode code point
3312
// using CreateCodePointFromUtf16SurrogatePair.
3313
inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
3314
return sizeof(wchar_t) == 2 &&
3315
(first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
3316
}
3317
3318
// Creates a Unicode code point from UTF16 surrogate pair.
3319
inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
3320
wchar_t second) {
3321
const UInt32 mask = (1 << 10) - 1;
3322
return (sizeof(wchar_t) == 2) ?
3323
(((first & mask) << 10) | (second & mask)) + 0x10000 :
3324
// This function should not be called when the condition is
3325
// false, but we provide a sensible default in case it is.
3326
static_cast<UInt32>(first);
3327
}
3328
3329
// Converts a wide string to a narrow string in UTF-8 encoding.
3330
// The wide string is assumed to have the following encoding:
3331
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
3332
// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
3333
// Parameter str points to a null-terminated wide string.
3334
// Parameter num_chars may additionally limit the number
3335
// of wchar_t characters processed. -1 is used when the entire string
3336
// should be processed.
3337
// If the string contains code points that are not valid Unicode code points
3338
// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
3339
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
3340
// and contains invalid UTF-16 surrogate pairs, values in those pairs
3341
// will be encoded as individual Unicode characters from Basic Normal Plane.
3342
std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
3343
if (num_chars == -1)
3344
num_chars = static_cast<int>(wcslen(str));
3345
3346
::std::stringstream stream;
3347
for (int i = 0; i < num_chars; ++i) {
3348
UInt32 unicode_code_point;
3349
3350
if (str[i] == L'\0') {
3351
break;
3352
} else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
3353
unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
3354
str[i + 1]);
3355
i++;
3356
} else {
3357
unicode_code_point = static_cast<UInt32>(str[i]);
3358
}
3359
3360
stream << CodePointToUtf8(unicode_code_point);
3361
}
3362
return StringStreamToString(&stream);
3363
}
3364
3365
// Converts a wide C string to an std::string using the UTF-8 encoding.
3366
// NULL will be converted to "(null)".
3367
std::string String::ShowWideCString(const wchar_t * wide_c_str) {
3368
if (wide_c_str == NULL) return "(null)";
3369
3370
return internal::WideStringToUtf8(wide_c_str, -1);
3371
}
3372
3373
// Compares two wide C strings. Returns true iff they have the same
3374
// content.
3375
//
3376
// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
3377
// C string is considered different to any non-NULL C string,
3378
// including the empty string.
3379
bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3380
if (lhs == NULL) return rhs == NULL;
3381
3382
if (rhs == NULL) return false;
3383
3384
return wcscmp(lhs, rhs) == 0;
3385
}
3386
3387
// Helper function for *_STREQ on wide strings.
3388
AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3389
const char* rhs_expression,
3390
const wchar_t* lhs,
3391
const wchar_t* rhs) {
3392
if (String::WideCStringEquals(lhs, rhs)) {
3393
return AssertionSuccess();
3394
}
3395
3396
return EqFailure(lhs_expression,
3397
rhs_expression,
3398
PrintToString(lhs),
3399
PrintToString(rhs),
3400
false);
3401
}
3402
3403
// Helper function for *_STRNE on wide strings.
3404
AssertionResult CmpHelperSTRNE(const char* s1_expression,
3405
const char* s2_expression,
3406
const wchar_t* s1,
3407
const wchar_t* s2) {
3408
if (!String::WideCStringEquals(s1, s2)) {
3409
return AssertionSuccess();
3410
}
3411
3412
return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3413
<< s2_expression << "), actual: "
3414
<< PrintToString(s1)
3415
<< " vs " << PrintToString(s2);
3416
}
3417
3418
// Compares two C strings, ignoring case. Returns true iff they have
3419
// the same content.
3420
//
3421
// Unlike strcasecmp(), this function can handle NULL argument(s). A
3422
// NULL C string is considered different to any non-NULL C string,
3423
// including the empty string.
3424
bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3425
if (lhs == NULL)
3426
return rhs == NULL;
3427
if (rhs == NULL)
3428
return false;
3429
return posix::StrCaseCmp(lhs, rhs) == 0;
3430
}
3431
3432
// Compares two wide C strings, ignoring case. Returns true iff they
3433
// have the same content.
3434
//
3435
// Unlike wcscasecmp(), this function can handle NULL argument(s).
3436
// A NULL C string is considered different to any non-NULL wide C string,
3437
// including the empty string.
3438
// NB: The implementations on different platforms slightly differ.
3439
// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3440
// environment variable. On GNU platform this method uses wcscasecmp
3441
// which compares according to LC_CTYPE category of the current locale.
3442
// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3443
// current locale.
3444
bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3445
const wchar_t* rhs) {
3446
if (lhs == NULL) return rhs == NULL;
3447
3448
if (rhs == NULL) return false;
3449
3450
#if GTEST_OS_WINDOWS
3451
return _wcsicmp(lhs, rhs) == 0;
3452
#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3453
return wcscasecmp(lhs, rhs) == 0;
3454
#else
3455
// Android, Mac OS X and Cygwin don't define wcscasecmp.
3456
// Other unknown OSes may not define it either.
3457
wint_t left, right;
3458
do {
3459
left = towlower(*lhs++);
3460
right = towlower(*rhs++);
3461
} while (left && left == right);
3462
return left == right;
3463
#endif // OS selector
3464
}
3465
3466
// Returns true iff str ends with the given suffix, ignoring case.
3467
// Any string is considered to end with an empty suffix.
3468
bool String::EndsWithCaseInsensitive(
3469
const std::string& str, const std::string& suffix) {
3470
const size_t str_len = str.length();
3471
const size_t suffix_len = suffix.length();
3472
return (str_len >= suffix_len) &&
3473
CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3474
suffix.c_str());
3475
}
3476
3477
// Formats an int value as "%02d".
3478
std::string String::FormatIntWidth2(int value) {
3479
std::stringstream ss;
3480
ss << std::setfill('0') << std::setw(2) << value;
3481
return ss.str();
3482
}
3483
3484
// Formats an int value as "%X".
3485
std::string String::FormatHexInt(int value) {
3486
std::stringstream ss;
3487
ss << std::hex << std::uppercase << value;
3488
return ss.str();
3489
}
3490
3491
// Formats a byte as "%02X".
3492
std::string String::FormatByte(unsigned char value) {
3493
std::stringstream ss;
3494
ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3495
<< static_cast<unsigned int>(value);
3496
return ss.str();
3497
}
3498
3499
// Converts the buffer in a stringstream to an std::string, converting NUL
3500
// bytes to "\\0" along the way.
3501
std::string StringStreamToString(::std::stringstream* ss) {
3502
const ::std::string& str = ss->str();
3503
const char* const start = str.c_str();
3504
const char* const end = start + str.length();
3505
3506
std::string result;
3507
result.reserve(2 * (end - start));
3508
for (const char* ch = start; ch != end; ++ch) {
3509
if (*ch == '\0') {
3510
result += "\\0"; // Replaces NUL with "\\0";
3511
} else {
3512
result += *ch;
3513
}
3514
}
3515
3516
return result;
3517
}
3518
3519
// Appends the user-supplied message to the Google-Test-generated message.
3520
std::string AppendUserMessage(const std::string& gtest_msg,
3521
const Message& user_msg) {
3522
// Appends the user message if it's non-empty.
3523
const std::string user_msg_string = user_msg.GetString();
3524
if (user_msg_string.empty()) {
3525
return gtest_msg;
3526
}
3527
3528
return gtest_msg + "\n" + user_msg_string;
3529
}
3530
3531
} // namespace internal
3532
3533
// class TestResult
3534
3535
// Creates an empty TestResult.
3536
TestResult::TestResult()
3537
: death_test_count_(0),
3538
elapsed_time_(0) {
3539
}
3540
3541
// D'tor.
3542
TestResult::~TestResult() {
3543
}
3544
3545
// Returns the i-th test part result among all the results. i can
3546
// range from 0 to total_part_count() - 1. If i is not in that range,
3547
// aborts the program.
3548
const TestPartResult& TestResult::GetTestPartResult(int i) const {
3549
if (i < 0 || i >= total_part_count())
3550
internal::posix::Abort();
3551
return test_part_results_.at(i);
3552
}
3553
3554
// Returns the i-th test property. i can range from 0 to
3555
// test_property_count() - 1. If i is not in that range, aborts the
3556
// program.
3557
const TestProperty& TestResult::GetTestProperty(int i) const {
3558
if (i < 0 || i >= test_property_count())
3559
internal::posix::Abort();
3560
return test_properties_.at(i);
3561
}
3562
3563
// Clears the test part results.
3564
void TestResult::ClearTestPartResults() {
3565
test_part_results_.clear();
3566
}
3567
3568
// Adds a test part result to the list.
3569
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3570
test_part_results_.push_back(test_part_result);
3571
}
3572
3573
// Adds a test property to the list. If a property with the same key as the
3574
// supplied property is already represented, the value of this test_property
3575
// replaces the old value for that key.
3576
void TestResult::RecordProperty(const std::string& xml_element,
3577
const TestProperty& test_property) {
3578
if (!ValidateTestProperty(xml_element, test_property)) {
3579
return;
3580
}
3581
internal::MutexLock lock(&test_properites_mutex_);
3582
const std::vector<TestProperty>::iterator property_with_matching_key =
3583
std::find_if(test_properties_.begin(), test_properties_.end(),
3584
internal::TestPropertyKeyIs(test_property.key()));
3585
if (property_with_matching_key == test_properties_.end()) {
3586
test_properties_.push_back(test_property);
3587
return;
3588
}
3589
property_with_matching_key->SetValue(test_property.value());
3590
}
3591
3592
// The list of reserved attributes used in the <testsuites> element of XML
3593
// output.
3594
static const char* const kReservedTestSuitesAttributes[] = {
3595
"disabled",
3596
"errors",
3597
"failures",
3598
"name",
3599
"random_seed",
3600
"tests",
3601
"time",
3602
"timestamp"
3603
};
3604
3605
// The list of reserved attributes used in the <testsuite> element of XML
3606
// output.
3607
static const char* const kReservedTestSuiteAttributes[] = {
3608
"disabled",
3609
"errors",
3610
"failures",
3611
"name",
3612
"tests",
3613
"time"
3614
};
3615
3616
// The list of reserved attributes used in the <testcase> element of XML output.
3617
static const char* const kReservedTestCaseAttributes[] = {
3618
"classname", "name", "status", "time",
3619
"type_param", "value_param", "file", "line"};
3620
3621
template <int kSize>
3622
std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3623
return std::vector<std::string>(array, array + kSize);
3624
}
3625
3626
static std::vector<std::string> GetReservedAttributesForElement(
3627
const std::string& xml_element) {
3628
if (xml_element == "testsuites") {
3629
return ArrayAsVector(kReservedTestSuitesAttributes);
3630
} else if (xml_element == "testsuite") {
3631
return ArrayAsVector(kReservedTestSuiteAttributes);
3632
} else if (xml_element == "testcase") {
3633
return ArrayAsVector(kReservedTestCaseAttributes);
3634
} else {
3635
GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3636
}
3637
// This code is unreachable but some compilers may not realizes that.
3638
return std::vector<std::string>();
3639
}
3640
3641
static std::string FormatWordList(const std::vector<std::string>& words) {
3642
Message word_list;
3643
for (size_t i = 0; i < words.size(); ++i) {
3644
if (i > 0 && words.size() > 2) {
3645
word_list << ", ";
3646
}
3647
if (i == words.size() - 1) {
3648
word_list << "and ";
3649
}
3650
word_list << "'" << words[i] << "'";
3651
}
3652
return word_list.GetString();
3653
}
3654
3655
static bool ValidateTestPropertyName(
3656
const std::string& property_name,
3657
const std::vector<std::string>& reserved_names) {
3658
if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3659
reserved_names.end()) {
3660
ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3661
<< " (" << FormatWordList(reserved_names)
3662
<< " are reserved by " << GTEST_NAME_ << ")";
3663
return false;
3664
}
3665
return true;
3666
}
3667
3668
// Adds a failure if the key is a reserved attribute of the element named
3669
// xml_element. Returns true if the property is valid.
3670
bool TestResult::ValidateTestProperty(const std::string& xml_element,
3671
const TestProperty& test_property) {
3672
return ValidateTestPropertyName(test_property.key(),
3673
GetReservedAttributesForElement(xml_element));
3674
}
3675
3676
// Clears the object.
3677
void TestResult::Clear() {
3678
test_part_results_.clear();
3679
test_properties_.clear();
3680
death_test_count_ = 0;
3681
elapsed_time_ = 0;
3682
}
3683
3684
// Returns true iff the test failed.
3685
bool TestResult::Failed() const {
3686
for (int i = 0; i < total_part_count(); ++i) {
3687
if (GetTestPartResult(i).failed())
3688
return true;
3689
}
3690
return false;
3691
}
3692
3693
// Returns true iff the test part fatally failed.
3694
static bool TestPartFatallyFailed(const TestPartResult& result) {
3695
return result.fatally_failed();
3696
}
3697
3698
// Returns true iff the test fatally failed.
3699
bool TestResult::HasFatalFailure() const {
3700
return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3701
}
3702
3703
// Returns true iff the test part non-fatally failed.
3704
static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3705
return result.nonfatally_failed();
3706
}
3707
3708
// Returns true iff the test has a non-fatal failure.
3709
bool TestResult::HasNonfatalFailure() const {
3710
return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3711
}
3712
3713
// Gets the number of all test parts. This is the sum of the number
3714
// of successful test parts and the number of failed test parts.
3715
int TestResult::total_part_count() const {
3716
return static_cast<int>(test_part_results_.size());
3717
}
3718
3719
// Returns the number of the test properties.
3720
int TestResult::test_property_count() const {
3721
return static_cast<int>(test_properties_.size());
3722
}
3723
3724
// class Test
3725
3726
// Creates a Test object.
3727
3728
// The c'tor saves the states of all flags.
3729
Test::Test()
3730
: gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
3731
}
3732
3733
// The d'tor restores the states of all flags. The actual work is
3734
// done by the d'tor of the gtest_flag_saver_ field, and thus not
3735
// visible here.
3736
Test::~Test() {
3737
}
3738
3739
// Sets up the test fixture.
3740
//
3741
// A sub-class may override this.
3742
void Test::SetUp() {
3743
}
3744
3745
// Tears down the test fixture.
3746
//
3747
// A sub-class may override this.
3748
void Test::TearDown() {
3749
}
3750
3751
// Allows user supplied key value pairs to be recorded for later output.
3752
void Test::RecordProperty(const std::string& key, const std::string& value) {
3753
UnitTest::GetInstance()->RecordProperty(key, value);
3754
}
3755
3756
// Allows user supplied key value pairs to be recorded for later output.
3757
void Test::RecordProperty(const std::string& key, int value) {
3758
Message value_message;
3759
value_message << value;
3760
RecordProperty(key, value_message.GetString().c_str());
3761
}
3762
3763
namespace internal {
3764
3765
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3766
const std::string& message) {
3767
// This function is a friend of UnitTest and as such has access to
3768
// AddTestPartResult.
3769
UnitTest::GetInstance()->AddTestPartResult(
3770
result_type,
3771
NULL, // No info about the source file where the exception occurred.
3772
-1, // We have no info on which line caused the exception.
3773
message,
3774
""); // No stack trace, either.
3775
}
3776
3777
} // namespace internal
3778
3779
// Google Test requires all tests in the same test case to use the same test
3780
// fixture class. This function checks if the current test has the
3781
// same fixture class as the first test in the current test case. If
3782
// yes, it returns true; otherwise it generates a Google Test failure and
3783
// returns false.
3784
bool Test::HasSameFixtureClass() {
3785
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3786
const TestCase* const test_case = impl->current_test_case();
3787
3788
// Info about the first test in the current test case.
3789
const TestInfo* const first_test_info = test_case->test_info_list()[0];
3790
const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3791
const char* const first_test_name = first_test_info->name();
3792
3793
// Info about the current test.
3794
const TestInfo* const this_test_info = impl->current_test_info();
3795
const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3796
const char* const this_test_name = this_test_info->name();
3797
3798
if (this_fixture_id != first_fixture_id) {
3799
// Is the first test defined using TEST?
3800
const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3801
// Is this test defined using TEST?
3802
const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3803
3804
if (first_is_TEST || this_is_TEST) {
3805
// Both TEST and TEST_F appear in same test case, which is incorrect.
3806
// Tell the user how to fix this.
3807
3808
// Gets the name of the TEST and the name of the TEST_F. Note
3809
// that first_is_TEST and this_is_TEST cannot both be true, as
3810
// the fixture IDs are different for the two tests.
3811
const char* const TEST_name =
3812
first_is_TEST ? first_test_name : this_test_name;
3813
const char* const TEST_F_name =
3814
first_is_TEST ? this_test_name : first_test_name;
3815
3816
ADD_FAILURE()
3817
<< "All tests in the same test case must use the same test fixture\n"
3818
<< "class, so mixing TEST_F and TEST in the same test case is\n"
3819
<< "illegal. In test case " << this_test_info->test_case_name()
3820
<< ",\n"
3821
<< "test " << TEST_F_name << " is defined using TEST_F but\n"
3822
<< "test " << TEST_name << " is defined using TEST. You probably\n"
3823
<< "want to change the TEST to TEST_F or move it to another test\n"
3824
<< "case.";
3825
} else {
3826
// Two fixture classes with the same name appear in two different
3827
// namespaces, which is not allowed. Tell the user how to fix this.
3828
ADD_FAILURE()
3829
<< "All tests in the same test case must use the same test fixture\n"
3830
<< "class. However, in test case "
3831
<< this_test_info->test_case_name() << ",\n"
3832
<< "you defined test " << first_test_name
3833
<< " and test " << this_test_name << "\n"
3834
<< "using two different test fixture classes. This can happen if\n"
3835
<< "the two classes are from different namespaces or translation\n"
3836
<< "units and have the same name. You should probably rename one\n"
3837
<< "of the classes to put the tests into different test cases.";
3838
}
3839
return false;
3840
}
3841
3842
return true;
3843
}
3844
3845
#if GTEST_HAS_SEH
3846
3847
// Adds an "exception thrown" fatal failure to the current test. This
3848
// function returns its result via an output parameter pointer because VC++
3849
// prohibits creation of objects with destructors on stack in functions
3850
// using __try (see error C2712).
3851
static std::string* FormatSehExceptionMessage(DWORD exception_code,
3852
const char* location) {
3853
Message message;
3854
message << "SEH exception with code 0x" << std::setbase(16) <<
3855
exception_code << std::setbase(10) << " thrown in " << location << ".";
3856
3857
return new std::string(message.GetString());
3858
}
3859
3860
#endif // GTEST_HAS_SEH
3861
3862
namespace internal {
3863
3864
#if GTEST_HAS_EXCEPTIONS
3865
3866
// Adds an "exception thrown" fatal failure to the current test.
3867
static std::string FormatCxxExceptionMessage(const char* description,
3868
const char* location) {
3869
Message message;
3870
if (description != NULL) {
3871
message << "C++ exception with description \"" << description << "\"";
3872
} else {
3873
message << "Unknown C++ exception";
3874
}
3875
message << " thrown in " << location << ".";
3876
3877
return message.GetString();
3878
}
3879
3880
static std::string PrintTestPartResultToString(
3881
const TestPartResult& test_part_result);
3882
3883
GoogleTestFailureException::GoogleTestFailureException(
3884
const TestPartResult& failure)
3885
: ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3886
3887
#endif // GTEST_HAS_EXCEPTIONS
3888
3889
// We put these helper functions in the internal namespace as IBM's xlC
3890
// compiler rejects the code if they were declared static.
3891
3892
// Runs the given method and handles SEH exceptions it throws, when
3893
// SEH is supported; returns the 0-value for type Result in case of an
3894
// SEH exception. (Microsoft compilers cannot handle SEH and C++
3895
// exceptions in the same function. Therefore, we provide a separate
3896
// wrapper function for handling SEH exceptions.)
3897
template <class T, typename Result>
3898
Result HandleSehExceptionsInMethodIfSupported(
3899
T* object, Result (T::*method)(), const char* location) {
3900
#if GTEST_HAS_SEH
3901
__try {
3902
return (object->*method)();
3903
} __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3904
GetExceptionCode())) {
3905
// We create the exception message on the heap because VC++ prohibits
3906
// creation of objects with destructors on stack in functions using __try
3907
// (see error C2712).
3908
std::string* exception_message = FormatSehExceptionMessage(
3909
GetExceptionCode(), location);
3910
internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3911
*exception_message);
3912
delete exception_message;
3913
return static_cast<Result>(0);
3914
}
3915
#else
3916
CV_UNUSED(location);
3917
return (object->*method)();
3918
#endif // GTEST_HAS_SEH
3919
}
3920
3921
// Runs the given method and catches and reports C++ and/or SEH-style
3922
// exceptions, if they are supported; returns the 0-value for type
3923
// Result in case of an SEH exception.
3924
template <class T, typename Result>
3925
Result HandleExceptionsInMethodIfSupported(
3926
T* object, Result (T::*method)(), const char* location) {
3927
// NOTE: The user code can affect the way in which Google Test handles
3928
// exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3929
// RUN_ALL_TESTS() starts. It is technically possible to check the flag
3930
// after the exception is caught and either report or re-throw the
3931
// exception based on the flag's value:
3932
//
3933
// try {
3934
// // Perform the test method.
3935
// } catch (...) {
3936
// if (GTEST_FLAG(catch_exceptions))
3937
// // Report the exception as failure.
3938
// else
3939
// throw; // Re-throws the original exception.
3940
// }
3941
//
3942
// However, the purpose of this flag is to allow the program to drop into
3943
// the debugger when the exception is thrown. On most platforms, once the
3944
// control enters the catch block, the exception origin information is
3945
// lost and the debugger will stop the program at the point of the
3946
// re-throw in this function -- instead of at the point of the original
3947
// throw statement in the code under test. For this reason, we perform
3948
// the check early, sacrificing the ability to affect Google Test's
3949
// exception handling in the method where the exception is thrown.
3950
if (internal::GetUnitTestImpl()->catch_exceptions()) {
3951
#if GTEST_HAS_EXCEPTIONS
3952
try {
3953
return HandleSehExceptionsInMethodIfSupported(object, method, location);
3954
} catch (const AssertionException&) { // NOLINT
3955
// This failure was reported already.
3956
} catch (const internal::GoogleTestFailureException&) { // NOLINT
3957
// This exception type can only be thrown by a failed Google
3958
// Test assertion with the intention of letting another testing
3959
// framework catch it. Therefore we just re-throw it.
3960
throw;
3961
} catch (const std::exception& e) { // NOLINT
3962
internal::ReportFailureInUnknownLocation(
3963
TestPartResult::kFatalFailure,
3964
FormatCxxExceptionMessage(e.what(), location));
3965
} catch (...) { // NOLINT
3966
internal::ReportFailureInUnknownLocation(
3967
TestPartResult::kFatalFailure,
3968
FormatCxxExceptionMessage(NULL, location));
3969
}
3970
return static_cast<Result>(0);
3971
#else
3972
return HandleSehExceptionsInMethodIfSupported(object, method, location);
3973
#endif // GTEST_HAS_EXCEPTIONS
3974
} else {
3975
return (object->*method)();
3976
}
3977
}
3978
3979
} // namespace internal
3980
3981
// Runs the test and updates the test result.
3982
void Test::Run() {
3983
if (!HasSameFixtureClass()) return;
3984
3985
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3986
impl->os_stack_trace_getter()->UponLeavingGTest();
3987
internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3988
// We will run the test only if SetUp() was successful.
3989
if (!HasFatalFailure()) {
3990
impl->os_stack_trace_getter()->UponLeavingGTest();
3991
internal::HandleExceptionsInMethodIfSupported(
3992
this, &Test::TestBody, "the test body");
3993
}
3994
3995
// However, we want to clean up as much as possible. Hence we will
3996
// always call TearDown(), even if SetUp() or the test body has
3997
// failed.
3998
impl->os_stack_trace_getter()->UponLeavingGTest();
3999
internal::HandleExceptionsInMethodIfSupported(
4000
this, &Test::TearDown, "TearDown()");
4001
}
4002
4003
// Returns true iff the current test has a fatal failure.
4004
bool Test::HasFatalFailure() {
4005
return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
4006
}
4007
4008
// Returns true iff the current test has a non-fatal failure.
4009
bool Test::HasNonfatalFailure() {
4010
return internal::GetUnitTestImpl()->current_test_result()->
4011
HasNonfatalFailure();
4012
}
4013
4014
// class TestInfo
4015
4016
// Constructs a TestInfo object. It assumes ownership of the test factory
4017
// object.
4018
TestInfo::TestInfo(const std::string& a_test_case_name,
4019
const std::string& a_name,
4020
const char* a_type_param,
4021
const char* a_value_param,
4022
internal::CodeLocation a_code_location,
4023
internal::TypeId fixture_class_id,
4024
internal::TestFactoryBase* factory)
4025
: test_case_name_(a_test_case_name),
4026
name_(a_name),
4027
type_param_(a_type_param ? new std::string(a_type_param) : NULL),
4028
value_param_(a_value_param ? new std::string(a_value_param) : NULL),
4029
location_(a_code_location),
4030
fixture_class_id_(fixture_class_id),
4031
should_run_(false),
4032
is_disabled_(false),
4033
matches_filter_(false),
4034
factory_(factory),
4035
result_() {}
4036
4037
// Destructs a TestInfo object.
4038
TestInfo::~TestInfo() { delete factory_; }
4039
4040
namespace internal {
4041
4042
// Creates a new TestInfo object and registers it with Google Test;
4043
// returns the created object.
4044
//
4045
// Arguments:
4046
//
4047
// test_case_name: name of the test case
4048
// name: name of the test
4049
// type_param: the name of the test's type parameter, or NULL if
4050
// this is not a typed or a type-parameterized test.
4051
// value_param: text representation of the test's value parameter,
4052
// or NULL if this is not a value-parameterized test.
4053
// code_location: code location where the test is defined
4054
// fixture_class_id: ID of the test fixture class
4055
// set_up_tc: pointer to the function that sets up the test case
4056
// tear_down_tc: pointer to the function that tears down the test case
4057
// factory: pointer to the factory that creates a test object.
4058
// The newly created TestInfo instance will assume
4059
// ownership of the factory object.
4060
TestInfo* MakeAndRegisterTestInfo(
4061
const char* test_case_name,
4062
const char* name,
4063
const char* type_param,
4064
const char* value_param,
4065
CodeLocation code_location,
4066
TypeId fixture_class_id,
4067
SetUpTestCaseFunc set_up_tc,
4068
TearDownTestCaseFunc tear_down_tc,
4069
TestFactoryBase* factory) {
4070
TestInfo* const test_info =
4071
new TestInfo(test_case_name, name, type_param, value_param,
4072
code_location, fixture_class_id, factory);
4073
GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
4074
return test_info;
4075
}
4076
4077
void ReportInvalidTestCaseType(const char* test_case_name,
4078
CodeLocation code_location) {
4079
Message errors;
4080
errors
4081
<< "Attempted redefinition of test case " << test_case_name << ".\n"
4082
<< "All tests in the same test case must use the same test fixture\n"
4083
<< "class. However, in test case " << test_case_name << ", you tried\n"
4084
<< "to define a test using a fixture class different from the one\n"
4085
<< "used earlier. This can happen if the two fixture classes are\n"
4086
<< "from different namespaces and have the same name. You should\n"
4087
<< "probably rename one of the classes to put the tests into different\n"
4088
<< "test cases.";
4089
4090
GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
4091
code_location.line)
4092
<< " " << errors.GetString();
4093
}
4094
} // namespace internal
4095
4096
namespace {
4097
4098
// A predicate that checks the test name of a TestInfo against a known
4099
// value.
4100
//
4101
// This is used for implementation of the TestCase class only. We put
4102
// it in the anonymous namespace to prevent polluting the outer
4103
// namespace.
4104
//
4105
// TestNameIs is copyable.
4106
class TestNameIs {
4107
public:
4108
// Constructor.
4109
//
4110
// TestNameIs has NO default constructor.
4111
explicit TestNameIs(const char* name)
4112
: name_(name) {}
4113
4114
// Returns true iff the test name of test_info matches name_.
4115
bool operator()(const TestInfo * test_info) const {
4116
return test_info && test_info->name() == name_;
4117
}
4118
4119
private:
4120
std::string name_;
4121
};
4122
4123
} // namespace
4124
4125
namespace internal {
4126
4127
// This method expands all parameterized tests registered with macros TEST_P
4128
// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
4129
// This will be done just once during the program runtime.
4130
void UnitTestImpl::RegisterParameterizedTests() {
4131
if (!parameterized_tests_registered_) {
4132
parameterized_test_registry_.RegisterTests();
4133
parameterized_tests_registered_ = true;
4134
}
4135
}
4136
4137
} // namespace internal
4138
4139
// Creates the test object, runs it, records its result, and then
4140
// deletes it.
4141
void TestInfo::Run() {
4142
if (!should_run_) return;
4143
4144
// Tells UnitTest where to store test result.
4145
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4146
impl->set_current_test_info(this);
4147
4148
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4149
4150
// Notifies the unit test event listeners that a test is about to start.
4151
repeater->OnTestStart(*this);
4152
4153
const TimeInMillis start = internal::GetTimeInMillis();
4154
4155
impl->os_stack_trace_getter()->UponLeavingGTest();
4156
4157
// Creates the test object.
4158
Test* const test = internal::HandleExceptionsInMethodIfSupported(
4159
factory_, &internal::TestFactoryBase::CreateTest,
4160
"the test fixture's constructor");
4161
4162
// Runs the test if the constructor didn't generate a fatal failure.
4163
// Note that the object will not be null
4164
if (!Test::HasFatalFailure()) {
4165
// This doesn't throw as all user code that can throw are wrapped into
4166
// exception handling code.
4167
test->Run();
4168
}
4169
4170
// Deletes the test object.
4171
impl->os_stack_trace_getter()->UponLeavingGTest();
4172
internal::HandleExceptionsInMethodIfSupported(
4173
test, &Test::DeleteSelf_, "the test fixture's destructor");
4174
4175
result_.set_elapsed_time(internal::GetTimeInMillis() - start);
4176
4177
// Notifies the unit test event listener that a test has just finished.
4178
repeater->OnTestEnd(*this);
4179
4180
// Tells UnitTest to stop associating assertion results to this
4181
// test.
4182
impl->set_current_test_info(NULL);
4183
}
4184
4185
// class TestCase
4186
4187
// Gets the number of successful tests in this test case.
4188
int TestCase::successful_test_count() const {
4189
return CountIf(test_info_list_, TestPassed);
4190
}
4191
4192
// Gets the number of failed tests in this test case.
4193
int TestCase::failed_test_count() const {
4194
return CountIf(test_info_list_, TestFailed);
4195
}
4196
4197
// Gets the number of disabled tests that will be reported in the XML report.
4198
int TestCase::reportable_disabled_test_count() const {
4199
return CountIf(test_info_list_, TestReportableDisabled);
4200
}
4201
4202
// Gets the number of disabled tests in this test case.
4203
int TestCase::disabled_test_count() const {
4204
return CountIf(test_info_list_, TestDisabled);
4205
}
4206
4207
// Gets the number of tests to be printed in the XML report.
4208
int TestCase::reportable_test_count() const {
4209
return CountIf(test_info_list_, TestReportable);
4210
}
4211
4212
// Get the number of tests in this test case that should run.
4213
int TestCase::test_to_run_count() const {
4214
return CountIf(test_info_list_, ShouldRunTest);
4215
}
4216
4217
// Gets the number of all tests.
4218
int TestCase::total_test_count() const {
4219
return static_cast<int>(test_info_list_.size());
4220
}
4221
4222
// Creates a TestCase with the given name.
4223
//
4224
// Arguments:
4225
//
4226
// name: name of the test case
4227
// a_type_param: the name of the test case's type parameter, or NULL if
4228
// this is not a typed or a type-parameterized test case.
4229
// set_up_tc: pointer to the function that sets up the test case
4230
// tear_down_tc: pointer to the function that tears down the test case
4231
TestCase::TestCase(const char* a_name, const char* a_type_param,
4232
Test::SetUpTestCaseFunc set_up_tc,
4233
Test::TearDownTestCaseFunc tear_down_tc)
4234
: name_(a_name),
4235
type_param_(a_type_param ? new std::string(a_type_param) : NULL),
4236
set_up_tc_(set_up_tc),
4237
tear_down_tc_(tear_down_tc),
4238
should_run_(false),
4239
elapsed_time_(0) {
4240
}
4241
4242
// Destructor of TestCase.
4243
TestCase::~TestCase() {
4244
// Deletes every Test in the collection.
4245
ForEach(test_info_list_, internal::Delete<TestInfo>);
4246
}
4247
4248
// Returns the i-th test among all the tests. i can range from 0 to
4249
// total_test_count() - 1. If i is not in that range, returns NULL.
4250
const TestInfo* TestCase::GetTestInfo(int i) const {
4251
const int index = GetElementOr(test_indices_, i, -1);
4252
return index < 0 ? NULL : test_info_list_[index];
4253
}
4254
4255
// Returns the i-th test among all the tests. i can range from 0 to
4256
// total_test_count() - 1. If i is not in that range, returns NULL.
4257
TestInfo* TestCase::GetMutableTestInfo(int i) {
4258
const int index = GetElementOr(test_indices_, i, -1);
4259
return index < 0 ? NULL : test_info_list_[index];
4260
}
4261
4262
// Adds a test to this test case. Will delete the test upon
4263
// destruction of the TestCase object.
4264
void TestCase::AddTestInfo(TestInfo * test_info) {
4265
test_info_list_.push_back(test_info);
4266
test_indices_.push_back(static_cast<int>(test_indices_.size()));
4267
}
4268
4269
// Runs every test in this TestCase.
4270
void TestCase::Run() {
4271
if (!should_run_) return;
4272
4273
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4274
impl->set_current_test_case(this);
4275
4276
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4277
4278
repeater->OnTestCaseStart(*this);
4279
impl->os_stack_trace_getter()->UponLeavingGTest();
4280
internal::HandleExceptionsInMethodIfSupported(
4281
this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
4282
4283
const internal::TimeInMillis start = internal::GetTimeInMillis();
4284
for (int i = 0; i < total_test_count(); i++) {
4285
GetMutableTestInfo(i)->Run();
4286
}
4287
elapsed_time_ = internal::GetTimeInMillis() - start;
4288
4289
impl->os_stack_trace_getter()->UponLeavingGTest();
4290
internal::HandleExceptionsInMethodIfSupported(
4291
this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
4292
4293
repeater->OnTestCaseEnd(*this);
4294
impl->set_current_test_case(NULL);
4295
}
4296
4297
// Clears the results of all tests in this test case.
4298
void TestCase::ClearResult() {
4299
ad_hoc_test_result_.Clear();
4300
ForEach(test_info_list_, TestInfo::ClearTestResult);
4301
}
4302
4303
// Shuffles the tests in this test case.
4304
void TestCase::ShuffleTests(internal::Random* random) {
4305
Shuffle(random, &test_indices_);
4306
}
4307
4308
// Restores the test order to before the first shuffle.
4309
void TestCase::UnshuffleTests() {
4310
for (size_t i = 0; i < test_indices_.size(); i++) {
4311
test_indices_[i] = static_cast<int>(i);
4312
}
4313
}
4314
4315
// Formats a countable noun. Depending on its quantity, either the
4316
// singular form or the plural form is used. e.g.
4317
//
4318
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
4319
// FormatCountableNoun(5, "book", "books") returns "5 books".
4320
static std::string FormatCountableNoun(int count,
4321
const char * singular_form,
4322
const char * plural_form) {
4323
return internal::StreamableToString(count) + " " +
4324
(count == 1 ? singular_form : plural_form);
4325
}
4326
4327
// Formats the count of tests.
4328
static std::string FormatTestCount(int test_count) {
4329
return FormatCountableNoun(test_count, "test", "tests");
4330
}
4331
4332
// Formats the count of test cases.
4333
static std::string FormatTestCaseCount(int test_case_count) {
4334
return FormatCountableNoun(test_case_count, "test case", "test cases");
4335
}
4336
4337
// Converts a TestPartResult::Type enum to human-friendly string
4338
// representation. Both kNonFatalFailure and kFatalFailure are translated
4339
// to "Failure", as the user usually doesn't care about the difference
4340
// between the two when viewing the test result.
4341
static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4342
switch (type) {
4343
case TestPartResult::kSuccess:
4344
return "Success";
4345
4346
case TestPartResult::kNonFatalFailure:
4347
case TestPartResult::kFatalFailure:
4348
#ifdef _MSC_VER
4349
return "error: ";
4350
#else
4351
return "Failure\n";
4352
#endif
4353
default:
4354
return "Unknown result type";
4355
}
4356
}
4357
4358
namespace internal {
4359
4360
// Prints a TestPartResult to an std::string.
4361
static std::string PrintTestPartResultToString(
4362
const TestPartResult& test_part_result) {
4363
return (Message()
4364
<< internal::FormatFileLocation(test_part_result.file_name(),
4365
test_part_result.line_number())
4366
<< " " << TestPartResultTypeToString(test_part_result.type())
4367
<< test_part_result.message()).GetString();
4368
}
4369
4370
// Prints a TestPartResult.
4371
static void PrintTestPartResult(const TestPartResult& test_part_result) {
4372
const std::string& result =
4373
PrintTestPartResultToString(test_part_result);
4374
printf("%s\n", result.c_str());
4375
fflush(stdout);
4376
// If the test program runs in Visual Studio or a debugger, the
4377
// following statements add the test part result message to the Output
4378
// window such that the user can double-click on it to jump to the
4379
// corresponding source code location; otherwise they do nothing.
4380
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4381
// We don't call OutputDebugString*() on Windows Mobile, as printing
4382
// to stdout is done by OutputDebugString() there already - we don't
4383
// want the same message printed twice.
4384
::OutputDebugStringA(result.c_str());
4385
::OutputDebugStringA("\n");
4386
#endif
4387
}
4388
4389
// class PrettyUnitTestResultPrinter
4390
4391
enum GTestColor {
4392
COLOR_DEFAULT,
4393
COLOR_RED,
4394
COLOR_GREEN,
4395
COLOR_YELLOW
4396
};
4397
4398
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4399
!GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4400
4401
// Returns the character attribute for the given color.
4402
static WORD GetColorAttribute(GTestColor color) {
4403
switch (color) {
4404
case COLOR_RED: return FOREGROUND_RED;
4405
case COLOR_GREEN: return FOREGROUND_GREEN;
4406
case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4407
default: return 0;
4408
}
4409
}
4410
4411
static int GetBitOffset(WORD color_mask) {
4412
if (color_mask == 0) return 0;
4413
4414
int bitOffset = 0;
4415
while ((color_mask & 1) == 0) {
4416
color_mask >>= 1;
4417
++bitOffset;
4418
}
4419
return bitOffset;
4420
}
4421
4422
static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
4423
// Let's reuse the BG
4424
static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
4425
BACKGROUND_RED | BACKGROUND_INTENSITY;
4426
static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
4427
FOREGROUND_RED | FOREGROUND_INTENSITY;
4428
const WORD existing_bg = old_color_attrs & background_mask;
4429
4430
WORD new_color =
4431
GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
4432
static const int bg_bitOffset = GetBitOffset(background_mask);
4433
static const int fg_bitOffset = GetBitOffset(foreground_mask);
4434
4435
if (((new_color & background_mask) >> bg_bitOffset) ==
4436
((new_color & foreground_mask) >> fg_bitOffset)) {
4437
new_color ^= FOREGROUND_INTENSITY; // invert intensity
4438
}
4439
return new_color;
4440
}
4441
4442
#else
4443
4444
// Returns the ANSI color code for the given color. COLOR_DEFAULT is
4445
// an invalid input.
4446
static const char* GetAnsiColorCode(GTestColor color) {
4447
switch (color) {
4448
case COLOR_RED: return "1";
4449
case COLOR_GREEN: return "2";
4450
case COLOR_YELLOW: return "3";
4451
default: return NULL;
4452
};
4453
}
4454
4455
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4456
4457
// Returns true iff Google Test should use colors in the output.
4458
bool ShouldUseColor(bool stdout_is_tty) {
4459
const char* const gtest_color = GTEST_FLAG(color).c_str();
4460
4461
if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4462
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
4463
// On Windows the TERM variable is usually not set, but the
4464
// console there does support colors.
4465
return stdout_is_tty;
4466
#else
4467
// On non-Windows platforms, we rely on the TERM variable.
4468
const char* const term = posix::GetEnv("TERM");
4469
const bool term_supports_color =
4470
String::CStringEquals(term, "xterm") ||
4471
String::CStringEquals(term, "xterm-color") ||
4472
String::CStringEquals(term, "xterm-256color") ||
4473
String::CStringEquals(term, "screen") ||
4474
String::CStringEquals(term, "screen-256color") ||
4475
String::CStringEquals(term, "tmux") ||
4476
String::CStringEquals(term, "tmux-256color") ||
4477
String::CStringEquals(term, "rxvt-unicode") ||
4478
String::CStringEquals(term, "rxvt-unicode-256color") ||
4479
String::CStringEquals(term, "linux") ||
4480
String::CStringEquals(term, "cygwin");
4481
return stdout_is_tty && term_supports_color;
4482
#endif // GTEST_OS_WINDOWS
4483
}
4484
4485
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4486
String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4487
String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4488
String::CStringEquals(gtest_color, "1");
4489
// We take "yes", "true", "t", and "1" as meaning "yes". If the
4490
// value is neither one of these nor "auto", we treat it as "no" to
4491
// be conservative.
4492
}
4493
4494
// Helpers for printing colored strings to stdout. Note that on Windows, we
4495
// cannot simply emit special characters and have the terminal change colors.
4496
// This routine must actually emit the characters rather than return a string
4497
// that would be colored when printed, as can be done on Linux.
4498
static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4499
va_list args;
4500
va_start(args, fmt);
4501
4502
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
4503
GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
4504
const bool use_color = AlwaysFalse();
4505
#else
4506
static const bool in_color_mode =
4507
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4508
const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4509
#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4510
// The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4511
4512
if (!use_color) {
4513
vprintf(fmt, args);
4514
va_end(args);
4515
return;
4516
}
4517
4518
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4519
!GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4520
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4521
4522
// Gets the current text color.
4523
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4524
GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4525
const WORD old_color_attrs = buffer_info.wAttributes;
4526
const WORD new_color = GetNewColor(color, old_color_attrs);
4527
4528
// We need to flush the stream buffers into the console before each
4529
// SetConsoleTextAttribute call lest it affect the text that is already
4530
// printed but has not yet reached the console.
4531
fflush(stdout);
4532
SetConsoleTextAttribute(stdout_handle, new_color);
4533
4534
vprintf(fmt, args);
4535
4536
fflush(stdout);
4537
// Restores the text color.
4538
SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4539
#else
4540
printf("\033[0;3%sm", GetAnsiColorCode(color));
4541
vprintf(fmt, args);
4542
printf("\033[m"); // Resets the terminal to default.
4543
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4544
va_end(args);
4545
}
4546
4547
// Text printed in Google Test's text output and --gtest_list_tests
4548
// output to label the type parameter and value parameter for a test.
4549
static const char kTypeParamLabel[] = "TypeParam";
4550
static const char kValueParamLabel[] = "GetParam()";
4551
4552
static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4553
const char* const type_param = test_info.type_param();
4554
const char* const value_param = test_info.value_param();
4555
4556
if (type_param != NULL || value_param != NULL) {
4557
printf(", where ");
4558
if (type_param != NULL) {
4559
printf("%s = %s", kTypeParamLabel, type_param);
4560
if (value_param != NULL)
4561
printf(" and ");
4562
}
4563
if (value_param != NULL) {
4564
printf("%s = %s", kValueParamLabel, value_param);
4565
}
4566
}
4567
}
4568
4569
// This class implements the TestEventListener interface.
4570
//
4571
// Class PrettyUnitTestResultPrinter is copyable.
4572
class PrettyUnitTestResultPrinter : public TestEventListener {
4573
public:
4574
PrettyUnitTestResultPrinter() {}
4575
static void PrintTestName(const char * test_case, const char * test) {
4576
printf("%s.%s", test_case, test);
4577
}
4578
4579
// The following methods override what's in the TestEventListener class.
4580
virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4581
virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4582
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4583
virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4584
virtual void OnTestCaseStart(const TestCase& test_case);
4585
virtual void OnTestStart(const TestInfo& test_info);
4586
virtual void OnTestPartResult(const TestPartResult& result);
4587
virtual void OnTestEnd(const TestInfo& test_info);
4588
virtual void OnTestCaseEnd(const TestCase& test_case);
4589
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4590
virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4591
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4592
virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4593
4594
private:
4595
static void PrintFailedTests(const UnitTest& unit_test);
4596
};
4597
4598
// Fired before each iteration of tests starts.
4599
void PrettyUnitTestResultPrinter::OnTestIterationStart(
4600
const UnitTest& unit_test, int iteration) {
4601
if (GTEST_FLAG(repeat) != 1)
4602
printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4603
4604
const char* const filter = GTEST_FLAG(filter).c_str();
4605
4606
// Prints the filter if it's not *. This reminds the user that some
4607
// tests may be skipped.
4608
if (!String::CStringEquals(filter, kUniversalFilter)) {
4609
ColoredPrintf(COLOR_YELLOW,
4610
"Note: %s filter = %s\n", GTEST_NAME_, filter);
4611
}
4612
4613
const char* const param_filter = GTEST_FLAG(param_filter).c_str();
4614
4615
// Ditto.
4616
if (!String::CStringEquals(param_filter, kUniversalFilter)) {
4617
ColoredPrintf(COLOR_YELLOW,
4618
"Note: %s parameter filter = %s\n", GTEST_NAME_, param_filter);
4619
}
4620
4621
if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4622
const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4623
ColoredPrintf(COLOR_YELLOW,
4624
"Note: This is test shard %d of %s.\n",
4625
static_cast<int>(shard_index) + 1,
4626
internal::posix::GetEnv(kTestTotalShards));
4627
}
4628
4629
if (GTEST_FLAG(shuffle)) {
4630
ColoredPrintf(COLOR_YELLOW,
4631
"Note: Randomizing tests' orders with a seed of %d .\n",
4632
unit_test.random_seed());
4633
}
4634
4635
ColoredPrintf(COLOR_GREEN, "[==========] ");
4636
printf("Running %s from %s.\n",
4637
FormatTestCount(unit_test.test_to_run_count()).c_str(),
4638
FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4639
fflush(stdout);
4640
}
4641
4642
void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4643
const UnitTest& /*unit_test*/) {
4644
ColoredPrintf(COLOR_GREEN, "[----------] ");
4645
printf("Global test environment set-up.\n");
4646
fflush(stdout);
4647
}
4648
4649
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4650
const std::string counts =
4651
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4652
ColoredPrintf(COLOR_GREEN, "[----------] ");
4653
printf("%s from %s", counts.c_str(), test_case.name());
4654
if (test_case.type_param() == NULL) {
4655
printf("\n");
4656
} else {
4657
printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4658
}
4659
fflush(stdout);
4660
}
4661
4662
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4663
ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4664
PrintTestName(test_info.test_case_name(), test_info.name());
4665
PrintFullTestCommentIfPresent(test_info);
4666
printf("\n");
4667
fflush(stdout);
4668
}
4669
4670
// Called after an assertion failure.
4671
void PrettyUnitTestResultPrinter::OnTestPartResult(
4672
const TestPartResult& result) {
4673
// If the test part succeeded, we don't need to do anything.
4674
if (result.type() == TestPartResult::kSuccess)
4675
return;
4676
4677
// Print failure message from the assertion (e.g. expected this and got that).
4678
PrintTestPartResult(result);
4679
fflush(stdout);
4680
}
4681
4682
void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4683
if (test_info.result()->Passed()) {
4684
ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4685
} else {
4686
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4687
}
4688
PrintTestName(test_info.test_case_name(), test_info.name());
4689
if (test_info.result()->Failed())
4690
PrintFullTestCommentIfPresent(test_info);
4691
4692
if (GTEST_FLAG(print_time)) {
4693
printf(" (%s ms)\n", internal::StreamableToString(
4694
test_info.result()->elapsed_time()).c_str());
4695
} else {
4696
printf("\n");
4697
}
4698
fflush(stdout);
4699
}
4700
4701
void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4702
if (!GTEST_FLAG(print_time)) return;
4703
4704
const std::string counts =
4705
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4706
ColoredPrintf(COLOR_GREEN, "[----------] ");
4707
printf("%s from %s (%s ms total)\n\n",
4708
counts.c_str(), test_case.name(),
4709
internal::StreamableToString(test_case.elapsed_time()).c_str());
4710
fflush(stdout);
4711
}
4712
4713
void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4714
const UnitTest& /*unit_test*/) {
4715
ColoredPrintf(COLOR_GREEN, "[----------] ");
4716
printf("Global test environment tear-down\n");
4717
fflush(stdout);
4718
}
4719
4720
// Internal helper for printing the list of failed tests.
4721
void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4722
const int failed_test_count = unit_test.failed_test_count();
4723
if (failed_test_count == 0) {
4724
return;
4725
}
4726
4727
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4728
const TestCase& test_case = *unit_test.GetTestCase(i);
4729
if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4730
continue;
4731
}
4732
for (int j = 0; j < test_case.total_test_count(); ++j) {
4733
const TestInfo& test_info = *test_case.GetTestInfo(j);
4734
if (!test_info.should_run() || test_info.result()->Passed()) {
4735
continue;
4736
}
4737
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4738
printf("%s.%s", test_case.name(), test_info.name());
4739
PrintFullTestCommentIfPresent(test_info);
4740
printf("\n");
4741
}
4742
}
4743
}
4744
4745
void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4746
int /*iteration*/) {
4747
ColoredPrintf(COLOR_GREEN, "[==========] ");
4748
printf("%s from %s ran.",
4749
FormatTestCount(unit_test.test_to_run_count()).c_str(),
4750
FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4751
if (GTEST_FLAG(print_time)) {
4752
printf(" (%s ms total)",
4753
internal::StreamableToString(unit_test.elapsed_time()).c_str());
4754
}
4755
printf("\n");
4756
ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4757
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4758
4759
int num_failures = unit_test.failed_test_count();
4760
if (!unit_test.Passed()) {
4761
const int failed_test_count = unit_test.failed_test_count();
4762
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4763
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4764
PrintFailedTests(unit_test);
4765
printf("\n%2d FAILED %s\n", num_failures,
4766
num_failures == 1 ? "TEST" : "TESTS");
4767
}
4768
4769
int num_disabled = unit_test.reportable_disabled_test_count();
4770
if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4771
if (!num_failures) {
4772
printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4773
}
4774
ColoredPrintf(COLOR_YELLOW,
4775
" YOU HAVE %d DISABLED %s\n\n",
4776
num_disabled,
4777
num_disabled == 1 ? "TEST" : "TESTS");
4778
}
4779
// Ensure that Google Test output is printed before, e.g., heapchecker output.
4780
fflush(stdout);
4781
}
4782
4783
// End PrettyUnitTestResultPrinter
4784
4785
// class TestEventRepeater
4786
//
4787
// This class forwards events to other event listeners.
4788
class TestEventRepeater : public TestEventListener {
4789
public:
4790
TestEventRepeater() : forwarding_enabled_(true) {}
4791
virtual ~TestEventRepeater();
4792
void Append(TestEventListener *listener);
4793
TestEventListener* Release(TestEventListener* listener);
4794
4795
// Controls whether events will be forwarded to listeners_. Set to false
4796
// in death test child processes.
4797
bool forwarding_enabled() const { return forwarding_enabled_; }
4798
void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4799
4800
virtual void OnTestProgramStart(const UnitTest& unit_test);
4801
virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4802
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4803
virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4804
virtual void OnTestCaseStart(const TestCase& test_case);
4805
virtual void OnTestStart(const TestInfo& test_info);
4806
virtual void OnTestPartResult(const TestPartResult& result);
4807
virtual void OnTestEnd(const TestInfo& test_info);
4808
virtual void OnTestCaseEnd(const TestCase& test_case);
4809
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4810
virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4811
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4812
virtual void OnTestProgramEnd(const UnitTest& unit_test);
4813
4814
private:
4815
// Controls whether events will be forwarded to listeners_. Set to false
4816
// in death test child processes.
4817
bool forwarding_enabled_;
4818
// The list of listeners that receive events.
4819
std::vector<TestEventListener*> listeners_;
4820
4821
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4822
};
4823
4824
TestEventRepeater::~TestEventRepeater() {
4825
ForEach(listeners_, Delete<TestEventListener>);
4826
}
4827
4828
void TestEventRepeater::Append(TestEventListener *listener) {
4829
listeners_.push_back(listener);
4830
}
4831
4832
// FIXME: Factor the search functionality into Vector::Find.
4833
TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4834
for (size_t i = 0; i < listeners_.size(); ++i) {
4835
if (listeners_[i] == listener) {
4836
listeners_.erase(listeners_.begin() + i);
4837
return listener;
4838
}
4839
}
4840
4841
return NULL;
4842
}
4843
4844
// Since most methods are very similar, use macros to reduce boilerplate.
4845
// This defines a member that forwards the call to all listeners.
4846
#define GTEST_REPEATER_METHOD_(Name, Type) \
4847
void TestEventRepeater::Name(const Type& parameter) { \
4848
if (forwarding_enabled_) { \
4849
for (size_t i = 0; i < listeners_.size(); i++) { \
4850
listeners_[i]->Name(parameter); \
4851
} \
4852
} \
4853
}
4854
// This defines a member that forwards the call to all listeners in reverse
4855
// order.
4856
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4857
void TestEventRepeater::Name(const Type& parameter) { \
4858
if (forwarding_enabled_) { \
4859
for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4860
listeners_[i]->Name(parameter); \
4861
} \
4862
} \
4863
}
4864
4865
GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4866
GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4867
GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4868
GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4869
GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4870
GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4871
GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4872
GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4873
GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4874
GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4875
GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4876
4877
#undef GTEST_REPEATER_METHOD_
4878
#undef GTEST_REVERSE_REPEATER_METHOD_
4879
4880
void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4881
int iteration) {
4882
if (forwarding_enabled_) {
4883
for (size_t i = 0; i < listeners_.size(); i++) {
4884
listeners_[i]->OnTestIterationStart(unit_test, iteration);
4885
}
4886
}
4887
}
4888
4889
void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4890
int iteration) {
4891
if (forwarding_enabled_) {
4892
for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4893
listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4894
}
4895
}
4896
}
4897
4898
// End TestEventRepeater
4899
4900
// This class generates an XML output file.
4901
class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4902
public:
4903
explicit XmlUnitTestResultPrinter(const char* output_file);
4904
4905
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4906
void ListTestsMatchingFilter(const std::vector<TestCase*>& test_cases);
4907
4908
// Prints an XML summary of all unit tests.
4909
static void PrintXmlTestsList(std::ostream* stream,
4910
const std::vector<TestCase*>& test_cases);
4911
4912
private:
4913
// Is c a whitespace character that is normalized to a space character
4914
// when it appears in an XML attribute value?
4915
static bool IsNormalizableWhitespace(char c) {
4916
return c == 0x9 || c == 0xA || c == 0xD;
4917
}
4918
4919
// May c appear in a well-formed XML document?
4920
static bool IsValidXmlCharacter(char c) {
4921
return IsNormalizableWhitespace(c) || c >= 0x20;
4922
}
4923
4924
// Returns an XML-escaped copy of the input string str. If
4925
// is_attribute is true, the text is meant to appear as an attribute
4926
// value, and normalizable whitespace is preserved by replacing it
4927
// with character references.
4928
static std::string EscapeXml(const std::string& str, bool is_attribute);
4929
4930
// Returns the given string with all characters invalid in XML removed.
4931
static std::string RemoveInvalidXmlCharacters(const std::string& str);
4932
4933
// Convenience wrapper around EscapeXml when str is an attribute value.
4934
static std::string EscapeXmlAttribute(const std::string& str) {
4935
return EscapeXml(str, true);
4936
}
4937
4938
// Convenience wrapper around EscapeXml when str is not an attribute value.
4939
static std::string EscapeXmlText(const char* str) {
4940
return EscapeXml(str, false);
4941
}
4942
4943
// Verifies that the given attribute belongs to the given element and
4944
// streams the attribute as XML.
4945
static void OutputXmlAttribute(std::ostream* stream,
4946
const std::string& element_name,
4947
const std::string& name,
4948
const std::string& value);
4949
4950
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4951
static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4952
4953
// Streams an XML representation of a TestInfo object.
4954
static void OutputXmlTestInfo(::std::ostream* stream,
4955
const char* test_case_name,
4956
const TestInfo& test_info);
4957
4958
// Prints an XML representation of a TestCase object
4959
static void PrintXmlTestCase(::std::ostream* stream,
4960
const TestCase& test_case);
4961
4962
// Prints an XML summary of unit_test to output stream out.
4963
static void PrintXmlUnitTest(::std::ostream* stream,
4964
const UnitTest& unit_test);
4965
4966
// Produces a string representing the test properties in a result as space
4967
// delimited XML attributes based on the property key="value" pairs.
4968
// When the std::string is not empty, it includes a space at the beginning,
4969
// to delimit this attribute from prior attributes.
4970
static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
4971
4972
// Streams an XML representation of the test properties of a TestResult
4973
// object.
4974
static void OutputXmlTestProperties(std::ostream* stream,
4975
const TestResult& result);
4976
4977
// The output file.
4978
const std::string output_file_;
4979
4980
GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4981
};
4982
4983
// Creates a new XmlUnitTestResultPrinter.
4984
XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4985
: output_file_(output_file) {
4986
if (output_file_.empty()) {
4987
GTEST_LOG_(FATAL) << "XML output file may not be null";
4988
}
4989
}
4990
4991
// Called after the unit test ends.
4992
void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4993
int /*iteration*/) {
4994
FILE* xmlout = OpenFileForWriting(output_file_);
4995
std::stringstream stream;
4996
PrintXmlUnitTest(&stream, unit_test);
4997
fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4998
fclose(xmlout);
4999
}
5000
5001
void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
5002
const std::vector<TestCase*>& test_cases) {
5003
FILE* xmlout = OpenFileForWriting(output_file_);
5004
std::stringstream stream;
5005
PrintXmlTestsList(&stream, test_cases);
5006
fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5007
fclose(xmlout);
5008
}
5009
5010
// Returns an XML-escaped copy of the input string str. If is_attribute
5011
// is true, the text is meant to appear as an attribute value, and
5012
// normalizable whitespace is preserved by replacing it with character
5013
// references.
5014
//
5015
// Invalid XML characters in str, if any, are stripped from the output.
5016
// It is expected that most, if not all, of the text processed by this
5017
// module will consist of ordinary English text.
5018
// If this module is ever modified to produce version 1.1 XML output,
5019
// most invalid characters can be retained using character references.
5020
// FIXME: It might be nice to have a minimally invasive, human-readable
5021
// escaping scheme for invalid characters, rather than dropping them.
5022
std::string XmlUnitTestResultPrinter::EscapeXml(
5023
const std::string& str, bool is_attribute) {
5024
Message m;
5025
5026
for (size_t i = 0; i < str.size(); ++i) {
5027
const char ch = str[i];
5028
switch (ch) {
5029
case '<':
5030
m << "&lt;";
5031
break;
5032
case '>':
5033
m << "&gt;";
5034
break;
5035
case '&':
5036
m << "&amp;";
5037
break;
5038
case '\'':
5039
if (is_attribute)
5040
m << "&apos;";
5041
else
5042
m << '\'';
5043
break;
5044
case '"':
5045
if (is_attribute)
5046
m << "&quot;";
5047
else
5048
m << '"';
5049
break;
5050
default:
5051
if (IsValidXmlCharacter(ch)) {
5052
if (is_attribute && IsNormalizableWhitespace(ch))
5053
m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
5054
<< ";";
5055
else
5056
m << ch;
5057
}
5058
break;
5059
}
5060
}
5061
5062
return m.GetString();
5063
}
5064
5065
// Returns the given string with all characters invalid in XML removed.
5066
// Currently invalid characters are dropped from the string. An
5067
// alternative is to replace them with certain characters such as . or ?.
5068
std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
5069
const std::string& str) {
5070
std::string output;
5071
output.reserve(str.size());
5072
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
5073
if (IsValidXmlCharacter(*it))
5074
output.push_back(*it);
5075
5076
return output;
5077
}
5078
5079
// The following routines generate an XML representation of a UnitTest
5080
// object.
5081
// GOOGLETEST_CM0009 DO NOT DELETE
5082
//
5083
// This is how Google Test concepts map to the DTD:
5084
//
5085
// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
5086
// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
5087
// <testcase name="test-name"> <-- corresponds to a TestInfo object
5088
// <failure message="...">...</failure>
5089
// <failure message="...">...</failure>
5090
// <failure message="...">...</failure>
5091
// <-- individual assertion failures
5092
// </testcase>
5093
// </testsuite>
5094
// </testsuites>
5095
5096
// Formats the given time in milliseconds as seconds.
5097
std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
5098
::std::stringstream ss;
5099
ss << (static_cast<double>(ms) * 1e-3);
5100
return ss.str();
5101
}
5102
5103
static bool PortableLocaltime(time_t seconds, struct tm* out) {
5104
#if defined(_MSC_VER)
5105
return localtime_s(out, &seconds) == 0;
5106
#elif defined(__MINGW32__) || defined(__MINGW64__)
5107
// MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
5108
// Windows' localtime(), which has a thread-local tm buffer.
5109
struct tm* tm_ptr = localtime(&seconds); // NOLINT
5110
if (tm_ptr == NULL)
5111
return false;
5112
*out = *tm_ptr;
5113
return true;
5114
#else
5115
return localtime_r(&seconds, out) != NULL;
5116
#endif
5117
}
5118
5119
// Converts the given epoch time in milliseconds to a date string in the ISO
5120
// 8601 format, without the timezone information.
5121
std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
5122
struct tm time_struct;
5123
if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5124
return "";
5125
// YYYY-MM-DDThh:mm:ss
5126
return StreamableToString(time_struct.tm_year + 1900) + "-" +
5127
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5128
String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5129
String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5130
String::FormatIntWidth2(time_struct.tm_min) + ":" +
5131
String::FormatIntWidth2(time_struct.tm_sec);
5132
}
5133
5134
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
5135
void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5136
const char* data) {
5137
const char* segment = data;
5138
*stream << "<![CDATA[";
5139
for (;;) {
5140
const char* const next_segment = strstr(segment, "]]>");
5141
if (next_segment != NULL) {
5142
stream->write(
5143
segment, static_cast<std::streamsize>(next_segment - segment));
5144
*stream << "]]>]]&gt;<![CDATA[";
5145
segment = next_segment + strlen("]]>");
5146
} else {
5147
*stream << segment;
5148
break;
5149
}
5150
}
5151
*stream << "]]>";
5152
}
5153
5154
void XmlUnitTestResultPrinter::OutputXmlAttribute(
5155
std::ostream* stream,
5156
const std::string& element_name,
5157
const std::string& name,
5158
const std::string& value) {
5159
const std::vector<std::string>& allowed_names =
5160
GetReservedAttributesForElement(element_name);
5161
5162
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5163
allowed_names.end())
5164
<< "Attribute " << name << " is not allowed for element <" << element_name
5165
<< ">.";
5166
5167
*stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
5168
}
5169
5170
// Prints an XML representation of a TestInfo object.
5171
// FIXME: There is also value in printing properties with the plain printer.
5172
void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
5173
const char* test_case_name,
5174
const TestInfo& test_info) {
5175
const TestResult& result = *test_info.result();
5176
const std::string kTestcase = "testcase";
5177
5178
if (test_info.is_in_another_shard()) {
5179
return;
5180
}
5181
5182
*stream << " <testcase";
5183
OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
5184
5185
if (test_info.value_param() != NULL) {
5186
OutputXmlAttribute(stream, kTestcase, "value_param",
5187
test_info.value_param());
5188
}
5189
if (test_info.type_param() != NULL) {
5190
OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
5191
}
5192
if (GTEST_FLAG(list_tests)) {
5193
OutputXmlAttribute(stream, kTestcase, "file", test_info.file());
5194
OutputXmlAttribute(stream, kTestcase, "line",
5195
StreamableToString(test_info.line()));
5196
*stream << " />\n";
5197
return;
5198
}
5199
5200
OutputXmlAttribute(stream, kTestcase, "status",
5201
test_info.should_run() ? "run" : "notrun");
5202
OutputXmlAttribute(stream, kTestcase, "time",
5203
FormatTimeInMillisAsSeconds(result.elapsed_time()));
5204
OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
5205
5206
int failures = 0;
5207
for (int i = 0; i < result.total_part_count(); ++i) {
5208
const TestPartResult& part = result.GetTestPartResult(i);
5209
if (part.failed()) {
5210
if (++failures == 1) {
5211
*stream << ">\n";
5212
}
5213
const std::string location =
5214
internal::FormatCompilerIndependentFileLocation(part.file_name(),
5215
part.line_number());
5216
const std::string summary = location + "\n" + part.summary();
5217
*stream << " <failure message=\""
5218
<< EscapeXmlAttribute(summary.c_str())
5219
<< "\" type=\"\">";
5220
const std::string detail = location + "\n" + part.message();
5221
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5222
*stream << "</failure>\n";
5223
}
5224
}
5225
5226
if (failures == 0 && result.test_property_count() == 0) {
5227
*stream << " />\n";
5228
} else {
5229
if (failures == 0) {
5230
*stream << ">\n";
5231
}
5232
OutputXmlTestProperties(stream, result);
5233
*stream << " </testcase>\n";
5234
}
5235
}
5236
5237
// Prints an XML representation of a TestCase object
5238
void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
5239
const TestCase& test_case) {
5240
const std::string kTestsuite = "testsuite";
5241
*stream << " <" << kTestsuite;
5242
OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
5243
OutputXmlAttribute(stream, kTestsuite, "tests",
5244
StreamableToString(test_case.reportable_test_count()));
5245
if (!GTEST_FLAG(list_tests)) {
5246
OutputXmlAttribute(stream, kTestsuite, "failures",
5247
StreamableToString(test_case.failed_test_count()));
5248
OutputXmlAttribute(
5249
stream, kTestsuite, "disabled",
5250
StreamableToString(test_case.reportable_disabled_test_count()));
5251
OutputXmlAttribute(stream, kTestsuite, "errors", "0");
5252
OutputXmlAttribute(stream, kTestsuite, "time",
5253
FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
5254
*stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result());
5255
}
5256
*stream << ">\n";
5257
for (int i = 0; i < test_case.total_test_count(); ++i) {
5258
if (test_case.GetTestInfo(i)->is_reportable())
5259
OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
5260
}
5261
*stream << " </" << kTestsuite << ">\n";
5262
}
5263
5264
// Prints an XML summary of unit_test to output stream out.
5265
void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5266
const UnitTest& unit_test) {
5267
const std::string kTestsuites = "testsuites";
5268
5269
*stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5270
*stream << "<" << kTestsuites;
5271
5272
OutputXmlAttribute(stream, kTestsuites, "tests",
5273
StreamableToString(unit_test.reportable_test_count()));
5274
OutputXmlAttribute(stream, kTestsuites, "failures",
5275
StreamableToString(unit_test.failed_test_count()));
5276
OutputXmlAttribute(
5277
stream, kTestsuites, "disabled",
5278
StreamableToString(unit_test.reportable_disabled_test_count()));
5279
OutputXmlAttribute(stream, kTestsuites, "errors", "0");
5280
OutputXmlAttribute(
5281
stream, kTestsuites, "timestamp",
5282
FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5283
OutputXmlAttribute(stream, kTestsuites, "time",
5284
FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5285
5286
if (GTEST_FLAG(shuffle)) {
5287
OutputXmlAttribute(stream, kTestsuites, "random_seed",
5288
StreamableToString(unit_test.random_seed()));
5289
}
5290
*stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5291
5292
OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5293
*stream << ">\n";
5294
5295
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
5296
if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
5297
PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
5298
}
5299
*stream << "</" << kTestsuites << ">\n";
5300
}
5301
5302
void XmlUnitTestResultPrinter::PrintXmlTestsList(
5303
std::ostream* stream, const std::vector<TestCase*>& test_cases) {
5304
const std::string kTestsuites = "testsuites";
5305
5306
*stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5307
*stream << "<" << kTestsuites;
5308
5309
int total_tests = 0;
5310
for (size_t i = 0; i < test_cases.size(); ++i) {
5311
total_tests += test_cases[i]->total_test_count();
5312
}
5313
OutputXmlAttribute(stream, kTestsuites, "tests",
5314
StreamableToString(total_tests));
5315
OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5316
*stream << ">\n";
5317
5318
for (size_t i = 0; i < test_cases.size(); ++i) {
5319
PrintXmlTestCase(stream, *test_cases[i]);
5320
}
5321
*stream << "</" << kTestsuites << ">\n";
5322
}
5323
5324
// Produces a string representing the test properties in a result as space
5325
// delimited XML attributes based on the property key="value" pairs.
5326
std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5327
const TestResult& result) {
5328
Message attributes;
5329
for (int i = 0; i < result.test_property_count(); ++i) {
5330
const TestProperty& property = result.GetTestProperty(i);
5331
attributes << " " << property.key() << "="
5332
<< "\"" << EscapeXmlAttribute(property.value()) << "\"";
5333
}
5334
return attributes.GetString();
5335
}
5336
5337
void XmlUnitTestResultPrinter::OutputXmlTestProperties(
5338
std::ostream* stream, const TestResult& result) {
5339
const std::string kProperties = "properties";
5340
const std::string kProperty = "property";
5341
5342
if (result.test_property_count() <= 0) {
5343
return;
5344
}
5345
5346
*stream << "<" << kProperties << ">\n";
5347
for (int i = 0; i < result.test_property_count(); ++i) {
5348
const TestProperty& property = result.GetTestProperty(i);
5349
*stream << "<" << kProperty;
5350
*stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
5351
*stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
5352
*stream << "/>\n";
5353
}
5354
*stream << "</" << kProperties << ">\n";
5355
}
5356
5357
// End XmlUnitTestResultPrinter
5358
5359
// This class generates an JSON output file.
5360
class JsonUnitTestResultPrinter : public EmptyTestEventListener {
5361
public:
5362
explicit JsonUnitTestResultPrinter(const char* output_file);
5363
5364
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
5365
5366
// Prints an JSON summary of all unit tests.
5367
static void PrintJsonTestList(::std::ostream* stream,
5368
const std::vector<TestCase*>& test_cases);
5369
5370
private:
5371
// Returns an JSON-escaped copy of the input string str.
5372
static std::string EscapeJson(const std::string& str);
5373
5374
//// Verifies that the given attribute belongs to the given element and
5375
//// streams the attribute as JSON.
5376
static void OutputJsonKey(std::ostream* stream,
5377
const std::string& element_name,
5378
const std::string& name,
5379
const std::string& value,
5380
const std::string& indent,
5381
bool comma = true);
5382
static void OutputJsonKey(std::ostream* stream,
5383
const std::string& element_name,
5384
const std::string& name,
5385
int value,
5386
const std::string& indent,
5387
bool comma = true);
5388
5389
// Streams a JSON representation of a TestInfo object.
5390
static void OutputJsonTestInfo(::std::ostream* stream,
5391
const char* test_case_name,
5392
const TestInfo& test_info);
5393
5394
// Prints a JSON representation of a TestCase object
5395
static void PrintJsonTestCase(::std::ostream* stream,
5396
const TestCase& test_case);
5397
5398
// Prints a JSON summary of unit_test to output stream out.
5399
static void PrintJsonUnitTest(::std::ostream* stream,
5400
const UnitTest& unit_test);
5401
5402
// Produces a string representing the test properties in a result as
5403
// a JSON dictionary.
5404
static std::string TestPropertiesAsJson(const TestResult& result,
5405
const std::string& indent);
5406
5407
// The output file.
5408
const std::string output_file_;
5409
5410
GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
5411
};
5412
5413
// Creates a new JsonUnitTestResultPrinter.
5414
JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
5415
: output_file_(output_file) {
5416
if (output_file_.empty()) {
5417
GTEST_LOG_(FATAL) << "JSON output file may not be null";
5418
}
5419
}
5420
5421
void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5422
int /*iteration*/) {
5423
FILE* jsonout = OpenFileForWriting(output_file_);
5424
std::stringstream stream;
5425
PrintJsonUnitTest(&stream, unit_test);
5426
fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
5427
fclose(jsonout);
5428
}
5429
5430
// Returns an JSON-escaped copy of the input string str.
5431
std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
5432
Message m;
5433
5434
for (size_t i = 0; i < str.size(); ++i) {
5435
const char ch = str[i];
5436
switch (ch) {
5437
case '\\':
5438
case '"':
5439
case '/':
5440
m << '\\' << ch;
5441
break;
5442
case '\b':
5443
m << "\\b";
5444
break;
5445
case '\t':
5446
m << "\\t";
5447
break;
5448
case '\n':
5449
m << "\\n";
5450
break;
5451
case '\f':
5452
m << "\\f";
5453
break;
5454
case '\r':
5455
m << "\\r";
5456
break;
5457
default:
5458
if (ch < ' ') {
5459
m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
5460
} else {
5461
m << ch;
5462
}
5463
break;
5464
}
5465
}
5466
5467
return m.GetString();
5468
}
5469
5470
// The following routines generate an JSON representation of a UnitTest
5471
// object.
5472
5473
// Formats the given time in milliseconds as seconds.
5474
static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
5475
::std::stringstream ss;
5476
ss << (static_cast<double>(ms) * 1e-3) << "s";
5477
return ss.str();
5478
}
5479
5480
// Converts the given epoch time in milliseconds to a date string in the
5481
// RFC3339 format, without the timezone information.
5482
static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
5483
struct tm time_struct;
5484
if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5485
return "";
5486
// YYYY-MM-DDThh:mm:ss
5487
return StreamableToString(time_struct.tm_year + 1900) + "-" +
5488
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5489
String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5490
String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5491
String::FormatIntWidth2(time_struct.tm_min) + ":" +
5492
String::FormatIntWidth2(time_struct.tm_sec) + "Z";
5493
}
5494
5495
static inline std::string Indent(int width) {
5496
return std::string(width, ' ');
5497
}
5498
5499
void JsonUnitTestResultPrinter::OutputJsonKey(
5500
std::ostream* stream,
5501
const std::string& element_name,
5502
const std::string& name,
5503
const std::string& value,
5504
const std::string& indent,
5505
bool comma) {
5506
const std::vector<std::string>& allowed_names =
5507
GetReservedAttributesForElement(element_name);
5508
5509
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5510
allowed_names.end())
5511
<< "Key \"" << name << "\" is not allowed for value \"" << element_name
5512
<< "\".";
5513
5514
*stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
5515
if (comma)
5516
*stream << ",\n";
5517
}
5518
5519
void JsonUnitTestResultPrinter::OutputJsonKey(
5520
std::ostream* stream,
5521
const std::string& element_name,
5522
const std::string& name,
5523
int value,
5524
const std::string& indent,
5525
bool comma) {
5526
const std::vector<std::string>& allowed_names =
5527
GetReservedAttributesForElement(element_name);
5528
5529
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5530
allowed_names.end())
5531
<< "Key \"" << name << "\" is not allowed for value \"" << element_name
5532
<< "\".";
5533
5534
*stream << indent << "\"" << name << "\": " << StreamableToString(value);
5535
if (comma)
5536
*stream << ",\n";
5537
}
5538
5539
// Prints a JSON representation of a TestInfo object.
5540
void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
5541
const char* test_case_name,
5542
const TestInfo& test_info) {
5543
const TestResult& result = *test_info.result();
5544
const std::string kTestcase = "testcase";
5545
const std::string kIndent = Indent(10);
5546
5547
*stream << Indent(8) << "{\n";
5548
OutputJsonKey(stream, kTestcase, "name", test_info.name(), kIndent);
5549
5550
if (test_info.value_param() != NULL) {
5551
OutputJsonKey(stream, kTestcase, "value_param",
5552
test_info.value_param(), kIndent);
5553
}
5554
if (test_info.type_param() != NULL) {
5555
OutputJsonKey(stream, kTestcase, "type_param", test_info.type_param(),
5556
kIndent);
5557
}
5558
if (GTEST_FLAG(list_tests)) {
5559
OutputJsonKey(stream, kTestcase, "file", test_info.file(), kIndent);
5560
OutputJsonKey(stream, kTestcase, "line", test_info.line(), kIndent, false);
5561
*stream << "\n" << Indent(8) << "}";
5562
return;
5563
}
5564
5565
OutputJsonKey(stream, kTestcase, "status",
5566
test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
5567
OutputJsonKey(stream, kTestcase, "time",
5568
FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
5569
OutputJsonKey(stream, kTestcase, "classname", test_case_name, kIndent, false);
5570
*stream << TestPropertiesAsJson(result, kIndent);
5571
5572
int failures = 0;
5573
for (int i = 0; i < result.total_part_count(); ++i) {
5574
const TestPartResult& part = result.GetTestPartResult(i);
5575
if (part.failed()) {
5576
*stream << ",\n";
5577
if (++failures == 1) {
5578
*stream << kIndent << "\"" << "failures" << "\": [\n";
5579
}
5580
const std::string location =
5581
internal::FormatCompilerIndependentFileLocation(part.file_name(),
5582
part.line_number());
5583
const std::string message = EscapeJson(location + "\n" + part.message());
5584
*stream << kIndent << " {\n"
5585
<< kIndent << " \"failure\": \"" << message << "\",\n"
5586
<< kIndent << " \"type\": \"\"\n"
5587
<< kIndent << " }";
5588
}
5589
}
5590
5591
if (failures > 0)
5592
*stream << "\n" << kIndent << "]";
5593
*stream << "\n" << Indent(8) << "}";
5594
}
5595
5596
// Prints an JSON representation of a TestCase object
5597
void JsonUnitTestResultPrinter::PrintJsonTestCase(std::ostream* stream,
5598
const TestCase& test_case) {
5599
const std::string kTestsuite = "testsuite";
5600
const std::string kIndent = Indent(6);
5601
5602
*stream << Indent(4) << "{\n";
5603
OutputJsonKey(stream, kTestsuite, "name", test_case.name(), kIndent);
5604
OutputJsonKey(stream, kTestsuite, "tests", test_case.reportable_test_count(),
5605
kIndent);
5606
if (!GTEST_FLAG(list_tests)) {
5607
OutputJsonKey(stream, kTestsuite, "failures", test_case.failed_test_count(),
5608
kIndent);
5609
OutputJsonKey(stream, kTestsuite, "disabled",
5610
test_case.reportable_disabled_test_count(), kIndent);
5611
OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
5612
OutputJsonKey(stream, kTestsuite, "time",
5613
FormatTimeInMillisAsDuration(test_case.elapsed_time()),
5614
kIndent, false);
5615
*stream << TestPropertiesAsJson(test_case.ad_hoc_test_result(), kIndent)
5616
<< ",\n";
5617
}
5618
5619
*stream << kIndent << "\"" << kTestsuite << "\": [\n";
5620
5621
bool comma = false;
5622
for (int i = 0; i < test_case.total_test_count(); ++i) {
5623
if (test_case.GetTestInfo(i)->is_reportable()) {
5624
if (comma) {
5625
*stream << ",\n";
5626
} else {
5627
comma = true;
5628
}
5629
OutputJsonTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
5630
}
5631
}
5632
*stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
5633
}
5634
5635
// Prints a JSON summary of unit_test to output stream out.
5636
void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
5637
const UnitTest& unit_test) {
5638
const std::string kTestsuites = "testsuites";
5639
const std::string kIndent = Indent(2);
5640
*stream << "{\n";
5641
5642
OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
5643
kIndent);
5644
OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
5645
kIndent);
5646
OutputJsonKey(stream, kTestsuites, "disabled",
5647
unit_test.reportable_disabled_test_count(), kIndent);
5648
OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
5649
if (GTEST_FLAG(shuffle)) {
5650
OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
5651
kIndent);
5652
}
5653
OutputJsonKey(stream, kTestsuites, "timestamp",
5654
FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
5655
kIndent);
5656
OutputJsonKey(stream, kTestsuites, "time",
5657
FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
5658
false);
5659
5660
*stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
5661
<< ",\n";
5662
5663
OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
5664
*stream << kIndent << "\"" << kTestsuites << "\": [\n";
5665
5666
bool comma = false;
5667
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
5668
if (unit_test.GetTestCase(i)->reportable_test_count() > 0) {
5669
if (comma) {
5670
*stream << ",\n";
5671
} else {
5672
comma = true;
5673
}
5674
PrintJsonTestCase(stream, *unit_test.GetTestCase(i));
5675
}
5676
}
5677
5678
*stream << "\n" << kIndent << "]\n" << "}\n";
5679
}
5680
5681
void JsonUnitTestResultPrinter::PrintJsonTestList(
5682
std::ostream* stream, const std::vector<TestCase*>& test_cases) {
5683
const std::string kTestsuites = "testsuites";
5684
const std::string kIndent = Indent(2);
5685
*stream << "{\n";
5686
int total_tests = 0;
5687
for (size_t i = 0; i < test_cases.size(); ++i) {
5688
total_tests += test_cases[i]->total_test_count();
5689
}
5690
OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
5691
5692
OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
5693
*stream << kIndent << "\"" << kTestsuites << "\": [\n";
5694
5695
for (size_t i = 0; i < test_cases.size(); ++i) {
5696
if (i != 0) {
5697
*stream << ",\n";
5698
}
5699
PrintJsonTestCase(stream, *test_cases[i]);
5700
}
5701
5702
*stream << "\n"
5703
<< kIndent << "]\n"
5704
<< "}\n";
5705
}
5706
// Produces a string representing the test properties in a result as
5707
// a JSON dictionary.
5708
std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
5709
const TestResult& result, const std::string& indent) {
5710
Message attributes;
5711
for (int i = 0; i < result.test_property_count(); ++i) {
5712
const TestProperty& property = result.GetTestProperty(i);
5713
attributes << ",\n" << indent << "\"" << property.key() << "\": "
5714
<< "\"" << EscapeJson(property.value()) << "\"";
5715
}
5716
return attributes.GetString();
5717
}
5718
5719
// End JsonUnitTestResultPrinter
5720
5721
#if GTEST_CAN_STREAM_RESULTS_
5722
5723
// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
5724
// replaces them by "%xx" where xx is their hexadecimal value. For
5725
// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
5726
// in both time and space -- important as the input str may contain an
5727
// arbitrarily long test failure message and stack trace.
5728
std::string StreamingListener::UrlEncode(const char* str) {
5729
std::string result;
5730
result.reserve(strlen(str) + 1);
5731
for (char ch = *str; ch != '\0'; ch = *++str) {
5732
switch (ch) {
5733
case '%':
5734
case '=':
5735
case '&':
5736
case '\n':
5737
result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
5738
break;
5739
default:
5740
result.push_back(ch);
5741
break;
5742
}
5743
}
5744
return result;
5745
}
5746
5747
void StreamingListener::SocketWriter::MakeConnection() {
5748
GTEST_CHECK_(sockfd_ == -1)
5749
<< "MakeConnection() can't be called when there is already a connection.";
5750
5751
addrinfo hints;
5752
memset(&hints, 0, sizeof(hints));
5753
hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
5754
hints.ai_socktype = SOCK_STREAM;
5755
addrinfo* servinfo = NULL;
5756
5757
// Use the getaddrinfo() to get a linked list of IP addresses for
5758
// the given host name.
5759
const int error_num = getaddrinfo(
5760
host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5761
if (error_num != 0) {
5762
GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
5763
<< gai_strerror(error_num);
5764
}
5765
5766
// Loop through all the results and connect to the first we can.
5767
for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
5768
cur_addr = cur_addr->ai_next) {
5769
sockfd_ = socket(
5770
cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
5771
if (sockfd_ != -1) {
5772
// Connect the client socket to the server socket.
5773
if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5774
close(sockfd_);
5775
sockfd_ = -1;
5776
}
5777
}
5778
}
5779
5780
freeaddrinfo(servinfo); // all done with this structure
5781
5782
if (sockfd_ == -1) {
5783
GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
5784
<< host_name_ << ":" << port_num_;
5785
}
5786
}
5787
5788
// End of class Streaming Listener
5789
#endif // GTEST_CAN_STREAM_RESULTS__
5790
5791
// class OsStackTraceGetter
5792
5793
const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
5794
"... " GTEST_NAME_ " internal frames ...";
5795
5796
std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
5797
GTEST_LOCK_EXCLUDED_(mutex_) {
5798
#if GTEST_HAS_ABSL
5799
std::string result;
5800
5801
if (max_depth <= 0) {
5802
return result;
5803
}
5804
5805
max_depth = std::min(max_depth, kMaxStackTraceDepth);
5806
5807
std::vector<void*> raw_stack(max_depth);
5808
// Skips the frames requested by the caller, plus this function.
5809
const int raw_stack_size =
5810
absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
5811
5812
void* caller_frame = nullptr;
5813
{
5814
MutexLock lock(&mutex_);
5815
caller_frame = caller_frame_;
5816
}
5817
5818
for (int i = 0; i < raw_stack_size; ++i) {
5819
if (raw_stack[i] == caller_frame &&
5820
!GTEST_FLAG(show_internal_stack_frames)) {
5821
// Add a marker to the trace and stop adding frames.
5822
absl::StrAppend(&result, kElidedFramesMarker, "\n");
5823
break;
5824
}
5825
5826
char tmp[1024];
5827
const char* symbol = "(unknown)";
5828
if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
5829
symbol = tmp;
5830
}
5831
5832
char line[1024];
5833
snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
5834
result += line;
5835
}
5836
5837
return result;
5838
5839
#else // !GTEST_HAS_ABSL
5840
static_cast<void>(max_depth);
5841
static_cast<void>(skip_count);
5842
return "";
5843
#endif // GTEST_HAS_ABSL
5844
}
5845
5846
void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
5847
#if GTEST_HAS_ABSL
5848
void* caller_frame = nullptr;
5849
if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5850
caller_frame = nullptr;
5851
}
5852
5853
MutexLock lock(&mutex_);
5854
caller_frame_ = caller_frame;
5855
#endif // GTEST_HAS_ABSL
5856
}
5857
5858
// A helper class that creates the premature-exit file in its
5859
// constructor and deletes the file in its destructor.
5860
class ScopedPrematureExitFile {
5861
public:
5862
explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5863
: premature_exit_filepath_(premature_exit_filepath ?
5864
premature_exit_filepath : "") {
5865
// If a path to the premature-exit file is specified...
5866
if (!premature_exit_filepath_.empty()) {
5867
// create the file with a single "0" character in it. I/O
5868
// errors are ignored as there's nothing better we can do and we
5869
// don't want to fail the test because of this.
5870
FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5871
fwrite("0", 1, 1, pfile);
5872
fclose(pfile);
5873
}
5874
}
5875
5876
~ScopedPrematureExitFile() {
5877
if (!premature_exit_filepath_.empty()) {
5878
int retval = remove(premature_exit_filepath_.c_str());
5879
if (retval) {
5880
GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
5881
<< premature_exit_filepath_ << "\" with error "
5882
<< retval;
5883
}
5884
}
5885
}
5886
5887
private:
5888
const std::string premature_exit_filepath_;
5889
5890
GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
5891
};
5892
5893
} // namespace internal
5894
5895
// class TestEventListeners
5896
5897
TestEventListeners::TestEventListeners()
5898
: repeater_(new internal::TestEventRepeater()),
5899
default_result_printer_(NULL),
5900
default_xml_generator_(NULL) {
5901
}
5902
5903
TestEventListeners::~TestEventListeners() { delete repeater_; }
5904
5905
// Returns the standard listener responsible for the default console
5906
// output. Can be removed from the listeners list to shut down default
5907
// console output. Note that removing this object from the listener list
5908
// with Release transfers its ownership to the user.
5909
void TestEventListeners::Append(TestEventListener* listener) {
5910
repeater_->Append(listener);
5911
}
5912
5913
// Removes the given event listener from the list and returns it. It then
5914
// becomes the caller's responsibility to delete the listener. Returns
5915
// NULL if the listener is not found in the list.
5916
TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5917
if (listener == default_result_printer_)
5918
default_result_printer_ = NULL;
5919
else if (listener == default_xml_generator_)
5920
default_xml_generator_ = NULL;
5921
return repeater_->Release(listener);
5922
}
5923
5924
// Returns repeater that broadcasts the TestEventListener events to all
5925
// subscribers.
5926
TestEventListener* TestEventListeners::repeater() { return repeater_; }
5927
5928
// Sets the default_result_printer attribute to the provided listener.
5929
// The listener is also added to the listener list and previous
5930
// default_result_printer is removed from it and deleted. The listener can
5931
// also be NULL in which case it will not be added to the list. Does
5932
// nothing if the previous and the current listener objects are the same.
5933
void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5934
if (default_result_printer_ != listener) {
5935
// It is an error to pass this method a listener that is already in the
5936
// list.
5937
delete Release(default_result_printer_);
5938
default_result_printer_ = listener;
5939
if (listener != NULL)
5940
Append(listener);
5941
}
5942
}
5943
5944
// Sets the default_xml_generator attribute to the provided listener. The
5945
// listener is also added to the listener list and previous
5946
// default_xml_generator is removed from it and deleted. The listener can
5947
// also be NULL in which case it will not be added to the list. Does
5948
// nothing if the previous and the current listener objects are the same.
5949
void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5950
if (default_xml_generator_ != listener) {
5951
// It is an error to pass this method a listener that is already in the
5952
// list.
5953
delete Release(default_xml_generator_);
5954
default_xml_generator_ = listener;
5955
if (listener != NULL)
5956
Append(listener);
5957
}
5958
}
5959
5960
// Controls whether events will be forwarded by the repeater to the
5961
// listeners in the list.
5962
bool TestEventListeners::EventForwardingEnabled() const {
5963
return repeater_->forwarding_enabled();
5964
}
5965
5966
void TestEventListeners::SuppressEventForwarding() {
5967
repeater_->set_forwarding_enabled(false);
5968
}
5969
5970
// class UnitTest
5971
5972
// Gets the singleton UnitTest object. The first time this method is
5973
// called, a UnitTest object is constructed and returned. Consecutive
5974
// calls will return the same object.
5975
//
5976
// We don't protect this under mutex_ as a user is not supposed to
5977
// call this before main() starts, from which point on the return
5978
// value will never change.
5979
UnitTest* UnitTest::GetInstance() {
5980
// When compiled with MSVC 7.1 in optimized mode, destroying the
5981
// UnitTest object upon exiting the program messes up the exit code,
5982
// causing successful tests to appear failed. We have to use a
5983
// different implementation in this case to bypass the compiler bug.
5984
// This implementation makes the compiler happy, at the cost of
5985
// leaking the UnitTest object.
5986
5987
// CodeGear C++Builder insists on a public destructor for the
5988
// default implementation. Use this implementation to keep good OO
5989
// design with private destructor.
5990
5991
#if (defined(_MSC_VER) && _MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5992
static UnitTest* const instance = new UnitTest;
5993
return instance;
5994
#else
5995
static UnitTest instance;
5996
return &instance;
5997
#endif // (defined(_MSC_VER) && _MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5998
}
5999
6000
// Gets the number of successful test cases.
6001
int UnitTest::successful_test_case_count() const {
6002
return impl()->successful_test_case_count();
6003
}
6004
6005
// Gets the number of failed test cases.
6006
int UnitTest::failed_test_case_count() const {
6007
return impl()->failed_test_case_count();
6008
}
6009
6010
// Gets the number of all test cases.
6011
int UnitTest::total_test_case_count() const {
6012
return impl()->total_test_case_count();
6013
}
6014
6015
// Gets the number of all test cases that contain at least one test
6016
// that should run.
6017
int UnitTest::test_case_to_run_count() const {
6018
return impl()->test_case_to_run_count();
6019
}
6020
6021
// Gets the number of successful tests.
6022
int UnitTest::successful_test_count() const {
6023
return impl()->successful_test_count();
6024
}
6025
6026
// Gets the number of failed tests.
6027
int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
6028
6029
// Gets the number of disabled tests that will be reported in the XML report.
6030
int UnitTest::reportable_disabled_test_count() const {
6031
return impl()->reportable_disabled_test_count();
6032
}
6033
6034
// Gets the number of disabled tests.
6035
int UnitTest::disabled_test_count() const {
6036
return impl()->disabled_test_count();
6037
}
6038
6039
// Gets the number of tests to be printed in the XML report.
6040
int UnitTest::reportable_test_count() const {
6041
return impl()->reportable_test_count();
6042
}
6043
6044
// Gets the number of all tests.
6045
int UnitTest::total_test_count() const { return impl()->total_test_count(); }
6046
6047
// Gets the number of tests that should run.
6048
int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
6049
6050
// Gets the time of the test program start, in ms from the start of the
6051
// UNIX epoch.
6052
internal::TimeInMillis UnitTest::start_timestamp() const {
6053
return impl()->start_timestamp();
6054
}
6055
6056
// Gets the elapsed time, in milliseconds.
6057
internal::TimeInMillis UnitTest::elapsed_time() const {
6058
return impl()->elapsed_time();
6059
}
6060
6061
// Returns true iff the unit test passed (i.e. all test cases passed).
6062
bool UnitTest::Passed() const { return impl()->Passed(); }
6063
6064
// Returns true iff the unit test failed (i.e. some test case failed
6065
// or something outside of all tests failed).
6066
bool UnitTest::Failed() const { return impl()->Failed(); }
6067
6068
// Gets the i-th test case among all the test cases. i can range from 0 to
6069
// total_test_case_count() - 1. If i is not in that range, returns NULL.
6070
const TestCase* UnitTest::GetTestCase(int i) const {
6071
return impl()->GetTestCase(i);
6072
}
6073
6074
// Returns the TestResult containing information on test failures and
6075
// properties logged outside of individual test cases.
6076
const TestResult& UnitTest::ad_hoc_test_result() const {
6077
return *impl()->ad_hoc_test_result();
6078
}
6079
6080
// Gets the i-th test case among all the test cases. i can range from 0 to
6081
// total_test_case_count() - 1. If i is not in that range, returns NULL.
6082
TestCase* UnitTest::GetMutableTestCase(int i) {
6083
return impl()->GetMutableTestCase(i);
6084
}
6085
6086
// Returns the list of event listeners that can be used to track events
6087
// inside Google Test.
6088
TestEventListeners& UnitTest::listeners() {
6089
return *impl()->listeners();
6090
}
6091
6092
// Registers and returns a global test environment. When a test
6093
// program is run, all global test environments will be set-up in the
6094
// order they were registered. After all tests in the program have
6095
// finished, all global test environments will be torn-down in the
6096
// *reverse* order they were registered.
6097
//
6098
// The UnitTest object takes ownership of the given environment.
6099
//
6100
// We don't protect this under mutex_, as we only support calling it
6101
// from the main thread.
6102
Environment* UnitTest::AddEnvironment(Environment* env) {
6103
if (env == NULL) {
6104
return NULL;
6105
}
6106
6107
impl_->environments().push_back(env);
6108
return env;
6109
}
6110
6111
// Adds a TestPartResult to the current TestResult object. All Google Test
6112
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
6113
// this to report their results. The user code should use the
6114
// assertion macros instead of calling this directly.
6115
void UnitTest::AddTestPartResult(
6116
TestPartResult::Type result_type,
6117
const char* file_name,
6118
int line_number,
6119
const std::string& message,
6120
const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
6121
Message msg;
6122
msg << message;
6123
6124
internal::MutexLock lock(&mutex_);
6125
if (impl_->gtest_trace_stack().size() > 0) {
6126
msg << "\n" << GTEST_NAME_ << " trace:";
6127
6128
for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
6129
i > 0; --i) {
6130
const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
6131
msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
6132
<< " " << trace.message;
6133
}
6134
}
6135
6136
if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
6137
msg << internal::kStackTraceMarker << os_stack_trace;
6138
}
6139
6140
const TestPartResult result =
6141
TestPartResult(result_type, file_name, line_number,
6142
msg.GetString().c_str());
6143
impl_->GetTestPartResultReporterForCurrentThread()->
6144
ReportTestPartResult(result);
6145
6146
if (result_type != TestPartResult::kSuccess) {
6147
// gtest_break_on_failure takes precedence over
6148
// gtest_throw_on_failure. This allows a user to set the latter
6149
// in the code (perhaps in order to use Google Test assertions
6150
// with another testing framework) and specify the former on the
6151
// command line for debugging.
6152
if (GTEST_FLAG(break_on_failure)) {
6153
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6154
// Using DebugBreak on Windows allows gtest to still break into a debugger
6155
// when a failure happens and both the --gtest_break_on_failure and
6156
// the --gtest_catch_exceptions flags are specified.
6157
DebugBreak();
6158
#elif (!defined(__native_client__)) && \
6159
((defined(__clang__) || defined(__GNUC__)) && \
6160
(defined(__x86_64__) || defined(__i386__)))
6161
// with clang/gcc we can achieve the same effect on x86 by invoking int3
6162
asm("int3");
6163
#else
6164
// Dereference NULL through a volatile pointer to prevent the compiler
6165
// from removing. We use this rather than abort() or __builtin_trap() for
6166
// portability: Symbian doesn't implement abort() well, and some debuggers
6167
// don't correctly trap abort().
6168
*static_cast<volatile int*>(NULL) = 1;
6169
#endif // GTEST_OS_WINDOWS
6170
} else if (GTEST_FLAG(throw_on_failure)) {
6171
#if GTEST_HAS_EXCEPTIONS
6172
throw internal::GoogleTestFailureException(result);
6173
#else
6174
// We cannot call abort() as it generates a pop-up in debug mode
6175
// that cannot be suppressed in VC 7.1 or below.
6176
exit(1);
6177
#endif
6178
}
6179
}
6180
}
6181
6182
// Adds a TestProperty to the current TestResult object when invoked from
6183
// inside a test, to current TestCase's ad_hoc_test_result_ when invoked
6184
// from SetUpTestCase or TearDownTestCase, or to the global property set
6185
// when invoked elsewhere. If the result already contains a property with
6186
// the same key, the value will be updated.
6187
void UnitTest::RecordProperty(const std::string& key,
6188
const std::string& value) {
6189
impl_->RecordProperty(TestProperty(key, value));
6190
}
6191
6192
// Runs all tests in this UnitTest object and prints the result.
6193
// Returns 0 if successful, or 1 otherwise.
6194
//
6195
// We don't protect this under mutex_, as we only support calling it
6196
// from the main thread.
6197
int UnitTest::Run() {
6198
const bool in_death_test_child_process =
6199
internal::GTEST_FLAG(internal_run_death_test).length() > 0;
6200
6201
// Google Test implements this protocol for catching that a test
6202
// program exits before returning control to Google Test:
6203
//
6204
// 1. Upon start, Google Test creates a file whose absolute path
6205
// is specified by the environment variable
6206
// TEST_PREMATURE_EXIT_FILE.
6207
// 2. When Google Test has finished its work, it deletes the file.
6208
//
6209
// This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
6210
// running a Google-Test-based test program and check the existence
6211
// of the file at the end of the test execution to see if it has
6212
// exited prematurely.
6213
6214
// If we are in the child process of a death test, don't
6215
// create/delete the premature exit file, as doing so is unnecessary
6216
// and will confuse the parent process. Otherwise, create/delete
6217
// the file upon entering/leaving this function. If the program
6218
// somehow exits before this function has a chance to return, the
6219
// premature-exit file will be left undeleted, causing a test runner
6220
// that understands the premature-exit-file protocol to report the
6221
// test as having failed.
6222
const internal::ScopedPrematureExitFile premature_exit_file(
6223
in_death_test_child_process ?
6224
NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
6225
6226
// Captures the value of GTEST_FLAG(catch_exceptions). This value will be
6227
// used for the duration of the program.
6228
impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
6229
6230
#if GTEST_OS_WINDOWS
6231
// Either the user wants Google Test to catch exceptions thrown by the
6232
// tests or this is executing in the context of death test child
6233
// process. In either case the user does not want to see pop-up dialogs
6234
// about crashes - they are expected.
6235
if (impl()->catch_exceptions() || in_death_test_child_process) {
6236
# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6237
// SetErrorMode doesn't exist on CE.
6238
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
6239
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
6240
# endif // !GTEST_OS_WINDOWS_MOBILE
6241
6242
# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
6243
// Death test children can be terminated with _abort(). On Windows,
6244
// _abort() can show a dialog with a warning message. This forces the
6245
// abort message to go to stderr instead.
6246
_set_error_mode(_OUT_TO_STDERR);
6247
# endif
6248
6249
# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
6250
// In the debug version, Visual Studio pops up a separate dialog
6251
// offering a choice to debug the aborted program. We need to suppress
6252
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
6253
// executed. Google Test will notify the user of any unexpected
6254
// failure via stderr.
6255
//
6256
// VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
6257
// Users of prior VC versions shall suffer the agony and pain of
6258
// clicking through the countless debug dialogs.
6259
// FIXME: find a way to suppress the abort dialog() in the
6260
// debug mode when compiled with VC 7.1 or lower.
6261
if (!GTEST_FLAG(break_on_failure))
6262
_set_abort_behavior(
6263
0x0, // Clear the following flags:
6264
_WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
6265
# endif
6266
}
6267
#endif // GTEST_OS_WINDOWS
6268
6269
return internal::HandleExceptionsInMethodIfSupported(
6270
impl(),
6271
&internal::UnitTestImpl::RunAllTests,
6272
"auxiliary test code (environments or event listeners)") ? 0 : 1;
6273
}
6274
6275
// Returns the working directory when the first TEST() or TEST_F() was
6276
// executed.
6277
const char* UnitTest::original_working_dir() const {
6278
return impl_->original_working_dir_.c_str();
6279
}
6280
6281
// Returns the TestCase object for the test that's currently running,
6282
// or NULL if no test is running.
6283
const TestCase* UnitTest::current_test_case() const
6284
GTEST_LOCK_EXCLUDED_(mutex_) {
6285
internal::MutexLock lock(&mutex_);
6286
return impl_->current_test_case();
6287
}
6288
6289
// Returns the TestInfo object for the test that's currently running,
6290
// or NULL if no test is running.
6291
const TestInfo* UnitTest::current_test_info() const
6292
GTEST_LOCK_EXCLUDED_(mutex_) {
6293
internal::MutexLock lock(&mutex_);
6294
return impl_->current_test_info();
6295
}
6296
6297
// Returns the random seed used at the start of the current test run.
6298
int UnitTest::random_seed() const { return impl_->random_seed(); }
6299
6300
// Returns ParameterizedTestCaseRegistry object used to keep track of
6301
// value-parameterized tests and instantiate and register them.
6302
internal::ParameterizedTestCaseRegistry&
6303
UnitTest::parameterized_test_registry()
6304
GTEST_LOCK_EXCLUDED_(mutex_) {
6305
return impl_->parameterized_test_registry();
6306
}
6307
6308
// Creates an empty UnitTest.
6309
UnitTest::UnitTest() {
6310
impl_ = new internal::UnitTestImpl(this);
6311
}
6312
6313
// Destructor of UnitTest.
6314
UnitTest::~UnitTest() {
6315
delete impl_;
6316
}
6317
6318
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
6319
// Google Test trace stack.
6320
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
6321
GTEST_LOCK_EXCLUDED_(mutex_) {
6322
internal::MutexLock lock(&mutex_);
6323
impl_->gtest_trace_stack().push_back(trace);
6324
}
6325
6326
// Pops a trace from the per-thread Google Test trace stack.
6327
void UnitTest::PopGTestTrace()
6328
GTEST_LOCK_EXCLUDED_(mutex_) {
6329
internal::MutexLock lock(&mutex_);
6330
impl_->gtest_trace_stack().pop_back();
6331
}
6332
6333
namespace internal {
6334
6335
UnitTestImpl::UnitTestImpl(UnitTest* parent)
6336
: parent_(parent),
6337
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
6338
default_global_test_part_result_reporter_(this),
6339
default_per_thread_test_part_result_reporter_(this),
6340
GTEST_DISABLE_MSC_WARNINGS_POP_()
6341
global_test_part_result_repoter_(
6342
&default_global_test_part_result_reporter_),
6343
per_thread_test_part_result_reporter_(
6344
&default_per_thread_test_part_result_reporter_),
6345
parameterized_test_registry_(),
6346
parameterized_tests_registered_(false),
6347
last_death_test_case_(-1),
6348
current_test_case_(NULL),
6349
current_test_info_(NULL),
6350
ad_hoc_test_result_(),
6351
os_stack_trace_getter_(NULL),
6352
post_flag_parse_init_performed_(false),
6353
random_seed_(0), // Will be overridden by the flag before first use.
6354
random_(0), // Will be reseeded before first use.
6355
start_timestamp_(0),
6356
elapsed_time_(0),
6357
#if GTEST_HAS_DEATH_TEST
6358
death_test_factory_(new DefaultDeathTestFactory),
6359
#endif
6360
// Will be overridden by the flag before first use.
6361
catch_exceptions_(false) {
6362
listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
6363
}
6364
6365
UnitTestImpl::~UnitTestImpl() {
6366
// Deletes every TestCase.
6367
ForEach(test_cases_, internal::Delete<TestCase>);
6368
6369
// Deletes every Environment.
6370
ForEach(environments_, internal::Delete<Environment>);
6371
6372
delete os_stack_trace_getter_;
6373
}
6374
6375
// Adds a TestProperty to the current TestResult object when invoked in a
6376
// context of a test, to current test case's ad_hoc_test_result when invoke
6377
// from SetUpTestCase/TearDownTestCase, or to the global property set
6378
// otherwise. If the result already contains a property with the same key,
6379
// the value will be updated.
6380
void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
6381
std::string xml_element;
6382
TestResult* test_result; // TestResult appropriate for property recording.
6383
6384
if (current_test_info_ != NULL) {
6385
xml_element = "testcase";
6386
test_result = &(current_test_info_->result_);
6387
} else if (current_test_case_ != NULL) {
6388
xml_element = "testsuite";
6389
test_result = &(current_test_case_->ad_hoc_test_result_);
6390
} else {
6391
xml_element = "testsuites";
6392
test_result = &ad_hoc_test_result_;
6393
}
6394
test_result->RecordProperty(xml_element, test_property);
6395
}
6396
6397
#if GTEST_HAS_DEATH_TEST
6398
// Disables event forwarding if the control is currently in a death test
6399
// subprocess. Must not be called before InitGoogleTest.
6400
void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
6401
if (internal_run_death_test_flag_.get() != NULL)
6402
listeners()->SuppressEventForwarding();
6403
}
6404
#endif // GTEST_HAS_DEATH_TEST
6405
6406
// Initializes event listeners performing XML output as specified by
6407
// UnitTestOptions. Must not be called before InitGoogleTest.
6408
void UnitTestImpl::ConfigureXmlOutput() {
6409
const std::string& output_format = UnitTestOptions::GetOutputFormat();
6410
if (output_format == "xml") {
6411
listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
6412
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
6413
} else if (output_format == "json") {
6414
listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
6415
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
6416
} else if (output_format != "") {
6417
GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
6418
<< output_format << "\" ignored.";
6419
}
6420
}
6421
6422
#if GTEST_CAN_STREAM_RESULTS_
6423
// Initializes event listeners for streaming test results in string form.
6424
// Must not be called before InitGoogleTest.
6425
void UnitTestImpl::ConfigureStreamingOutput() {
6426
const std::string& target = GTEST_FLAG(stream_result_to);
6427
if (!target.empty()) {
6428
const size_t pos = target.find(':');
6429
if (pos != std::string::npos) {
6430
listeners()->Append(new StreamingListener(target.substr(0, pos),
6431
target.substr(pos+1)));
6432
} else {
6433
GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
6434
<< "\" ignored.";
6435
}
6436
}
6437
}
6438
#endif // GTEST_CAN_STREAM_RESULTS_
6439
6440
// Performs initialization dependent upon flag values obtained in
6441
// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
6442
// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
6443
// this function is also called from RunAllTests. Since this function can be
6444
// called more than once, it has to be idempotent.
6445
void UnitTestImpl::PostFlagParsingInit() {
6446
// Ensures that this function does not execute more than once.
6447
if (!post_flag_parse_init_performed_) {
6448
post_flag_parse_init_performed_ = true;
6449
6450
#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
6451
// Register to send notifications about key process state changes.
6452
listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
6453
#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
6454
6455
#if GTEST_HAS_DEATH_TEST
6456
InitDeathTestSubprocessControlInfo();
6457
SuppressTestEventsIfInSubprocess();
6458
#endif // GTEST_HAS_DEATH_TEST
6459
6460
// Registers parameterized tests. This makes parameterized tests
6461
// available to the UnitTest reflection API without running
6462
// RUN_ALL_TESTS.
6463
RegisterParameterizedTests();
6464
6465
// Configures listeners for XML output. This makes it possible for users
6466
// to shut down the default XML output before invoking RUN_ALL_TESTS.
6467
ConfigureXmlOutput();
6468
6469
#if GTEST_CAN_STREAM_RESULTS_
6470
// Configures listeners for streaming test results to the specified server.
6471
ConfigureStreamingOutput();
6472
#endif // GTEST_CAN_STREAM_RESULTS_
6473
6474
#if GTEST_HAS_ABSL
6475
if (GTEST_FLAG(install_failure_signal_handler)) {
6476
absl::FailureSignalHandlerOptions options;
6477
absl::InstallFailureSignalHandler(options);
6478
}
6479
#endif // GTEST_HAS_ABSL
6480
}
6481
}
6482
6483
// A predicate that checks the name of a TestCase against a known
6484
// value.
6485
//
6486
// This is used for implementation of the UnitTest class only. We put
6487
// it in the anonymous namespace to prevent polluting the outer
6488
// namespace.
6489
//
6490
// TestCaseNameIs is copyable.
6491
class TestCaseNameIs {
6492
public:
6493
// Constructor.
6494
explicit TestCaseNameIs(const std::string& name)
6495
: name_(name) {}
6496
6497
// Returns true iff the name of test_case matches name_.
6498
bool operator()(const TestCase* test_case) const {
6499
return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
6500
}
6501
6502
private:
6503
std::string name_;
6504
};
6505
6506
// Finds and returns a TestCase with the given name. If one doesn't
6507
// exist, creates one and returns it. It's the CALLER'S
6508
// RESPONSIBILITY to ensure that this function is only called WHEN THE
6509
// TESTS ARE NOT SHUFFLED.
6510
//
6511
// Arguments:
6512
//
6513
// test_case_name: name of the test case
6514
// type_param: the name of the test case's type parameter, or NULL if
6515
// this is not a typed or a type-parameterized test case.
6516
// set_up_tc: pointer to the function that sets up the test case
6517
// tear_down_tc: pointer to the function that tears down the test case
6518
TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
6519
const char* type_param,
6520
Test::SetUpTestCaseFunc set_up_tc,
6521
Test::TearDownTestCaseFunc tear_down_tc) {
6522
// Can we find a TestCase with the given name?
6523
const std::vector<TestCase*>::const_reverse_iterator test_case =
6524
std::find_if(test_cases_.rbegin(), test_cases_.rend(),
6525
TestCaseNameIs(test_case_name));
6526
6527
if (test_case != test_cases_.rend())
6528
return *test_case;
6529
6530
// No. Let's create one.
6531
TestCase* const new_test_case =
6532
new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
6533
6534
// Is this a death test case?
6535
if (internal::UnitTestOptions::MatchesFilter(test_case_name,
6536
kDeathTestCaseFilter)) {
6537
// Yes. Inserts the test case after the last death test case
6538
// defined so far. This only works when the test cases haven't
6539
// been shuffled. Otherwise we may end up running a death test
6540
// after a non-death test.
6541
++last_death_test_case_;
6542
test_cases_.insert(test_cases_.begin() + last_death_test_case_,
6543
new_test_case);
6544
} else {
6545
// No. Appends to the end of the list.
6546
test_cases_.push_back(new_test_case);
6547
}
6548
6549
test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
6550
return new_test_case;
6551
}
6552
6553
// Helpers for setting up / tearing down the given environment. They
6554
// are for use in the ForEach() function.
6555
static void SetUpEnvironment(Environment* env) { env->SetUp(); }
6556
static void TearDownEnvironment(Environment* env) { env->TearDown(); }
6557
6558
// Runs all tests in this UnitTest object, prints the result, and
6559
// returns true if all tests are successful. If any exception is
6560
// thrown during a test, the test is considered to be failed, but the
6561
// rest of the tests will still be run.
6562
//
6563
// When parameterized tests are enabled, it expands and registers
6564
// parameterized tests first in RegisterParameterizedTests().
6565
// All other functions called from RunAllTests() may safely assume that
6566
// parameterized tests are ready to be counted and run.
6567
bool UnitTestImpl::RunAllTests() {
6568
// True iff Google Test is initialized before RUN_ALL_TESTS() is called.
6569
const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
6570
6571
// Do not run any test if the --help flag was specified.
6572
if (g_help_flag)
6573
return true;
6574
6575
// Repeats the call to the post-flag parsing initialization in case the
6576
// user didn't call InitGoogleTest.
6577
PostFlagParsingInit();
6578
6579
// Even if sharding is not on, test runners may want to use the
6580
// GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
6581
// protocol.
6582
internal::WriteToShardStatusFileIfNeeded();
6583
6584
// True iff we are in a subprocess for running a thread-safe-style
6585
// death test.
6586
bool in_subprocess_for_death_test = false;
6587
6588
#if GTEST_HAS_DEATH_TEST
6589
in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
6590
# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6591
if (in_subprocess_for_death_test) {
6592
GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
6593
}
6594
# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6595
#endif // GTEST_HAS_DEATH_TEST
6596
6597
const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
6598
in_subprocess_for_death_test);
6599
6600
// Compares the full test names with the filter to decide which
6601
// tests to run.
6602
const bool has_tests_to_run = FilterTests(should_shard
6603
? HONOR_SHARDING_PROTOCOL
6604
: IGNORE_SHARDING_PROTOCOL) > 0;
6605
6606
// Lists the tests and exits if the --gtest_list_tests flag was specified.
6607
if (GTEST_FLAG(list_tests)) {
6608
// This must be called *after* FilterTests() has been called.
6609
ListTestsMatchingFilter();
6610
return true;
6611
}
6612
6613
random_seed_ = GTEST_FLAG(shuffle) ?
6614
GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
6615
6616
// True iff at least one test has failed.
6617
bool failed = false;
6618
6619
TestEventListener* repeater = listeners()->repeater();
6620
6621
start_timestamp_ = GetTimeInMillis();
6622
repeater->OnTestProgramStart(*parent_);
6623
6624
// How many times to repeat the tests? We don't want to repeat them
6625
// when we are inside the subprocess of a death test.
6626
const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
6627
// Repeats forever if the repeat count is negative.
6628
const bool forever = repeat < 0;
6629
for (int i = 0; forever || i != repeat; i++) {
6630
// We want to preserve failures generated by ad-hoc test
6631
// assertions executed before RUN_ALL_TESTS().
6632
ClearNonAdHocTestResult();
6633
6634
const TimeInMillis start = GetTimeInMillis();
6635
6636
// Shuffles test cases and tests if requested.
6637
if (has_tests_to_run && GTEST_FLAG(shuffle)) {
6638
random()->Reseed(random_seed_);
6639
// This should be done before calling OnTestIterationStart(),
6640
// such that a test event listener can see the actual test order
6641
// in the event.
6642
ShuffleTests();
6643
}
6644
6645
// Tells the unit test event listeners that the tests are about to start.
6646
repeater->OnTestIterationStart(*parent_, i);
6647
6648
// Runs each test case if there is at least one test to run.
6649
if (has_tests_to_run) {
6650
// Sets up all environments beforehand.
6651
repeater->OnEnvironmentsSetUpStart(*parent_);
6652
ForEach(environments_, SetUpEnvironment);
6653
repeater->OnEnvironmentsSetUpEnd(*parent_);
6654
6655
// Runs the tests only if there was no fatal failure during global
6656
// set-up.
6657
if (!Test::HasFatalFailure()) {
6658
for (int test_index = 0; test_index < total_test_case_count();
6659
test_index++) {
6660
GetMutableTestCase(test_index)->Run();
6661
}
6662
}
6663
6664
// Tears down all environments in reverse order afterwards.
6665
repeater->OnEnvironmentsTearDownStart(*parent_);
6666
std::for_each(environments_.rbegin(), environments_.rend(),
6667
TearDownEnvironment);
6668
repeater->OnEnvironmentsTearDownEnd(*parent_);
6669
}
6670
6671
elapsed_time_ = GetTimeInMillis() - start;
6672
6673
// Tells the unit test event listener that the tests have just finished.
6674
repeater->OnTestIterationEnd(*parent_, i);
6675
6676
// Gets the result and clears it.
6677
if (!Passed()) {
6678
failed = true;
6679
}
6680
6681
// Restores the original test order after the iteration. This
6682
// allows the user to quickly repro a failure that happens in the
6683
// N-th iteration without repeating the first (N - 1) iterations.
6684
// This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
6685
// case the user somehow changes the value of the flag somewhere
6686
// (it's always safe to unshuffle the tests).
6687
UnshuffleTests();
6688
6689
if (GTEST_FLAG(shuffle)) {
6690
// Picks a new random seed for each iteration.
6691
random_seed_ = GetNextRandomSeed(random_seed_);
6692
}
6693
}
6694
6695
repeater->OnTestProgramEnd(*parent_);
6696
6697
if (!gtest_is_initialized_before_run_all_tests) {
6698
ColoredPrintf(
6699
COLOR_RED,
6700
"\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
6701
"This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
6702
"() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
6703
" will start to enforce the valid usage. "
6704
"Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
6705
#if GTEST_FOR_GOOGLE_
6706
ColoredPrintf(COLOR_RED,
6707
"For more details, see http://wiki/Main/ValidGUnitMain.\n");
6708
#endif // GTEST_FOR_GOOGLE_
6709
}
6710
6711
return !failed;
6712
}
6713
6714
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
6715
// if the variable is present. If a file already exists at this location, this
6716
// function will write over it. If the variable is present, but the file cannot
6717
// be created, prints an error and exits.
6718
void WriteToShardStatusFileIfNeeded() {
6719
const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
6720
if (test_shard_file != NULL) {
6721
FILE* const file = posix::FOpen(test_shard_file, "w");
6722
if (file == NULL) {
6723
ColoredPrintf(COLOR_RED,
6724
"Could not write to the test shard status file \"%s\" "
6725
"specified by the %s environment variable.\n",
6726
test_shard_file, kTestShardStatusFile);
6727
fflush(stdout);
6728
exit(EXIT_FAILURE);
6729
}
6730
fclose(file);
6731
}
6732
}
6733
6734
// Checks whether sharding is enabled by examining the relevant
6735
// environment variable values. If the variables are present,
6736
// but inconsistent (i.e., shard_index >= total_shards), prints
6737
// an error and exits. If in_subprocess_for_death_test, sharding is
6738
// disabled because it must only be applied to the original test
6739
// process. Otherwise, we could filter out death tests we intended to execute.
6740
bool ShouldShard(const char* total_shards_env,
6741
const char* shard_index_env,
6742
bool in_subprocess_for_death_test) {
6743
if (in_subprocess_for_death_test) {
6744
return false;
6745
}
6746
6747
const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
6748
const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
6749
6750
if (total_shards == -1 && shard_index == -1) {
6751
return false;
6752
} else if (total_shards == -1 && shard_index != -1) {
6753
const Message msg = Message()
6754
<< "Invalid environment variables: you have "
6755
<< kTestShardIndex << " = " << shard_index
6756
<< ", but have left " << kTestTotalShards << " unset.\n";
6757
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6758
fflush(stdout);
6759
exit(EXIT_FAILURE);
6760
} else if (total_shards != -1 && shard_index == -1) {
6761
const Message msg = Message()
6762
<< "Invalid environment variables: you have "
6763
<< kTestTotalShards << " = " << total_shards
6764
<< ", but have left " << kTestShardIndex << " unset.\n";
6765
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6766
fflush(stdout);
6767
exit(EXIT_FAILURE);
6768
} else if (shard_index < 0 || shard_index >= total_shards) {
6769
const Message msg = Message()
6770
<< "Invalid environment variables: we require 0 <= "
6771
<< kTestShardIndex << " < " << kTestTotalShards
6772
<< ", but you have " << kTestShardIndex << "=" << shard_index
6773
<< ", " << kTestTotalShards << "=" << total_shards << ".\n";
6774
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6775
fflush(stdout);
6776
exit(EXIT_FAILURE);
6777
}
6778
6779
return total_shards > 1;
6780
}
6781
6782
// Parses the environment variable var as an Int32. If it is unset,
6783
// returns default_val. If it is not an Int32, prints an error
6784
// and aborts.
6785
Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
6786
const char* str_val = posix::GetEnv(var);
6787
if (str_val == NULL) {
6788
return default_val;
6789
}
6790
6791
Int32 result;
6792
if (!ParseInt32(Message() << "The value of environment variable " << var,
6793
str_val, &result)) {
6794
exit(EXIT_FAILURE);
6795
}
6796
return result;
6797
}
6798
6799
// Given the total number of shards, the shard index, and the test id,
6800
// returns true iff the test should be run on this shard. The test id is
6801
// some arbitrary but unique non-negative integer assigned to each test
6802
// method. Assumes that 0 <= shard_index < total_shards.
6803
bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
6804
return (test_id % total_shards) == shard_index;
6805
}
6806
6807
// Compares the name of each test with the user-specified filter to
6808
// decide whether the test should be run, then records the result in
6809
// each TestCase and TestInfo object.
6810
// If shard_tests == true, further filters tests based on sharding
6811
// variables in the environment - see
6812
// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
6813
// . Returns the number of tests that should run.
6814
int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6815
const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
6816
Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
6817
const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
6818
Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
6819
6820
// num_runnable_tests are the number of tests that will
6821
// run across all shards (i.e., match filter and are not disabled).
6822
// num_selected_tests are the number of tests to be run on
6823
// this shard.
6824
int num_runnable_tests = 0;
6825
int num_selected_tests = 0;
6826
for (size_t i = 0; i < test_cases_.size(); i++) {
6827
TestCase* const test_case = test_cases_[i];
6828
const std::string &test_case_name = test_case->name();
6829
test_case->set_should_run(false);
6830
6831
for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6832
TestInfo* const test_info = test_case->test_info_list()[j];
6833
const std::string test_name(test_info->name());
6834
// A test is disabled if test case name or test name matches
6835
// kDisableTestFilter.
6836
const bool is_disabled =
6837
internal::UnitTestOptions::MatchesFilter(test_case_name,
6838
kDisableTestFilter) ||
6839
internal::UnitTestOptions::MatchesFilter(test_name,
6840
kDisableTestFilter);
6841
test_info->is_disabled_ = is_disabled;
6842
6843
const std::string value_param(test_info->value_param() == NULL ?
6844
"" : test_info->value_param());
6845
6846
const bool matches_filter =
6847
internal::UnitTestOptions::FilterMatchesTest(test_case_name,
6848
test_name) &&
6849
internal::UnitTestOptions::MatchesFilter(value_param,
6850
GTEST_FLAG(param_filter).c_str());
6851
6852
test_info->matches_filter_ = matches_filter;
6853
6854
const bool is_runnable =
6855
(GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
6856
matches_filter;
6857
6858
const bool is_in_another_shard =
6859
shard_tests != IGNORE_SHARDING_PROTOCOL &&
6860
!ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
6861
test_info->is_in_another_shard_ = is_in_another_shard;
6862
const bool is_selected = is_runnable && !is_in_another_shard;
6863
6864
num_runnable_tests += is_runnable;
6865
num_selected_tests += is_selected;
6866
6867
test_info->should_run_ = is_selected;
6868
test_case->set_should_run(test_case->should_run() || is_selected);
6869
}
6870
}
6871
return num_selected_tests;
6872
}
6873
6874
// Prints the given C-string on a single line by replacing all '\n'
6875
// characters with string "\\n". If the output takes more than
6876
// max_length characters, only prints the first max_length characters
6877
// and "...".
6878
static void PrintOnOneLine(const char* str, int max_length) {
6879
if (str != NULL) {
6880
for (int i = 0; *str != '\0'; ++str) {
6881
if (i >= max_length) {
6882
printf("...");
6883
break;
6884
}
6885
if (*str == '\n') {
6886
printf("\\n");
6887
i += 2;
6888
} else {
6889
printf("%c", *str);
6890
++i;
6891
}
6892
}
6893
}
6894
}
6895
6896
// Prints the names of the tests matching the user-specified filter flag.
6897
void UnitTestImpl::ListTestsMatchingFilter() {
6898
// Print at most this many characters for each type/value parameter.
6899
const int kMaxParamLength = 250;
6900
6901
for (size_t i = 0; i < test_cases_.size(); i++) {
6902
const TestCase* const test_case = test_cases_[i];
6903
bool printed_test_case_name = false;
6904
6905
for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6906
const TestInfo* const test_info =
6907
test_case->test_info_list()[j];
6908
if (test_info->matches_filter_) {
6909
if (!printed_test_case_name) {
6910
printed_test_case_name = true;
6911
printf("%s.", test_case->name());
6912
if (test_case->type_param() != NULL) {
6913
printf(" # %s = ", kTypeParamLabel);
6914
// We print the type parameter on a single line to make
6915
// the output easy to parse by a program.
6916
PrintOnOneLine(test_case->type_param(), kMaxParamLength);
6917
}
6918
printf("\n");
6919
}
6920
printf(" %s", test_info->name());
6921
if (test_info->value_param() != NULL) {
6922
printf(" # %s = ", kValueParamLabel);
6923
// We print the value parameter on a single line to make the
6924
// output easy to parse by a program.
6925
PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6926
}
6927
printf("\n");
6928
}
6929
}
6930
}
6931
fflush(stdout);
6932
const std::string& output_format = UnitTestOptions::GetOutputFormat();
6933
if (output_format == "xml" || output_format == "json") {
6934
FILE* fileout = OpenFileForWriting(
6935
UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
6936
std::stringstream stream;
6937
if (output_format == "xml") {
6938
XmlUnitTestResultPrinter(
6939
UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6940
.PrintXmlTestsList(&stream, test_cases_);
6941
} else if (output_format == "json") {
6942
JsonUnitTestResultPrinter(
6943
UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6944
.PrintJsonTestList(&stream, test_cases_);
6945
}
6946
fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
6947
fclose(fileout);
6948
}
6949
}
6950
6951
// Sets the OS stack trace getter.
6952
//
6953
// Does nothing if the input and the current OS stack trace getter are
6954
// the same; otherwise, deletes the old getter and makes the input the
6955
// current getter.
6956
void UnitTestImpl::set_os_stack_trace_getter(
6957
OsStackTraceGetterInterface* getter) {
6958
if (os_stack_trace_getter_ != getter) {
6959
delete os_stack_trace_getter_;
6960
os_stack_trace_getter_ = getter;
6961
}
6962
}
6963
6964
// Returns the current OS stack trace getter if it is not NULL;
6965
// otherwise, creates an OsStackTraceGetter, makes it the current
6966
// getter, and returns it.
6967
OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
6968
if (os_stack_trace_getter_ == NULL) {
6969
#ifdef GTEST_OS_STACK_TRACE_GETTER_
6970
os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
6971
#else
6972
os_stack_trace_getter_ = new OsStackTraceGetter;
6973
#endif // GTEST_OS_STACK_TRACE_GETTER_
6974
}
6975
6976
return os_stack_trace_getter_;
6977
}
6978
6979
// Returns the most specific TestResult currently running.
6980
TestResult* UnitTestImpl::current_test_result() {
6981
if (current_test_info_ != NULL) {
6982
return &current_test_info_->result_;
6983
}
6984
if (current_test_case_ != NULL) {
6985
return &current_test_case_->ad_hoc_test_result_;
6986
}
6987
return &ad_hoc_test_result_;
6988
}
6989
6990
// Shuffles all test cases, and the tests within each test case,
6991
// making sure that death tests are still run first.
6992
void UnitTestImpl::ShuffleTests() {
6993
// Shuffles the death test cases.
6994
ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
6995
6996
// Shuffles the non-death test cases.
6997
ShuffleRange(random(), last_death_test_case_ + 1,
6998
static_cast<int>(test_cases_.size()), &test_case_indices_);
6999
7000
// Shuffles the tests inside each test case.
7001
for (size_t i = 0; i < test_cases_.size(); i++) {
7002
test_cases_[i]->ShuffleTests(random());
7003
}
7004
}
7005
7006
// Restores the test cases and tests to their order before the first shuffle.
7007
void UnitTestImpl::UnshuffleTests() {
7008
for (size_t i = 0; i < test_cases_.size(); i++) {
7009
// Unshuffles the tests in each test case.
7010
test_cases_[i]->UnshuffleTests();
7011
// Resets the index of each test case.
7012
test_case_indices_[i] = static_cast<int>(i);
7013
}
7014
}
7015
7016
// Returns the current OS stack trace as an std::string.
7017
//
7018
// The maximum number of stack frames to be included is specified by
7019
// the gtest_stack_trace_depth flag. The skip_count parameter
7020
// specifies the number of top frames to be skipped, which doesn't
7021
// count against the number of frames to be included.
7022
//
7023
// For example, if Foo() calls Bar(), which in turn calls
7024
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
7025
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
7026
std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
7027
int skip_count) {
7028
// We pass skip_count + 1 to skip this wrapper function in addition
7029
// to what the user really wants to skip.
7030
return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
7031
}
7032
7033
// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
7034
// suppress unreachable code warnings.
7035
namespace {
7036
class ClassUniqueToAlwaysTrue {};
7037
}
7038
7039
bool IsTrue(bool condition) { return condition; }
7040
7041
bool AlwaysTrue() {
7042
#if GTEST_HAS_EXCEPTIONS
7043
// This condition is always false so AlwaysTrue() never actually throws,
7044
// but it makes the compiler think that it may throw.
7045
if (IsTrue(false))
7046
throw ClassUniqueToAlwaysTrue();
7047
#endif // GTEST_HAS_EXCEPTIONS
7048
return true;
7049
}
7050
7051
// If *pstr starts with the given prefix, modifies *pstr to be right
7052
// past the prefix and returns true; otherwise leaves *pstr unchanged
7053
// and returns false. None of pstr, *pstr, and prefix can be NULL.
7054
bool SkipPrefix(const char* prefix, const char** pstr) {
7055
const size_t prefix_len = strlen(prefix);
7056
if (strncmp(*pstr, prefix, prefix_len) == 0) {
7057
*pstr += prefix_len;
7058
return true;
7059
}
7060
return false;
7061
}
7062
7063
// Parses a string as a command line flag. The string should have
7064
// the format "--flag=value". When def_optional is true, the "=value"
7065
// part can be omitted.
7066
//
7067
// Returns the value of the flag, or NULL if the parsing failed.
7068
static const char* ParseFlagValue(const char* str, const char* flag,
7069
bool def_optional) {
7070
// str and flag must not be NULL.
7071
if (str == NULL || flag == NULL) return NULL;
7072
7073
// The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
7074
const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
7075
const size_t flag_len = flag_str.length();
7076
if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
7077
7078
// Skips the flag name.
7079
const char* flag_end = str + flag_len;
7080
7081
// When def_optional is true, it's OK to not have a "=value" part.
7082
if (def_optional && (flag_end[0] == '\0')) {
7083
return flag_end;
7084
}
7085
7086
// If def_optional is true and there are more characters after the
7087
// flag name, or if def_optional is false, there must be a '=' after
7088
// the flag name.
7089
if (flag_end[0] != '=') return NULL;
7090
7091
// Returns the string after "=".
7092
return flag_end + 1;
7093
}
7094
7095
// Parses a string for a bool flag, in the form of either
7096
// "--flag=value" or "--flag".
7097
//
7098
// In the former case, the value is taken as true as long as it does
7099
// not start with '0', 'f', or 'F'.
7100
//
7101
// In the latter case, the value is taken as true.
7102
//
7103
// On success, stores the value of the flag in *value, and returns
7104
// true. On failure, returns false without changing *value.
7105
static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
7106
// Gets the value of the flag as a string.
7107
const char* const value_str = ParseFlagValue(str, flag, true);
7108
7109
// Aborts if the parsing failed.
7110
if (value_str == NULL) return false;
7111
7112
// Converts the string value to a bool.
7113
*value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
7114
return true;
7115
}
7116
7117
// Parses a string for an Int32 flag, in the form of
7118
// "--flag=value".
7119
//
7120
// On success, stores the value of the flag in *value, and returns
7121
// true. On failure, returns false without changing *value.
7122
bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
7123
// Gets the value of the flag as a string.
7124
const char* const value_str = ParseFlagValue(str, flag, false);
7125
7126
// Aborts if the parsing failed.
7127
if (value_str == NULL) return false;
7128
7129
// Sets *value to the value of the flag.
7130
return ParseInt32(Message() << "The value of flag --" << flag,
7131
value_str, value);
7132
}
7133
7134
// Parses a string for a string flag, in the form of
7135
// "--flag=value".
7136
//
7137
// On success, stores the value of the flag in *value, and returns
7138
// true. On failure, returns false without changing *value.
7139
template <typename String>
7140
static bool ParseStringFlag(const char* str, const char* flag, String* value) {
7141
// Gets the value of the flag as a string.
7142
const char* const value_str = ParseFlagValue(str, flag, false);
7143
7144
// Aborts if the parsing failed.
7145
if (value_str == NULL) return false;
7146
7147
// Sets *value to the value of the flag.
7148
*value = value_str;
7149
return true;
7150
}
7151
7152
// Determines whether a string has a prefix that Google Test uses for its
7153
// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
7154
// If Google Test detects that a command line flag has its prefix but is not
7155
// recognized, it will print its help message. Flags starting with
7156
// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
7157
// internal flags and do not trigger the help message.
7158
static bool HasGoogleTestFlagPrefix(const char* str) {
7159
return (SkipPrefix("--", &str) ||
7160
SkipPrefix("-", &str) ||
7161
SkipPrefix("/", &str)) &&
7162
!SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
7163
(SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
7164
SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
7165
}
7166
7167
// Prints a string containing code-encoded text. The following escape
7168
// sequences can be used in the string to control the text color:
7169
//
7170
// @@ prints a single '@' character.
7171
// @R changes the color to red.
7172
// @G changes the color to green.
7173
// @Y changes the color to yellow.
7174
// @D changes to the default terminal text color.
7175
//
7176
// FIXME: Write tests for this once we add stdout
7177
// capturing to Google Test.
7178
static void PrintColorEncoded(const char* str) {
7179
GTestColor color = COLOR_DEFAULT; // The current color.
7180
7181
// Conceptually, we split the string into segments divided by escape
7182
// sequences. Then we print one segment at a time. At the end of
7183
// each iteration, the str pointer advances to the beginning of the
7184
// next segment.
7185
for (;;) {
7186
const char* p = strchr(str, '@');
7187
if (p == NULL) {
7188
ColoredPrintf(color, "%s", str);
7189
return;
7190
}
7191
7192
ColoredPrintf(color, "%s", std::string(str, p).c_str());
7193
7194
const char ch = p[1];
7195
str = p + 2;
7196
if (ch == '@') {
7197
ColoredPrintf(color, "@");
7198
} else if (ch == 'D') {
7199
color = COLOR_DEFAULT;
7200
} else if (ch == 'R') {
7201
color = COLOR_RED;
7202
} else if (ch == 'G') {
7203
color = COLOR_GREEN;
7204
} else if (ch == 'Y') {
7205
color = COLOR_YELLOW;
7206
} else {
7207
--str;
7208
}
7209
}
7210
}
7211
7212
static const char kColorEncodedHelpMessage[] =
7213
"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
7214
"following command line flags to control its behavior:\n"
7215
"\n"
7216
"Test Selection:\n"
7217
" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
7218
" List the names of all tests instead of running them. The name of\n"
7219
" TEST(Foo, Bar) is \"Foo.Bar\".\n"
7220
" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
7221
"[@G-@YNEGATIVE_PATTERNS]@D\n"
7222
" Run only the tests whose name matches one of the positive patterns but\n"
7223
" none of the negative patterns. '?' matches any single character; '*'\n"
7224
" matches any substring; ':' separates two patterns.\n"
7225
" @G--" GTEST_FLAG_PREFIX_ "param_filter=@YPOSITIVE_PATTERNS"
7226
"[@G-@YNEGATIVE_PATTERNS]@D\n"
7227
" Like @G--" GTEST_FLAG_PREFIX_
7228
"filter@D, but applies to the test's parameter. If a\n"
7229
" test is not parameterized, its parameter is considered to be the\n"
7230
" empty string.\n"
7231
" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
7232
" Run all disabled tests too.\n"
7233
"\n"
7234
"Test Execution:\n"
7235
" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
7236
" Run the tests repeatedly; use a negative count to repeat forever.\n"
7237
" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
7238
" Randomize tests' orders on every iteration.\n"
7239
" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
7240
" Random number seed to use for shuffling test orders (between 1 and\n"
7241
" 99999, or 0 to use a seed based on the current time).\n"
7242
"\n"
7243
"Test Output:\n"
7244
" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
7245
" Enable/disable colored output. The default is @Gauto@D.\n"
7246
" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
7247
" Don't print the elapsed time of each test.\n"
7248
" @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
7249
GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
7250
" Generate a JSON or XML report in the given directory or with the given\n"
7251
" file name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
7252
# if GTEST_CAN_STREAM_RESULTS_
7253
" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
7254
" Stream test results to the given server.\n"
7255
# endif // GTEST_CAN_STREAM_RESULTS_
7256
"\n"
7257
"Assertion Behavior:\n"
7258
# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7259
" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
7260
" Set the default death test style.\n"
7261
# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7262
" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
7263
" Turn assertion failures into debugger break-points.\n"
7264
" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
7265
" Turn assertion failures into C++ exceptions for use by an external\n"
7266
" test framework.\n"
7267
" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
7268
" Do not report exceptions as test failures. Instead, allow them\n"
7269
" to crash the program or throw a pop-up (on Windows).\n"
7270
"\n"
7271
"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
7272
"the corresponding\n"
7273
"environment variable of a flag (all letters in upper-case). For example, to\n"
7274
"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
7275
"color=no@D or set\n"
7276
"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
7277
"\n"
7278
"For more information, please read the " GTEST_NAME_ " documentation at\n"
7279
"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
7280
"(not one in your own code or tests), please report it to\n"
7281
"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
7282
7283
static bool ParseGoogleTestFlag(const char* const arg) {
7284
return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
7285
&GTEST_FLAG(also_run_disabled_tests)) ||
7286
ParseBoolFlag(arg, kBreakOnFailureFlag,
7287
&GTEST_FLAG(break_on_failure)) ||
7288
ParseBoolFlag(arg, kCatchExceptionsFlag,
7289
&GTEST_FLAG(catch_exceptions)) ||
7290
ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
7291
ParseStringFlag(arg, kDeathTestStyleFlag,
7292
&GTEST_FLAG(death_test_style)) ||
7293
ParseBoolFlag(arg, kDeathTestUseFork,
7294
&GTEST_FLAG(death_test_use_fork)) ||
7295
ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
7296
ParseStringFlag(arg, kParamFilterFlag, &GTEST_FLAG(param_filter)) ||
7297
ParseStringFlag(arg, kInternalRunDeathTestFlag,
7298
&GTEST_FLAG(internal_run_death_test)) ||
7299
ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
7300
ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
7301
ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
7302
ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
7303
ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
7304
ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
7305
ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
7306
ParseInt32Flag(arg, kStackTraceDepthFlag,
7307
&GTEST_FLAG(stack_trace_depth)) ||
7308
ParseStringFlag(arg, kStreamResultToFlag,
7309
&GTEST_FLAG(stream_result_to)) ||
7310
ParseBoolFlag(arg, kThrowOnFailureFlag,
7311
&GTEST_FLAG(throw_on_failure));
7312
}
7313
7314
#if GTEST_USE_OWN_FLAGFILE_FLAG_
7315
static void LoadFlagsFromFile(const std::string& path) {
7316
FILE* flagfile = posix::FOpen(path.c_str(), "r");
7317
if (!flagfile) {
7318
GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
7319
<< "\"";
7320
}
7321
std::string contents(ReadEntireFile(flagfile));
7322
posix::FClose(flagfile);
7323
std::vector<std::string> lines;
7324
SplitString(contents, '\n', &lines);
7325
for (size_t i = 0; i < lines.size(); ++i) {
7326
if (lines[i].empty())
7327
continue;
7328
if (!ParseGoogleTestFlag(lines[i].c_str()))
7329
g_help_flag = true;
7330
}
7331
}
7332
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
7333
7334
// Parses the command line for Google Test flags, without initializing
7335
// other parts of Google Test. The type parameter CharType can be
7336
// instantiated to either char or wchar_t.
7337
template <typename CharType>
7338
void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
7339
for (int i = 1; i < *argc; i++) {
7340
const std::string arg_string = StreamableToString(argv[i]);
7341
const char* const arg = arg_string.c_str();
7342
7343
using internal::ParseBoolFlag;
7344
using internal::ParseInt32Flag;
7345
using internal::ParseStringFlag;
7346
7347
bool remove_flag = false;
7348
if (ParseGoogleTestFlag(arg)) {
7349
remove_flag = true;
7350
#if GTEST_USE_OWN_FLAGFILE_FLAG_
7351
} else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
7352
LoadFlagsFromFile(GTEST_FLAG(flagfile));
7353
remove_flag = true;
7354
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
7355
} else if (arg_string == "--help" || arg_string == "-h" ||
7356
arg_string == "-?" || arg_string == "/?" ||
7357
HasGoogleTestFlagPrefix(arg)) {
7358
// Both help flag and unrecognized Google Test flags (excluding
7359
// internal ones) trigger help display.
7360
g_help_flag = true;
7361
}
7362
7363
if (remove_flag) {
7364
// Shift the remainder of the argv list left by one. Note
7365
// that argv has (*argc + 1) elements, the last one always being
7366
// NULL. The following loop moves the trailing NULL element as
7367
// well.
7368
for (int j = i; j != *argc; j++) {
7369
argv[j] = argv[j + 1];
7370
}
7371
7372
// Decrements the argument count.
7373
(*argc)--;
7374
7375
// We also need to decrement the iterator as we just removed
7376
// an element.
7377
i--;
7378
}
7379
}
7380
7381
if (g_help_flag) {
7382
// We print the help here instead of in RUN_ALL_TESTS(), as the
7383
// latter may not be called at all if the user is using Google
7384
// Test with another testing framework.
7385
PrintColorEncoded(kColorEncodedHelpMessage);
7386
}
7387
}
7388
7389
// Parses the command line for Google Test flags, without initializing
7390
// other parts of Google Test.
7391
void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
7392
ParseGoogleTestFlagsOnlyImpl(argc, argv);
7393
7394
// Fix the value of *_NSGetArgc() on macOS, but iff
7395
// *_NSGetArgv() == argv
7396
// Only applicable to char** version of argv
7397
#if GTEST_OS_MAC
7398
#ifndef GTEST_OS_IOS
7399
if (*_NSGetArgv() == argv) {
7400
*_NSGetArgc() = *argc;
7401
}
7402
#endif
7403
#endif
7404
}
7405
void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
7406
ParseGoogleTestFlagsOnlyImpl(argc, argv);
7407
}
7408
7409
// The internal implementation of InitGoogleTest().
7410
//
7411
// The type parameter CharType can be instantiated to either char or
7412
// wchar_t.
7413
template <typename CharType>
7414
void InitGoogleTestImpl(int* argc, CharType** argv) {
7415
// We don't want to run the initialization code twice.
7416
if (GTestIsInitialized()) return;
7417
7418
if (*argc <= 0) return;
7419
7420
g_argvs.clear();
7421
for (int i = 0; i != *argc; i++) {
7422
g_argvs.push_back(StreamableToString(argv[i]));
7423
}
7424
7425
#if GTEST_HAS_ABSL
7426
absl::InitializeSymbolizer(g_argvs[0].c_str());
7427
#endif // GTEST_HAS_ABSL
7428
7429
ParseGoogleTestFlagsOnly(argc, argv);
7430
GetUnitTestImpl()->PostFlagParsingInit();
7431
}
7432
7433
} // namespace internal
7434
7435
// Initializes Google Test. This must be called before calling
7436
// RUN_ALL_TESTS(). In particular, it parses a command line for the
7437
// flags that Google Test recognizes. Whenever a Google Test flag is
7438
// seen, it is removed from argv, and *argc is decremented.
7439
//
7440
// No value is returned. Instead, the Google Test flag variables are
7441
// updated.
7442
//
7443
// Calling the function for the second time has no user-visible effect.
7444
void InitGoogleTest(int* argc, char** argv) {
7445
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7446
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7447
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7448
internal::InitGoogleTestImpl(argc, argv);
7449
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7450
}
7451
7452
// This overloaded version can be used in Windows programs compiled in
7453
// UNICODE mode.
7454
void InitGoogleTest(int* argc, wchar_t** argv) {
7455
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7456
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7457
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7458
internal::InitGoogleTestImpl(argc, argv);
7459
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7460
}
7461
7462
std::string TempDir() {
7463
#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
7464
return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
7465
#endif
7466
7467
#if GTEST_OS_WINDOWS_MOBILE
7468
return "\\temp\\";
7469
#elif GTEST_OS_WINDOWS
7470
const char* temp_dir = internal::posix::GetEnv("TEMP");
7471
if (temp_dir == NULL || temp_dir[0] == '\0')
7472
return "\\temp\\";
7473
else if (temp_dir[strlen(temp_dir) - 1] == '\\')
7474
return temp_dir;
7475
else
7476
return std::string(temp_dir) + "\\";
7477
#elif GTEST_OS_LINUX_ANDROID
7478
return "/sdcard/";
7479
#else
7480
return "/tmp/";
7481
#endif // GTEST_OS_WINDOWS_MOBILE
7482
}
7483
7484
// Class ScopedTrace
7485
7486
// Pushes the given source file location and message onto a per-thread
7487
// trace stack maintained by Google Test.
7488
void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
7489
internal::TraceInfo trace;
7490
trace.file = file;
7491
trace.line = line;
7492
trace.message.swap(message);
7493
7494
UnitTest::GetInstance()->PushGTestTrace(trace);
7495
}
7496
7497
// Pops the info pushed by the c'tor.
7498
ScopedTrace::~ScopedTrace()
7499
GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
7500
UnitTest::GetInstance()->PopGTestTrace();
7501
}
7502
7503
} // namespace testing
7504
// Copyright 2005, Google Inc.
7505
// All rights reserved.
7506
//
7507
// Redistribution and use in source and binary forms, with or without
7508
// modification, are permitted provided that the following conditions are
7509
// met:
7510
//
7511
// * Redistributions of source code must retain the above copyright
7512
// notice, this list of conditions and the following disclaimer.
7513
// * Redistributions in binary form must reproduce the above
7514
// copyright notice, this list of conditions and the following disclaimer
7515
// in the documentation and/or other materials provided with the
7516
// distribution.
7517
// * Neither the name of Google Inc. nor the names of its
7518
// contributors may be used to endorse or promote products derived from
7519
// this software without specific prior written permission.
7520
//
7521
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7522
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7523
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7524
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7525
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7526
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7527
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7528
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7529
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7530
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7531
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7532
7533
//
7534
// This file implements death tests.
7535
7536
7537
#if GTEST_HAS_DEATH_TEST
7538
7539
# if GTEST_OS_MAC
7540
# include <crt_externs.h>
7541
# endif // GTEST_OS_MAC
7542
7543
# include <errno.h>
7544
# include <fcntl.h>
7545
# include <limits.h>
7546
7547
# if GTEST_OS_LINUX
7548
# include <signal.h>
7549
# endif // GTEST_OS_LINUX
7550
7551
# include <stdarg.h>
7552
7553
# if GTEST_OS_WINDOWS
7554
# include <windows.h>
7555
# else
7556
# include <sys/mman.h>
7557
# include <sys/wait.h>
7558
# endif // GTEST_OS_WINDOWS
7559
7560
# if GTEST_OS_QNX
7561
# include <spawn.h>
7562
# endif // GTEST_OS_QNX
7563
7564
# if GTEST_OS_FUCHSIA
7565
# include <lib/fdio/io.h>
7566
# include <lib/fdio/spawn.h>
7567
# include <zircon/processargs.h>
7568
# include <zircon/syscalls.h>
7569
# include <zircon/syscalls/port.h>
7570
# endif // GTEST_OS_FUCHSIA
7571
7572
#endif // GTEST_HAS_DEATH_TEST
7573
7574
7575
namespace testing {
7576
7577
// Constants.
7578
7579
// The default death test style.
7580
//
7581
// This is defined in internal/gtest-port.h as "fast", but can be overridden by
7582
// a definition in internal/custom/gtest-port.h. The recommended value, which is
7583
// used internally at Google, is "threadsafe".
7584
static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
7585
7586
GTEST_DEFINE_string_(
7587
death_test_style,
7588
internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
7589
"Indicates how to run a death test in a forked child process: "
7590
"\"threadsafe\" (child process re-executes the test binary "
7591
"from the beginning, running only the specific death test) or "
7592
"\"fast\" (child process runs the death test immediately "
7593
"after forking).");
7594
7595
GTEST_DEFINE_bool_(
7596
death_test_use_fork,
7597
internal::BoolFromGTestEnv("death_test_use_fork", false),
7598
"Instructs to use fork()/_exit() instead of clone() in death tests. "
7599
"Ignored and always uses fork() on POSIX systems where clone() is not "
7600
"implemented. Useful when running under valgrind or similar tools if "
7601
"those do not support clone(). Valgrind 3.3.1 will just fail if "
7602
"it sees an unsupported combination of clone() flags. "
7603
"It is not recommended to use this flag w/o valgrind though it will "
7604
"work in 99% of the cases. Once valgrind is fixed, this flag will "
7605
"most likely be removed.");
7606
7607
namespace internal {
7608
GTEST_DEFINE_string_(
7609
internal_run_death_test, "",
7610
"Indicates the file, line number, temporal index of "
7611
"the single death test to run, and a file descriptor to "
7612
"which a success code may be sent, all separated by "
7613
"the '|' characters. This flag is specified if and only if the current "
7614
"process is a sub-process launched for running a thread-safe "
7615
"death test. FOR INTERNAL USE ONLY.");
7616
} // namespace internal
7617
7618
#if GTEST_HAS_DEATH_TEST
7619
7620
namespace internal {
7621
7622
// Valid only for fast death tests. Indicates the code is running in the
7623
// child process of a fast style death test.
7624
# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7625
static bool g_in_fast_death_test_child = false;
7626
# endif
7627
7628
// Returns a Boolean value indicating whether the caller is currently
7629
// executing in the context of the death test child process. Tools such as
7630
// Valgrind heap checkers may need this to modify their behavior in death
7631
// tests. IMPORTANT: This is an internal utility. Using it may break the
7632
// implementation of death tests. User code MUST NOT use it.
7633
bool InDeathTestChild() {
7634
# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7635
7636
// On Windows and Fuchsia, death tests are thread-safe regardless of the value
7637
// of the death_test_style flag.
7638
return !GTEST_FLAG(internal_run_death_test).empty();
7639
7640
# else
7641
7642
if (GTEST_FLAG(death_test_style) == "threadsafe")
7643
return !GTEST_FLAG(internal_run_death_test).empty();
7644
else
7645
return g_in_fast_death_test_child;
7646
#endif
7647
}
7648
7649
} // namespace internal
7650
7651
// ExitedWithCode constructor.
7652
ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
7653
}
7654
7655
// ExitedWithCode function-call operator.
7656
bool ExitedWithCode::operator()(int exit_status) const {
7657
# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7658
7659
return exit_status == exit_code_;
7660
7661
# else
7662
7663
return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
7664
7665
# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7666
}
7667
7668
# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7669
// KilledBySignal constructor.
7670
KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
7671
}
7672
7673
// KilledBySignal function-call operator.
7674
bool KilledBySignal::operator()(int exit_status) const {
7675
# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7676
{
7677
bool result;
7678
if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
7679
return result;
7680
}
7681
}
7682
# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7683
return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
7684
}
7685
# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7686
7687
namespace internal {
7688
7689
// Utilities needed for death tests.
7690
7691
// Generates a textual description of a given exit code, in the format
7692
// specified by wait(2).
7693
static std::string ExitSummary(int exit_code) {
7694
Message m;
7695
7696
# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7697
7698
m << "Exited with exit status " << exit_code;
7699
7700
# else
7701
7702
if (WIFEXITED(exit_code)) {
7703
m << "Exited with exit status " << WEXITSTATUS(exit_code);
7704
} else if (WIFSIGNALED(exit_code)) {
7705
m << "Terminated by signal " << WTERMSIG(exit_code);
7706
}
7707
# ifdef WCOREDUMP
7708
if (WCOREDUMP(exit_code)) {
7709
m << " (core dumped)";
7710
}
7711
# endif
7712
# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7713
7714
return m.GetString();
7715
}
7716
7717
// Returns true if exit_status describes a process that was terminated
7718
// by a signal, or exited normally with a nonzero exit code.
7719
bool ExitedUnsuccessfully(int exit_status) {
7720
return !ExitedWithCode(0)(exit_status);
7721
}
7722
7723
# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7724
// Generates a textual failure message when a death test finds more than
7725
// one thread running, or cannot determine the number of threads, prior
7726
// to executing the given statement. It is the responsibility of the
7727
// caller not to pass a thread_count of 1.
7728
static std::string DeathTestThreadWarning(size_t thread_count) {
7729
Message msg;
7730
msg << "Death tests use fork(), which is unsafe particularly"
7731
<< " in a threaded context. For this test, " << GTEST_NAME_ << " ";
7732
if (thread_count == 0) {
7733
msg << "couldn't detect the number of threads.";
7734
} else {
7735
msg << "detected " << thread_count << " threads.";
7736
}
7737
msg << " See "
7738
"https://github.com/google/googletest/blob/master/googletest/docs/"
7739
"advanced.md#death-tests-and-threads"
7740
<< " for more explanation and suggested solutions, especially if"
7741
<< " this is the last message you see before your test times out.";
7742
return msg.GetString();
7743
}
7744
# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7745
7746
// Flag characters for reporting a death test that did not die.
7747
static const char kDeathTestLived = 'L';
7748
static const char kDeathTestReturned = 'R';
7749
static const char kDeathTestThrew = 'T';
7750
static const char kDeathTestInternalError = 'I';
7751
7752
#if GTEST_OS_FUCHSIA
7753
7754
// File descriptor used for the pipe in the child process.
7755
static const int kFuchsiaReadPipeFd = 3;
7756
7757
#endif
7758
7759
// An enumeration describing all of the possible ways that a death test can
7760
// conclude. DIED means that the process died while executing the test
7761
// code; LIVED means that process lived beyond the end of the test code;
7762
// RETURNED means that the test statement attempted to execute a return
7763
// statement, which is not allowed; THREW means that the test statement
7764
// returned control by throwing an exception. IN_PROGRESS means the test
7765
// has not yet concluded.
7766
// FIXME: Unify names and possibly values for
7767
// AbortReason, DeathTestOutcome, and flag characters above.
7768
enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
7769
7770
// Routine for aborting the program which is safe to call from an
7771
// exec-style death test child process, in which case the error
7772
// message is propagated back to the parent process. Otherwise, the
7773
// message is simply printed to stderr. In either case, the program
7774
// then exits with status 1.
7775
static void DeathTestAbort(const std::string& message) {
7776
// On a POSIX system, this function may be called from a threadsafe-style
7777
// death test child process, which operates on a very small stack. Use
7778
// the heap for any additional non-minuscule memory requirements.
7779
const InternalRunDeathTestFlag* const flag =
7780
GetUnitTestImpl()->internal_run_death_test_flag();
7781
if (flag != NULL) {
7782
FILE* parent = posix::FDOpen(flag->write_fd(), "w");
7783
fputc(kDeathTestInternalError, parent);
7784
fprintf(parent, "%s", message.c_str());
7785
fflush(parent);
7786
_exit(1);
7787
} else {
7788
fprintf(stderr, "%s", message.c_str());
7789
fflush(stderr);
7790
posix::Abort();
7791
}
7792
}
7793
7794
// A replacement for CHECK that calls DeathTestAbort if the assertion
7795
// fails.
7796
# define GTEST_DEATH_TEST_CHECK_(expression) \
7797
do { \
7798
if (!::testing::internal::IsTrue(expression)) { \
7799
DeathTestAbort( \
7800
::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7801
+ ::testing::internal::StreamableToString(__LINE__) + ": " \
7802
+ #expression); \
7803
} \
7804
} while (::testing::internal::AlwaysFalse())
7805
7806
// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
7807
// evaluating any system call that fulfills two conditions: it must return
7808
// -1 on failure, and set errno to EINTR when it is interrupted and
7809
// should be tried again. The macro expands to a loop that repeatedly
7810
// evaluates the expression as long as it evaluates to -1 and sets
7811
// errno to EINTR. If the expression evaluates to -1 but errno is
7812
// something other than EINTR, DeathTestAbort is called.
7813
# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
7814
do { \
7815
int gtest_retval; \
7816
do { \
7817
gtest_retval = (expression); \
7818
} while (gtest_retval == -1 && errno == EINTR); \
7819
if (gtest_retval == -1) { \
7820
DeathTestAbort( \
7821
::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7822
+ ::testing::internal::StreamableToString(__LINE__) + ": " \
7823
+ #expression + " != -1"); \
7824
} \
7825
} while (::testing::internal::AlwaysFalse())
7826
7827
// Returns the message describing the last system error in errno.
7828
std::string GetLastErrnoDescription() {
7829
return errno == 0 ? "" : posix::StrError(errno);
7830
}
7831
7832
// This is called from a death test parent process to read a failure
7833
// message from the death test child process and log it with the FATAL
7834
// severity. On Windows, the message is read from a pipe handle. On other
7835
// platforms, it is read from a file descriptor.
7836
static void FailFromInternalError(int fd) {
7837
Message error;
7838
char buffer[256];
7839
int num_read;
7840
7841
do {
7842
while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
7843
buffer[num_read] = '\0';
7844
error << buffer;
7845
}
7846
} while (num_read == -1 && errno == EINTR);
7847
7848
if (num_read == 0) {
7849
GTEST_LOG_(FATAL) << error.GetString();
7850
} else {
7851
const int last_error = errno;
7852
GTEST_LOG_(FATAL) << "Error while reading death test internal: "
7853
<< GetLastErrnoDescription() << " [" << last_error << "]";
7854
}
7855
}
7856
7857
// Death test constructor. Increments the running death test count
7858
// for the current test.
7859
DeathTest::DeathTest() {
7860
TestInfo* const info = GetUnitTestImpl()->current_test_info();
7861
if (info == NULL) {
7862
DeathTestAbort("Cannot run a death test outside of a TEST or "
7863
"TEST_F construct");
7864
}
7865
}
7866
7867
// Creates and returns a death test by dispatching to the current
7868
// death test factory.
7869
bool DeathTest::Create(const char* statement, const RE* regex,
7870
const char* file, int line, DeathTest** test) {
7871
return GetUnitTestImpl()->death_test_factory()->Create(
7872
statement, regex, file, line, test);
7873
}
7874
7875
const char* DeathTest::LastMessage() {
7876
return last_death_test_message_.c_str();
7877
}
7878
7879
void DeathTest::set_last_death_test_message(const std::string& message) {
7880
last_death_test_message_ = message;
7881
}
7882
7883
std::string DeathTest::last_death_test_message_;
7884
7885
// Provides cross platform implementation for some death functionality.
7886
class DeathTestImpl : public DeathTest {
7887
protected:
7888
DeathTestImpl(const char* a_statement, const RE* a_regex)
7889
: statement_(a_statement),
7890
regex_(a_regex),
7891
spawned_(false),
7892
status_(-1),
7893
outcome_(IN_PROGRESS),
7894
read_fd_(-1),
7895
write_fd_(-1) {}
7896
7897
// read_fd_ is expected to be closed and cleared by a derived class.
7898
~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
7899
7900
void Abort(AbortReason reason);
7901
virtual bool Passed(bool status_ok);
7902
7903
const char* statement() const { return statement_; }
7904
const RE* regex() const { return regex_; }
7905
bool spawned() const { return spawned_; }
7906
void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
7907
int status() const { return status_; }
7908
void set_status(int a_status) { status_ = a_status; }
7909
DeathTestOutcome outcome() const { return outcome_; }
7910
void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
7911
int read_fd() const { return read_fd_; }
7912
void set_read_fd(int fd) { read_fd_ = fd; }
7913
int write_fd() const { return write_fd_; }
7914
void set_write_fd(int fd) { write_fd_ = fd; }
7915
7916
// Called in the parent process only. Reads the result code of the death
7917
// test child process via a pipe, interprets it to set the outcome_
7918
// member, and closes read_fd_. Outputs diagnostics and terminates in
7919
// case of unexpected codes.
7920
void ReadAndInterpretStatusByte();
7921
7922
private:
7923
// The textual content of the code this object is testing. This class
7924
// doesn't own this string and should not attempt to delete it.
7925
const char* const statement_;
7926
// The regular expression which test output must match. DeathTestImpl
7927
// doesn't own this object and should not attempt to delete it.
7928
const RE* const regex_;
7929
// True if the death test child process has been successfully spawned.
7930
bool spawned_;
7931
// The exit status of the child process.
7932
int status_;
7933
// How the death test concluded.
7934
DeathTestOutcome outcome_;
7935
// Descriptor to the read end of the pipe to the child process. It is
7936
// always -1 in the child process. The child keeps its write end of the
7937
// pipe in write_fd_.
7938
int read_fd_;
7939
// Descriptor to the child's write end of the pipe to the parent process.
7940
// It is always -1 in the parent process. The parent keeps its end of the
7941
// pipe in read_fd_.
7942
int write_fd_;
7943
};
7944
7945
// Called in the parent process only. Reads the result code of the death
7946
// test child process via a pipe, interprets it to set the outcome_
7947
// member, and closes read_fd_. Outputs diagnostics and terminates in
7948
// case of unexpected codes.
7949
void DeathTestImpl::ReadAndInterpretStatusByte() {
7950
char flag;
7951
int bytes_read;
7952
7953
// The read() here blocks until data is available (signifying the
7954
// failure of the death test) or until the pipe is closed (signifying
7955
// its success), so it's okay to call this in the parent before
7956
// the child process has exited.
7957
do {
7958
bytes_read = posix::Read(read_fd(), &flag, 1);
7959
} while (bytes_read == -1 && errno == EINTR);
7960
7961
if (bytes_read == 0) {
7962
set_outcome(DIED);
7963
} else if (bytes_read == 1) {
7964
switch (flag) {
7965
case kDeathTestReturned:
7966
set_outcome(RETURNED);
7967
break;
7968
case kDeathTestThrew:
7969
set_outcome(THREW);
7970
break;
7971
case kDeathTestLived:
7972
set_outcome(LIVED);
7973
break;
7974
case kDeathTestInternalError:
7975
FailFromInternalError(read_fd()); // Does not return.
7976
break;
7977
default:
7978
GTEST_LOG_(FATAL) << "Death test child process reported "
7979
<< "unexpected status byte ("
7980
<< static_cast<unsigned int>(flag) << ")";
7981
}
7982
} else {
7983
GTEST_LOG_(FATAL) << "Read from death test child process failed: "
7984
<< GetLastErrnoDescription();
7985
}
7986
GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
7987
set_read_fd(-1);
7988
}
7989
7990
// Signals that the death test code which should have exited, didn't.
7991
// Should be called only in a death test child process.
7992
// Writes a status byte to the child's status file descriptor, then
7993
// calls _exit(1).
7994
void DeathTestImpl::Abort(AbortReason reason) {
7995
// The parent process considers the death test to be a failure if
7996
// it finds any data in our pipe. So, here we write a single flag byte
7997
// to the pipe, then exit.
7998
const char status_ch =
7999
reason == TEST_DID_NOT_DIE ? kDeathTestLived :
8000
reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
8001
8002
GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
8003
// We are leaking the descriptor here because on some platforms (i.e.,
8004
// when built as Windows DLL), destructors of global objects will still
8005
// run after calling _exit(). On such systems, write_fd_ will be
8006
// indirectly closed from the destructor of UnitTestImpl, causing double
8007
// close if it is also closed here. On debug configurations, double close
8008
// may assert. As there are no in-process buffers to flush here, we are
8009
// relying on the OS to close the descriptor after the process terminates
8010
// when the destructors are not run.
8011
_exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
8012
}
8013
8014
// Returns an indented copy of stderr output for a death test.
8015
// This makes distinguishing death test output lines from regular log lines
8016
// much easier.
8017
static ::std::string FormatDeathTestOutput(const ::std::string& output) {
8018
::std::string ret;
8019
for (size_t at = 0; ; ) {
8020
const size_t line_end = output.find('\n', at);
8021
ret += "[ DEATH ] ";
8022
if (line_end == ::std::string::npos) {
8023
ret += output.substr(at);
8024
break;
8025
}
8026
ret += output.substr(at, line_end + 1 - at);
8027
at = line_end + 1;
8028
}
8029
return ret;
8030
}
8031
8032
// Assesses the success or failure of a death test, using both private
8033
// members which have previously been set, and one argument:
8034
//
8035
// Private data members:
8036
// outcome: An enumeration describing how the death test
8037
// concluded: DIED, LIVED, THREW, or RETURNED. The death test
8038
// fails in the latter three cases.
8039
// status: The exit status of the child process. On *nix, it is in the
8040
// in the format specified by wait(2). On Windows, this is the
8041
// value supplied to the ExitProcess() API or a numeric code
8042
// of the exception that terminated the program.
8043
// regex: A regular expression object to be applied to
8044
// the test's captured standard error output; the death test
8045
// fails if it does not match.
8046
//
8047
// Argument:
8048
// status_ok: true if exit_status is acceptable in the context of
8049
// this particular death test, which fails if it is false
8050
//
8051
// Returns true iff all of the above conditions are met. Otherwise, the
8052
// first failing condition, in the order given above, is the one that is
8053
// reported. Also sets the last death test message string.
8054
bool DeathTestImpl::Passed(bool status_ok) {
8055
if (!spawned())
8056
return false;
8057
8058
const std::string error_message = GetCapturedStderr();
8059
8060
bool success = false;
8061
Message buffer;
8062
8063
buffer << "Death test: " << statement() << "\n";
8064
switch (outcome()) {
8065
case LIVED:
8066
buffer << " Result: failed to die.\n"
8067
<< " Error msg:\n" << FormatDeathTestOutput(error_message);
8068
break;
8069
case THREW:
8070
buffer << " Result: threw an exception.\n"
8071
<< " Error msg:\n" << FormatDeathTestOutput(error_message);
8072
break;
8073
case RETURNED:
8074
buffer << " Result: illegal return in test statement.\n"
8075
<< " Error msg:\n" << FormatDeathTestOutput(error_message);
8076
break;
8077
case DIED:
8078
if (status_ok) {
8079
# if GTEST_USES_PCRE
8080
// PCRE regexes support embedded NULs.
8081
const bool matched = RE::PartialMatch(error_message, *regex());
8082
# else
8083
const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
8084
# endif // GTEST_USES_PCRE
8085
if (matched) {
8086
success = true;
8087
} else {
8088
buffer << " Result: died but not with expected error.\n"
8089
<< " Expected: " << regex()->pattern() << "\n"
8090
<< "Actual msg:\n" << FormatDeathTestOutput(error_message);
8091
}
8092
} else {
8093
buffer << " Result: died but not with expected exit code:\n"
8094
<< " " << ExitSummary(status()) << "\n"
8095
<< "Actual msg:\n" << FormatDeathTestOutput(error_message);
8096
}
8097
break;
8098
case IN_PROGRESS:
8099
default:
8100
GTEST_LOG_(FATAL)
8101
<< "DeathTest::Passed somehow called before conclusion of test";
8102
}
8103
8104
DeathTest::set_last_death_test_message(buffer.GetString());
8105
return success;
8106
}
8107
8108
# if GTEST_OS_WINDOWS
8109
// WindowsDeathTest implements death tests on Windows. Due to the
8110
// specifics of starting new processes on Windows, death tests there are
8111
// always threadsafe, and Google Test considers the
8112
// --gtest_death_test_style=fast setting to be equivalent to
8113
// --gtest_death_test_style=threadsafe there.
8114
//
8115
// A few implementation notes: Like the Linux version, the Windows
8116
// implementation uses pipes for child-to-parent communication. But due to
8117
// the specifics of pipes on Windows, some extra steps are required:
8118
//
8119
// 1. The parent creates a communication pipe and stores handles to both
8120
// ends of it.
8121
// 2. The parent starts the child and provides it with the information
8122
// necessary to acquire the handle to the write end of the pipe.
8123
// 3. The child acquires the write end of the pipe and signals the parent
8124
// using a Windows event.
8125
// 4. Now the parent can release the write end of the pipe on its side. If
8126
// this is done before step 3, the object's reference count goes down to
8127
// 0 and it is destroyed, preventing the child from acquiring it. The
8128
// parent now has to release it, or read operations on the read end of
8129
// the pipe will not return when the child terminates.
8130
// 5. The parent reads child's output through the pipe (outcome code and
8131
// any possible error messages) from the pipe, and its stderr and then
8132
// determines whether to fail the test.
8133
//
8134
// Note: to distinguish Win32 API calls from the local method and function
8135
// calls, the former are explicitly resolved in the global namespace.
8136
//
8137
class WindowsDeathTest : public DeathTestImpl {
8138
public:
8139
WindowsDeathTest(const char* a_statement,
8140
const RE* a_regex,
8141
const char* file,
8142
int line)
8143
: DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
8144
8145
// All of these virtual functions are inherited from DeathTest.
8146
virtual int Wait();
8147
virtual TestRole AssumeRole();
8148
8149
private:
8150
// The name of the file in which the death test is located.
8151
const char* const file_;
8152
// The line number on which the death test is located.
8153
const int line_;
8154
// Handle to the write end of the pipe to the child process.
8155
AutoHandle write_handle_;
8156
// Child process handle.
8157
AutoHandle child_handle_;
8158
// Event the child process uses to signal the parent that it has
8159
// acquired the handle to the write end of the pipe. After seeing this
8160
// event the parent can release its own handles to make sure its
8161
// ReadFile() calls return when the child terminates.
8162
AutoHandle event_handle_;
8163
};
8164
8165
// Waits for the child in a death test to exit, returning its exit
8166
// status, or 0 if no child process exists. As a side effect, sets the
8167
// outcome data member.
8168
int WindowsDeathTest::Wait() {
8169
if (!spawned())
8170
return 0;
8171
8172
// Wait until the child either signals that it has acquired the write end
8173
// of the pipe or it dies.
8174
const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
8175
switch (::WaitForMultipleObjects(2,
8176
wait_handles,
8177
FALSE, // Waits for any of the handles.
8178
INFINITE)) {
8179
case WAIT_OBJECT_0:
8180
case WAIT_OBJECT_0 + 1:
8181
break;
8182
default:
8183
GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
8184
}
8185
8186
// The child has acquired the write end of the pipe or exited.
8187
// We release the handle on our side and continue.
8188
write_handle_.Reset();
8189
event_handle_.Reset();
8190
8191
ReadAndInterpretStatusByte();
8192
8193
// Waits for the child process to exit if it haven't already. This
8194
// returns immediately if the child has already exited, regardless of
8195
// whether previous calls to WaitForMultipleObjects synchronized on this
8196
// handle or not.
8197
GTEST_DEATH_TEST_CHECK_(
8198
WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
8199
INFINITE));
8200
DWORD status_code;
8201
GTEST_DEATH_TEST_CHECK_(
8202
::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
8203
child_handle_.Reset();
8204
set_status(static_cast<int>(status_code));
8205
return status();
8206
}
8207
8208
// The AssumeRole process for a Windows death test. It creates a child
8209
// process with the same executable as the current process to run the
8210
// death test. The child process is given the --gtest_filter and
8211
// --gtest_internal_run_death_test flags such that it knows to run the
8212
// current death test only.
8213
DeathTest::TestRole WindowsDeathTest::AssumeRole() {
8214
const UnitTestImpl* const impl = GetUnitTestImpl();
8215
const InternalRunDeathTestFlag* const flag =
8216
impl->internal_run_death_test_flag();
8217
const TestInfo* const info = impl->current_test_info();
8218
const int death_test_index = info->result()->death_test_count();
8219
8220
if (flag != NULL) {
8221
// ParseInternalRunDeathTestFlag() has performed all the necessary
8222
// processing.
8223
set_write_fd(flag->write_fd());
8224
return EXECUTE_TEST;
8225
}
8226
8227
// WindowsDeathTest uses an anonymous pipe to communicate results of
8228
// a death test.
8229
SECURITY_ATTRIBUTES handles_are_inheritable = {
8230
sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
8231
HANDLE read_handle, write_handle;
8232
GTEST_DEATH_TEST_CHECK_(
8233
::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
8234
0) // Default buffer size.
8235
!= FALSE);
8236
set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
8237
O_RDONLY));
8238
write_handle_.Reset(write_handle);
8239
event_handle_.Reset(::CreateEvent(
8240
&handles_are_inheritable,
8241
TRUE, // The event will automatically reset to non-signaled state.
8242
FALSE, // The initial state is non-signalled.
8243
NULL)); // The even is unnamed.
8244
GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
8245
const std::string filter_flag =
8246
std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
8247
info->test_case_name() + "." + info->name();
8248
const std::string internal_flag =
8249
std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
8250
"=" + file_ + "|" + StreamableToString(line_) + "|" +
8251
StreamableToString(death_test_index) + "|" +
8252
StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
8253
// size_t has the same width as pointers on both 32-bit and 64-bit
8254
// Windows platforms.
8255
// See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
8256
"|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
8257
"|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
8258
8259
char executable_path[_MAX_PATH + 1]; // NOLINT
8260
GTEST_DEATH_TEST_CHECK_(
8261
_MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
8262
executable_path,
8263
_MAX_PATH));
8264
8265
std::string command_line =
8266
std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
8267
internal_flag + "\"";
8268
8269
DeathTest::set_last_death_test_message("");
8270
8271
CaptureStderr();
8272
// Flush the log buffers since the log streams are shared with the child.
8273
FlushInfoLog();
8274
8275
// The child process will share the standard handles with the parent.
8276
STARTUPINFOA startup_info;
8277
memset(&startup_info, 0, sizeof(STARTUPINFO));
8278
startup_info.dwFlags = STARTF_USESTDHANDLES;
8279
startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
8280
startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
8281
startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
8282
8283
PROCESS_INFORMATION process_info;
8284
GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
8285
executable_path,
8286
const_cast<char*>(command_line.c_str()),
8287
NULL, // Retuned process handle is not inheritable.
8288
NULL, // Retuned thread handle is not inheritable.
8289
TRUE, // Child inherits all inheritable handles (for write_handle_).
8290
0x0, // Default creation flags.
8291
NULL, // Inherit the parent's environment.
8292
UnitTest::GetInstance()->original_working_dir(),
8293
&startup_info,
8294
&process_info) != FALSE);
8295
child_handle_.Reset(process_info.hProcess);
8296
::CloseHandle(process_info.hThread);
8297
set_spawned(true);
8298
return OVERSEE_TEST;
8299
}
8300
8301
# elif GTEST_OS_FUCHSIA
8302
8303
class FuchsiaDeathTest : public DeathTestImpl {
8304
public:
8305
FuchsiaDeathTest(const char* a_statement,
8306
const RE* a_regex,
8307
const char* file,
8308
int line)
8309
: DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
8310
virtual ~FuchsiaDeathTest() {
8311
zx_status_t status = zx_handle_close(child_process_);
8312
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8313
status = zx_handle_close(port_);
8314
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8315
}
8316
8317
// All of these virtual functions are inherited from DeathTest.
8318
virtual int Wait();
8319
virtual TestRole AssumeRole();
8320
8321
private:
8322
// The name of the file in which the death test is located.
8323
const char* const file_;
8324
// The line number on which the death test is located.
8325
const int line_;
8326
8327
zx_handle_t child_process_ = ZX_HANDLE_INVALID;
8328
zx_handle_t port_ = ZX_HANDLE_INVALID;
8329
};
8330
8331
// Utility class for accumulating command-line arguments.
8332
class Arguments {
8333
public:
8334
Arguments() {
8335
args_.push_back(NULL);
8336
}
8337
8338
~Arguments() {
8339
for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8340
++i) {
8341
free(*i);
8342
}
8343
}
8344
void AddArgument(const char* argument) {
8345
args_.insert(args_.end() - 1, posix::StrDup(argument));
8346
}
8347
8348
template <typename Str>
8349
void AddArguments(const ::std::vector<Str>& arguments) {
8350
for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8351
i != arguments.end();
8352
++i) {
8353
args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
8354
}
8355
}
8356
char* const* Argv() {
8357
return &args_[0];
8358
}
8359
8360
int size() {
8361
return args_.size() - 1;
8362
}
8363
8364
private:
8365
std::vector<char*> args_;
8366
};
8367
8368
// Waits for the child in a death test to exit, returning its exit
8369
// status, or 0 if no child process exists. As a side effect, sets the
8370
// outcome data member.
8371
int FuchsiaDeathTest::Wait() {
8372
if (!spawned())
8373
return 0;
8374
8375
// Register to wait for the child process to terminate.
8376
zx_status_t status_zx;
8377
status_zx = zx_object_wait_async(child_process_,
8378
port_,
8379
0 /* key */,
8380
ZX_PROCESS_TERMINATED,
8381
ZX_WAIT_ASYNC_ONCE);
8382
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8383
8384
// Wait for it to terminate, or an exception to be received.
8385
zx_port_packet_t packet;
8386
status_zx = zx_port_wait(port_, ZX_TIME_INFINITE, &packet);
8387
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8388
8389
if (ZX_PKT_IS_EXCEPTION(packet.type)) {
8390
// Process encountered an exception. Kill it directly rather than letting
8391
// other handlers process the event.
8392
status_zx = zx_task_kill(child_process_);
8393
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8394
8395
// Now wait for |child_process_| to terminate.
8396
zx_signals_t signals = 0;
8397
status_zx = zx_object_wait_one(
8398
child_process_, ZX_PROCESS_TERMINATED, ZX_TIME_INFINITE, &signals);
8399
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8400
GTEST_DEATH_TEST_CHECK_(signals & ZX_PROCESS_TERMINATED);
8401
} else {
8402
// Process terminated.
8403
GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
8404
GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
8405
}
8406
8407
ReadAndInterpretStatusByte();
8408
8409
zx_info_process_t buffer;
8410
status_zx = zx_object_get_info(
8411
child_process_,
8412
ZX_INFO_PROCESS,
8413
&buffer,
8414
sizeof(buffer),
8415
nullptr,
8416
nullptr);
8417
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8418
8419
GTEST_DEATH_TEST_CHECK_(buffer.exited);
8420
set_status(buffer.return_code);
8421
return status();
8422
}
8423
8424
// The AssumeRole process for a Fuchsia death test. It creates a child
8425
// process with the same executable as the current process to run the
8426
// death test. The child process is given the --gtest_filter and
8427
// --gtest_internal_run_death_test flags such that it knows to run the
8428
// current death test only.
8429
DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
8430
const UnitTestImpl* const impl = GetUnitTestImpl();
8431
const InternalRunDeathTestFlag* const flag =
8432
impl->internal_run_death_test_flag();
8433
const TestInfo* const info = impl->current_test_info();
8434
const int death_test_index = info->result()->death_test_count();
8435
8436
if (flag != NULL) {
8437
// ParseInternalRunDeathTestFlag() has performed all the necessary
8438
// processing.
8439
set_write_fd(kFuchsiaReadPipeFd);
8440
return EXECUTE_TEST;
8441
}
8442
8443
CaptureStderr();
8444
// Flush the log buffers since the log streams are shared with the child.
8445
FlushInfoLog();
8446
8447
// Build the child process command line.
8448
const std::string filter_flag =
8449
std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
8450
+ info->test_case_name() + "." + info->name();
8451
const std::string internal_flag =
8452
std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
8453
+ file_ + "|"
8454
+ StreamableToString(line_) + "|"
8455
+ StreamableToString(death_test_index);
8456
Arguments args;
8457
args.AddArguments(GetInjectableArgvs());
8458
args.AddArgument(filter_flag.c_str());
8459
args.AddArgument(internal_flag.c_str());
8460
8461
// Build the pipe for communication with the child.
8462
zx_status_t status;
8463
zx_handle_t child_pipe_handle;
8464
uint32_t type;
8465
status = fdio_pipe_half(&child_pipe_handle, &type);
8466
GTEST_DEATH_TEST_CHECK_(status >= 0);
8467
set_read_fd(status);
8468
8469
// Set the pipe handle for the child.
8470
fdio_spawn_action_t add_handle_action = {};
8471
add_handle_action.action = FDIO_SPAWN_ACTION_ADD_HANDLE;
8472
add_handle_action.h.id = PA_HND(type, kFuchsiaReadPipeFd);
8473
add_handle_action.h.handle = child_pipe_handle;
8474
8475
// Spawn the child process.
8476
status = fdio_spawn_etc(ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL,
8477
args.Argv()[0], args.Argv(), nullptr, 1,
8478
&add_handle_action, &child_process_, nullptr);
8479
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8480
8481
// Create an exception port and attach it to the |child_process_|, to allow
8482
// us to suppress the system default exception handler from firing.
8483
status = zx_port_create(0, &port_);
8484
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8485
status = zx_task_bind_exception_port(
8486
child_process_, port_, 0 /* key */, 0 /*options */);
8487
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8488
8489
set_spawned(true);
8490
return OVERSEE_TEST;
8491
}
8492
8493
#else // We are neither on Windows, nor on Fuchsia.
8494
8495
// ForkingDeathTest provides implementations for most of the abstract
8496
// methods of the DeathTest interface. Only the AssumeRole method is
8497
// left undefined.
8498
class ForkingDeathTest : public DeathTestImpl {
8499
public:
8500
ForkingDeathTest(const char* statement, const RE* regex);
8501
8502
// All of these virtual functions are inherited from DeathTest.
8503
virtual int Wait();
8504
8505
protected:
8506
void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
8507
8508
private:
8509
// PID of child process during death test; 0 in the child process itself.
8510
pid_t child_pid_;
8511
};
8512
8513
// Constructs a ForkingDeathTest.
8514
ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
8515
: DeathTestImpl(a_statement, a_regex),
8516
child_pid_(-1) {}
8517
8518
// Waits for the child in a death test to exit, returning its exit
8519
// status, or 0 if no child process exists. As a side effect, sets the
8520
// outcome data member.
8521
int ForkingDeathTest::Wait() {
8522
if (!spawned())
8523
return 0;
8524
8525
ReadAndInterpretStatusByte();
8526
8527
int status_value;
8528
GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
8529
set_status(status_value);
8530
return status_value;
8531
}
8532
8533
// A concrete death test class that forks, then immediately runs the test
8534
// in the child process.
8535
class NoExecDeathTest : public ForkingDeathTest {
8536
public:
8537
NoExecDeathTest(const char* a_statement, const RE* a_regex) :
8538
ForkingDeathTest(a_statement, a_regex) { }
8539
virtual TestRole AssumeRole();
8540
};
8541
8542
// The AssumeRole process for a fork-and-run death test. It implements a
8543
// straightforward fork, with a simple pipe to transmit the status byte.
8544
DeathTest::TestRole NoExecDeathTest::AssumeRole() {
8545
const size_t thread_count = GetThreadCount();
8546
if (thread_count != 1) {
8547
GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
8548
}
8549
8550
int pipe_fd[2];
8551
GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8552
8553
DeathTest::set_last_death_test_message("");
8554
CaptureStderr();
8555
// When we fork the process below, the log file buffers are copied, but the
8556
// file descriptors are shared. We flush all log files here so that closing
8557
// the file descriptors in the child process doesn't throw off the
8558
// synchronization between descriptors and buffers in the parent process.
8559
// This is as close to the fork as possible to avoid a race condition in case
8560
// there are multiple threads running before the death test, and another
8561
// thread writes to the log file.
8562
FlushInfoLog();
8563
8564
const pid_t child_pid = fork();
8565
GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8566
set_child_pid(child_pid);
8567
if (child_pid == 0) {
8568
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
8569
set_write_fd(pipe_fd[1]);
8570
// Redirects all logging to stderr in the child process to prevent
8571
// concurrent writes to the log files. We capture stderr in the parent
8572
// process and append the child process' output to a log.
8573
LogToStderr();
8574
// Event forwarding to the listeners of event listener API mush be shut
8575
// down in death test subprocesses.
8576
GetUnitTestImpl()->listeners()->SuppressEventForwarding();
8577
g_in_fast_death_test_child = true;
8578
return EXECUTE_TEST;
8579
} else {
8580
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8581
set_read_fd(pipe_fd[0]);
8582
set_spawned(true);
8583
return OVERSEE_TEST;
8584
}
8585
}
8586
8587
// A concrete death test class that forks and re-executes the main
8588
// program from the beginning, with command-line flags set that cause
8589
// only this specific death test to be run.
8590
class ExecDeathTest : public ForkingDeathTest {
8591
public:
8592
ExecDeathTest(const char* a_statement, const RE* a_regex,
8593
const char* file, int line) :
8594
ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
8595
virtual TestRole AssumeRole();
8596
private:
8597
static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
8598
::std::vector<std::string> args = GetInjectableArgvs();
8599
# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
8600
::std::vector<std::string> extra_args =
8601
GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
8602
args.insert(args.end(), extra_args.begin(), extra_args.end());
8603
# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
8604
return args;
8605
}
8606
// The name of the file in which the death test is located.
8607
const char* const file_;
8608
// The line number on which the death test is located.
8609
const int line_;
8610
};
8611
8612
// Utility class for accumulating command-line arguments.
8613
class Arguments {
8614
public:
8615
Arguments() {
8616
args_.push_back(NULL);
8617
}
8618
8619
~Arguments() {
8620
for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8621
++i) {
8622
free(*i);
8623
}
8624
}
8625
void AddArgument(const char* argument) {
8626
args_.insert(args_.end() - 1, posix::StrDup(argument));
8627
}
8628
8629
template <typename Str>
8630
void AddArguments(const ::std::vector<Str>& arguments) {
8631
for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8632
i != arguments.end();
8633
++i) {
8634
args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
8635
}
8636
}
8637
char* const* Argv() {
8638
return &args_[0];
8639
}
8640
8641
private:
8642
std::vector<char*> args_;
8643
};
8644
8645
// A struct that encompasses the arguments to the child process of a
8646
// threadsafe-style death test process.
8647
struct ExecDeathTestArgs {
8648
char* const* argv; // Command-line arguments for the child's call to exec
8649
int close_fd; // File descriptor to close; the read end of a pipe
8650
};
8651
8652
# if GTEST_OS_MAC
8653
inline char** GetEnviron() {
8654
// When Google Test is built as a framework on MacOS X, the environ variable
8655
// is unavailable. Apple's documentation (man environ) recommends using
8656
// _NSGetEnviron() instead.
8657
return *_NSGetEnviron();
8658
}
8659
# else
8660
// Some POSIX platforms expect you to declare environ. extern "C" makes
8661
// it reside in the global namespace.
8662
extern "C" char** environ;
8663
inline char** GetEnviron() { return environ; }
8664
# endif // GTEST_OS_MAC
8665
8666
# if !GTEST_OS_QNX
8667
// The main function for a threadsafe-style death test child process.
8668
// This function is called in a clone()-ed process and thus must avoid
8669
// any potentially unsafe operations like malloc or libc functions.
8670
static int ExecDeathTestChildMain(void* child_arg) {
8671
ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
8672
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
8673
8674
// We need to execute the test program in the same environment where
8675
// it was originally invoked. Therefore we change to the original
8676
// working directory first.
8677
const char* const original_dir =
8678
UnitTest::GetInstance()->original_working_dir();
8679
// We can safely call chdir() as it's a direct system call.
8680
if (chdir(original_dir) != 0) {
8681
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
8682
GetLastErrnoDescription());
8683
return EXIT_FAILURE;
8684
}
8685
8686
// We can safely call execve() as it's a direct system call. We
8687
// cannot use execvp() as it's a libc function and thus potentially
8688
// unsafe. Since execve() doesn't search the PATH, the user must
8689
// invoke the test program via a valid path that contains at least
8690
// one path separator.
8691
execve(args->argv[0], args->argv, GetEnviron());
8692
DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
8693
original_dir + " failed: " +
8694
GetLastErrnoDescription());
8695
return EXIT_FAILURE;
8696
}
8697
# endif // !GTEST_OS_QNX
8698
8699
# if GTEST_HAS_CLONE
8700
// Two utility routines that together determine the direction the stack
8701
// grows.
8702
// This could be accomplished more elegantly by a single recursive
8703
// function, but we want to guard against the unlikely possibility of
8704
// a smart compiler optimizing the recursion away.
8705
//
8706
// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
8707
// StackLowerThanAddress into StackGrowsDown, which then doesn't give
8708
// correct answer.
8709
static void StackLowerThanAddress(const void* ptr,
8710
bool* result) GTEST_NO_INLINE_;
8711
static void StackLowerThanAddress(const void* ptr, bool* result) {
8712
int dummy;
8713
*result = (&dummy < ptr);
8714
}
8715
8716
// Make sure AddressSanitizer does not tamper with the stack here.
8717
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
8718
static bool StackGrowsDown() {
8719
int dummy;
8720
bool result;
8721
StackLowerThanAddress(&dummy, &result);
8722
return result;
8723
}
8724
# endif // GTEST_HAS_CLONE
8725
8726
// Spawns a child process with the same executable as the current process in
8727
// a thread-safe manner and instructs it to run the death test. The
8728
// implementation uses fork(2) + exec. On systems where clone(2) is
8729
// available, it is used instead, being slightly more thread-safe. On QNX,
8730
// fork supports only single-threaded environments, so this function uses
8731
// spawn(2) there instead. The function dies with an error message if
8732
// anything goes wrong.
8733
static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
8734
ExecDeathTestArgs args = { argv, close_fd };
8735
pid_t child_pid = -1;
8736
8737
# if GTEST_OS_QNX
8738
// Obtains the current directory and sets it to be closed in the child
8739
// process.
8740
const int cwd_fd = open(".", O_RDONLY);
8741
GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
8742
GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
8743
// We need to execute the test program in the same environment where
8744
// it was originally invoked. Therefore we change to the original
8745
// working directory first.
8746
const char* const original_dir =
8747
UnitTest::GetInstance()->original_working_dir();
8748
// We can safely call chdir() as it's a direct system call.
8749
if (chdir(original_dir) != 0) {
8750
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
8751
GetLastErrnoDescription());
8752
return EXIT_FAILURE;
8753
}
8754
8755
int fd_flags;
8756
// Set close_fd to be closed after spawn.
8757
GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
8758
GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
8759
fd_flags | FD_CLOEXEC));
8760
struct inheritance inherit = {0};
8761
// spawn is a system call.
8762
child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
8763
// Restores the current working directory.
8764
GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
8765
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
8766
8767
# else // GTEST_OS_QNX
8768
# if GTEST_OS_LINUX
8769
// When a SIGPROF signal is received while fork() or clone() are executing,
8770
// the process may hang. To avoid this, we ignore SIGPROF here and re-enable
8771
// it after the call to fork()/clone() is complete.
8772
struct sigaction saved_sigprof_action;
8773
struct sigaction ignore_sigprof_action;
8774
memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
8775
sigemptyset(&ignore_sigprof_action.sa_mask);
8776
ignore_sigprof_action.sa_handler = SIG_IGN;
8777
GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
8778
SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
8779
# endif // GTEST_OS_LINUX
8780
8781
# if GTEST_HAS_CLONE
8782
const bool use_fork = GTEST_FLAG(death_test_use_fork);
8783
8784
if (!use_fork) {
8785
static const bool stack_grows_down = StackGrowsDown();
8786
const size_t stack_size = getpagesize();
8787
// MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
8788
void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
8789
MAP_ANON | MAP_PRIVATE, -1, 0);
8790
GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
8791
8792
// Maximum stack alignment in bytes: For a downward-growing stack, this
8793
// amount is subtracted from size of the stack space to get an address
8794
// that is within the stack space and is aligned on all systems we care
8795
// about. As far as I know there is no ABI with stack alignment greater
8796
// than 64. We assume stack and stack_size already have alignment of
8797
// kMaxStackAlignment.
8798
const size_t kMaxStackAlignment = 64;
8799
void* const stack_top =
8800
static_cast<char*>(stack) +
8801
(stack_grows_down ? stack_size - kMaxStackAlignment : 0);
8802
GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
8803
reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
8804
8805
child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
8806
8807
GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
8808
}
8809
# else
8810
const bool use_fork = true;
8811
# endif // GTEST_HAS_CLONE
8812
8813
if (use_fork && (child_pid = fork()) == 0) {
8814
ExecDeathTestChildMain(&args);
8815
_exit(0);
8816
}
8817
# endif // GTEST_OS_QNX
8818
# if GTEST_OS_LINUX
8819
GTEST_DEATH_TEST_CHECK_SYSCALL_(
8820
sigaction(SIGPROF, &saved_sigprof_action, NULL));
8821
# endif // GTEST_OS_LINUX
8822
8823
GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8824
return child_pid;
8825
}
8826
8827
// The AssumeRole process for a fork-and-exec death test. It re-executes the
8828
// main program from the beginning, setting the --gtest_filter
8829
// and --gtest_internal_run_death_test flags to cause only the current
8830
// death test to be re-run.
8831
DeathTest::TestRole ExecDeathTest::AssumeRole() {
8832
const UnitTestImpl* const impl = GetUnitTestImpl();
8833
const InternalRunDeathTestFlag* const flag =
8834
impl->internal_run_death_test_flag();
8835
const TestInfo* const info = impl->current_test_info();
8836
const int death_test_index = info->result()->death_test_count();
8837
8838
if (flag != NULL) {
8839
set_write_fd(flag->write_fd());
8840
return EXECUTE_TEST;
8841
}
8842
8843
int pipe_fd[2];
8844
GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8845
// Clear the close-on-exec flag on the write end of the pipe, lest
8846
// it be closed when the child process does an exec:
8847
GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
8848
8849
const std::string filter_flag =
8850
std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
8851
+ info->test_case_name() + "." + info->name();
8852
const std::string internal_flag =
8853
std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
8854
+ file_ + "|" + StreamableToString(line_) + "|"
8855
+ StreamableToString(death_test_index) + "|"
8856
+ StreamableToString(pipe_fd[1]);
8857
Arguments args;
8858
args.AddArguments(GetArgvsForDeathTestChildProcess());
8859
args.AddArgument(filter_flag.c_str());
8860
args.AddArgument(internal_flag.c_str());
8861
8862
DeathTest::set_last_death_test_message("");
8863
8864
CaptureStderr();
8865
// See the comment in NoExecDeathTest::AssumeRole for why the next line
8866
// is necessary.
8867
FlushInfoLog();
8868
8869
const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
8870
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8871
set_child_pid(child_pid);
8872
set_read_fd(pipe_fd[0]);
8873
set_spawned(true);
8874
return OVERSEE_TEST;
8875
}
8876
8877
# endif // !GTEST_OS_WINDOWS
8878
8879
// Creates a concrete DeathTest-derived class that depends on the
8880
// --gtest_death_test_style flag, and sets the pointer pointed to
8881
// by the "test" argument to its address. If the test should be
8882
// skipped, sets that pointer to NULL. Returns true, unless the
8883
// flag is set to an invalid value.
8884
bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
8885
const char* file, int line,
8886
DeathTest** test) {
8887
UnitTestImpl* const impl = GetUnitTestImpl();
8888
const InternalRunDeathTestFlag* const flag =
8889
impl->internal_run_death_test_flag();
8890
const int death_test_index = impl->current_test_info()
8891
->increment_death_test_count();
8892
8893
if (flag != NULL) {
8894
if (death_test_index > flag->index()) {
8895
DeathTest::set_last_death_test_message(
8896
"Death test count (" + StreamableToString(death_test_index)
8897
+ ") somehow exceeded expected maximum ("
8898
+ StreamableToString(flag->index()) + ")");
8899
return false;
8900
}
8901
8902
if (!(flag->file() == file && flag->line() == line &&
8903
flag->index() == death_test_index)) {
8904
*test = NULL;
8905
return true;
8906
}
8907
}
8908
8909
# if GTEST_OS_WINDOWS
8910
8911
if (GTEST_FLAG(death_test_style) == "threadsafe" ||
8912
GTEST_FLAG(death_test_style) == "fast") {
8913
*test = new WindowsDeathTest(statement, regex, file, line);
8914
}
8915
8916
# elif GTEST_OS_FUCHSIA
8917
8918
if (GTEST_FLAG(death_test_style) == "threadsafe" ||
8919
GTEST_FLAG(death_test_style) == "fast") {
8920
*test = new FuchsiaDeathTest(statement, regex, file, line);
8921
}
8922
8923
# else
8924
8925
if (GTEST_FLAG(death_test_style) == "threadsafe") {
8926
*test = new ExecDeathTest(statement, regex, file, line);
8927
} else if (GTEST_FLAG(death_test_style) == "fast") {
8928
*test = new NoExecDeathTest(statement, regex);
8929
}
8930
8931
# endif // GTEST_OS_WINDOWS
8932
8933
else { // NOLINT - this is more readable than unbalanced brackets inside #if.
8934
DeathTest::set_last_death_test_message(
8935
"Unknown death test style \"" + GTEST_FLAG(death_test_style)
8936
+ "\" encountered");
8937
return false;
8938
}
8939
8940
return true;
8941
}
8942
8943
# if GTEST_OS_WINDOWS
8944
// Recreates the pipe and event handles from the provided parameters,
8945
// signals the event, and returns a file descriptor wrapped around the pipe
8946
// handle. This function is called in the child process only.
8947
static int GetStatusFileDescriptor(unsigned int parent_process_id,
8948
size_t write_handle_as_size_t,
8949
size_t event_handle_as_size_t) {
8950
AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
8951
FALSE, // Non-inheritable.
8952
parent_process_id));
8953
if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
8954
DeathTestAbort("Unable to open parent process " +
8955
StreamableToString(parent_process_id));
8956
}
8957
8958
// FIXME: Replace the following check with a
8959
// compile-time assertion when available.
8960
GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
8961
8962
const HANDLE write_handle =
8963
reinterpret_cast<HANDLE>(write_handle_as_size_t);
8964
HANDLE dup_write_handle;
8965
8966
// The newly initialized handle is accessible only in the parent
8967
// process. To obtain one accessible within the child, we need to use
8968
// DuplicateHandle.
8969
if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
8970
::GetCurrentProcess(), &dup_write_handle,
8971
0x0, // Requested privileges ignored since
8972
// DUPLICATE_SAME_ACCESS is used.
8973
FALSE, // Request non-inheritable handler.
8974
DUPLICATE_SAME_ACCESS)) {
8975
DeathTestAbort("Unable to duplicate the pipe handle " +
8976
StreamableToString(write_handle_as_size_t) +
8977
" from the parent process " +
8978
StreamableToString(parent_process_id));
8979
}
8980
8981
const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
8982
HANDLE dup_event_handle;
8983
8984
if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
8985
::GetCurrentProcess(), &dup_event_handle,
8986
0x0,
8987
FALSE,
8988
DUPLICATE_SAME_ACCESS)) {
8989
DeathTestAbort("Unable to duplicate the event handle " +
8990
StreamableToString(event_handle_as_size_t) +
8991
" from the parent process " +
8992
StreamableToString(parent_process_id));
8993
}
8994
8995
const int write_fd =
8996
::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
8997
if (write_fd == -1) {
8998
DeathTestAbort("Unable to convert pipe handle " +
8999
StreamableToString(write_handle_as_size_t) +
9000
" to a file descriptor");
9001
}
9002
9003
// Signals the parent that the write end of the pipe has been acquired
9004
// so the parent can release its own write end.
9005
::SetEvent(dup_event_handle);
9006
9007
return write_fd;
9008
}
9009
# endif // GTEST_OS_WINDOWS
9010
9011
// Returns a newly created InternalRunDeathTestFlag object with fields
9012
// initialized from the GTEST_FLAG(internal_run_death_test) flag if
9013
// the flag is specified; otherwise returns NULL.
9014
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
9015
if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
9016
9017
// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
9018
// can use it here.
9019
int line = -1;
9020
int index = -1;
9021
::std::vector< ::std::string> fields;
9022
SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
9023
int write_fd = -1;
9024
9025
# if GTEST_OS_WINDOWS
9026
9027
unsigned int parent_process_id = 0;
9028
size_t write_handle_as_size_t = 0;
9029
size_t event_handle_as_size_t = 0;
9030
9031
if (fields.size() != 6
9032
|| !ParseNaturalNumber(fields[1], &line)
9033
|| !ParseNaturalNumber(fields[2], &index)
9034
|| !ParseNaturalNumber(fields[3], &parent_process_id)
9035
|| !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
9036
|| !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
9037
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
9038
GTEST_FLAG(internal_run_death_test));
9039
}
9040
write_fd = GetStatusFileDescriptor(parent_process_id,
9041
write_handle_as_size_t,
9042
event_handle_as_size_t);
9043
9044
# elif GTEST_OS_FUCHSIA
9045
9046
if (fields.size() != 3
9047
|| !ParseNaturalNumber(fields[1], &line)
9048
|| !ParseNaturalNumber(fields[2], &index)) {
9049
DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9050
+ GTEST_FLAG(internal_run_death_test));
9051
}
9052
9053
# else
9054
9055
if (fields.size() != 4
9056
|| !ParseNaturalNumber(fields[1], &line)
9057
|| !ParseNaturalNumber(fields[2], &index)
9058
|| !ParseNaturalNumber(fields[3], &write_fd)) {
9059
DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9060
+ GTEST_FLAG(internal_run_death_test));
9061
}
9062
9063
# endif // GTEST_OS_WINDOWS
9064
9065
return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
9066
}
9067
9068
} // namespace internal
9069
9070
#endif // GTEST_HAS_DEATH_TEST
9071
9072
} // namespace testing
9073
// Copyright 2008, Google Inc.
9074
// All rights reserved.
9075
//
9076
// Redistribution and use in source and binary forms, with or without
9077
// modification, are permitted provided that the following conditions are
9078
// met:
9079
//
9080
// * Redistributions of source code must retain the above copyright
9081
// notice, this list of conditions and the following disclaimer.
9082
// * Redistributions in binary form must reproduce the above
9083
// copyright notice, this list of conditions and the following disclaimer
9084
// in the documentation and/or other materials provided with the
9085
// distribution.
9086
// * Neither the name of Google Inc. nor the names of its
9087
// contributors may be used to endorse or promote products derived from
9088
// this software without specific prior written permission.
9089
//
9090
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9091
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9092
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9093
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9094
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9095
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9096
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9097
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9098
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9099
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9100
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9101
9102
9103
#include <stdlib.h>
9104
9105
#if GTEST_OS_WINDOWS_MOBILE
9106
# include <windows.h>
9107
#elif GTEST_OS_WINDOWS
9108
# include <direct.h>
9109
# include <io.h>
9110
#elif GTEST_OS_SYMBIAN
9111
// Symbian OpenC has PATH_MAX in sys/syslimits.h
9112
# include <sys/syslimits.h>
9113
#else
9114
# include <limits.h>
9115
# include <climits> // Some Linux distributions define PATH_MAX here.
9116
#endif // GTEST_OS_WINDOWS_MOBILE
9117
9118
9119
#if GTEST_OS_WINDOWS
9120
# define GTEST_PATH_MAX_ _MAX_PATH
9121
#elif defined(PATH_MAX)
9122
# define GTEST_PATH_MAX_ PATH_MAX
9123
#elif defined(_XOPEN_PATH_MAX)
9124
# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
9125
#else
9126
# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
9127
#endif // GTEST_OS_WINDOWS
9128
9129
namespace testing {
9130
namespace internal {
9131
9132
#if GTEST_OS_WINDOWS
9133
// On Windows, '\\' is the standard path separator, but many tools and the
9134
// Windows API also accept '/' as an alternate path separator. Unless otherwise
9135
// noted, a file path can contain either kind of path separators, or a mixture
9136
// of them.
9137
const char kPathSeparator = '\\';
9138
const char kAlternatePathSeparator = '/';
9139
//const char kPathSeparatorString[] = "\\";
9140
const char kAlternatePathSeparatorString[] = "/";
9141
# if GTEST_OS_WINDOWS_MOBILE
9142
// Windows CE doesn't have a current directory. You should not use
9143
// the current directory in tests on Windows CE, but this at least
9144
// provides a reasonable fallback.
9145
const char kCurrentDirectoryString[] = "\\";
9146
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
9147
const DWORD kInvalidFileAttributes = 0xffffffff;
9148
# else
9149
const char kCurrentDirectoryString[] = ".\\";
9150
# endif // GTEST_OS_WINDOWS_MOBILE
9151
#else
9152
const char kPathSeparator = '/';
9153
//const char kPathSeparatorString[] = "/";
9154
const char kCurrentDirectoryString[] = "./";
9155
#endif // GTEST_OS_WINDOWS
9156
9157
// Returns whether the given character is a valid path separator.
9158
static bool IsPathSeparator(char c) {
9159
#if GTEST_HAS_ALT_PATH_SEP_
9160
return (c == kPathSeparator) || (c == kAlternatePathSeparator);
9161
#else
9162
return c == kPathSeparator;
9163
#endif
9164
}
9165
9166
// Returns the current working directory, or "" if unsuccessful.
9167
FilePath FilePath::GetCurrentDir() {
9168
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
9169
// Windows CE doesn't have a current directory, so we just return
9170
// something reasonable.
9171
return FilePath(kCurrentDirectoryString);
9172
#elif GTEST_OS_WINDOWS
9173
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9174
return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
9175
#else
9176
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9177
char* result = getcwd(cwd, sizeof(cwd));
9178
# if GTEST_OS_NACL
9179
// getcwd will likely fail in NaCl due to the sandbox, so return something
9180
// reasonable. The user may have provided a shim implementation for getcwd,
9181
// however, so fallback only when failure is detected.
9182
return FilePath(result == NULL ? kCurrentDirectoryString : cwd);
9183
# endif // GTEST_OS_NACL
9184
return FilePath(result == NULL ? "" : cwd);
9185
#endif // GTEST_OS_WINDOWS_MOBILE
9186
}
9187
9188
// Returns a copy of the FilePath with the case-insensitive extension removed.
9189
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
9190
// FilePath("dir/file"). If a case-insensitive extension is not
9191
// found, returns a copy of the original FilePath.
9192
FilePath FilePath::RemoveExtension(const char* extension) const {
9193
const std::string dot_extension = std::string(".") + extension;
9194
if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
9195
return FilePath(pathname_.substr(
9196
0, pathname_.length() - dot_extension.length()));
9197
}
9198
return *this;
9199
}
9200
9201
// Returns a pointer to the last occurrence of a valid path separator in
9202
// the FilePath. On Windows, for example, both '/' and '\' are valid path
9203
// separators. Returns NULL if no path separator was found.
9204
const char* FilePath::FindLastPathSeparator() const {
9205
const char* const last_sep = strrchr(c_str(), kPathSeparator);
9206
#if GTEST_HAS_ALT_PATH_SEP_
9207
const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
9208
// Comparing two pointers of which only one is NULL is undefined.
9209
if (last_alt_sep != NULL &&
9210
(last_sep == NULL || last_alt_sep > last_sep)) {
9211
return last_alt_sep;
9212
}
9213
#endif
9214
return last_sep;
9215
}
9216
9217
// Returns a copy of the FilePath with the directory part removed.
9218
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
9219
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
9220
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
9221
// returns an empty FilePath ("").
9222
// On Windows platform, '\' is the path separator, otherwise it is '/'.
9223
FilePath FilePath::RemoveDirectoryName() const {
9224
const char* const last_sep = FindLastPathSeparator();
9225
return last_sep ? FilePath(last_sep + 1) : *this;
9226
}
9227
9228
// RemoveFileName returns the directory path with the filename removed.
9229
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
9230
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
9231
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
9232
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
9233
// On Windows platform, '\' is the path separator, otherwise it is '/'.
9234
FilePath FilePath::RemoveFileName() const {
9235
const char* const last_sep = FindLastPathSeparator();
9236
std::string dir;
9237
if (last_sep) {
9238
dir = std::string(c_str(), last_sep + 1 - c_str());
9239
} else {
9240
dir = kCurrentDirectoryString;
9241
}
9242
return FilePath(dir);
9243
}
9244
9245
// Helper functions for naming files in a directory for xml output.
9246
9247
// Given directory = "dir", base_name = "test", number = 0,
9248
// extension = "xml", returns "dir/test.xml". If number is greater
9249
// than zero (e.g., 12), returns "dir/test_12.xml".
9250
// On Windows platform, uses \ as the separator rather than /.
9251
FilePath FilePath::MakeFileName(const FilePath& directory,
9252
const FilePath& base_name,
9253
int number,
9254
const char* extension) {
9255
std::string file;
9256
if (number == 0) {
9257
file = base_name.string() + "." + extension;
9258
} else {
9259
file = base_name.string() + "_" + StreamableToString(number)
9260
+ "." + extension;
9261
}
9262
return ConcatPaths(directory, FilePath(file));
9263
}
9264
9265
// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
9266
// On Windows, uses \ as the separator rather than /.
9267
FilePath FilePath::ConcatPaths(const FilePath& directory,
9268
const FilePath& relative_path) {
9269
if (directory.IsEmpty())
9270
return relative_path;
9271
const FilePath dir(directory.RemoveTrailingPathSeparator());
9272
return FilePath(dir.string() + kPathSeparator + relative_path.string());
9273
}
9274
9275
// Returns true if pathname describes something findable in the file-system,
9276
// either a file, directory, or whatever.
9277
bool FilePath::FileOrDirectoryExists() const {
9278
#if GTEST_OS_WINDOWS_MOBILE
9279
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
9280
const DWORD attributes = GetFileAttributes(unicode);
9281
delete [] unicode;
9282
return attributes != kInvalidFileAttributes;
9283
#else
9284
posix::StatStruct file_stat;
9285
return posix::Stat(pathname_.c_str(), &file_stat) == 0;
9286
#endif // GTEST_OS_WINDOWS_MOBILE
9287
}
9288
9289
// Returns true if pathname describes a directory in the file-system
9290
// that exists.
9291
bool FilePath::DirectoryExists() const {
9292
bool result = false;
9293
#if GTEST_OS_WINDOWS
9294
// Don't strip off trailing separator if path is a root directory on
9295
// Windows (like "C:\\").
9296
const FilePath& path(IsRootDirectory() ? *this :
9297
RemoveTrailingPathSeparator());
9298
#else
9299
const FilePath& path(*this);
9300
#endif
9301
9302
#if GTEST_OS_WINDOWS_MOBILE
9303
LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
9304
const DWORD attributes = GetFileAttributes(unicode);
9305
delete [] unicode;
9306
if ((attributes != kInvalidFileAttributes) &&
9307
(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
9308
result = true;
9309
}
9310
#else
9311
posix::StatStruct file_stat;
9312
result = posix::Stat(path.c_str(), &file_stat) == 0 &&
9313
posix::IsDir(file_stat);
9314
#endif // GTEST_OS_WINDOWS_MOBILE
9315
9316
return result;
9317
}
9318
9319
// Returns true if pathname describes a root directory. (Windows has one
9320
// root directory per disk drive.)
9321
bool FilePath::IsRootDirectory() const {
9322
#if GTEST_OS_WINDOWS
9323
// FIXME: on Windows a network share like
9324
// \\server\share can be a root directory, although it cannot be the
9325
// current directory. Handle this properly.
9326
return pathname_.length() == 3 && IsAbsolutePath();
9327
#else
9328
return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
9329
#endif
9330
}
9331
9332
// Returns true if pathname describes an absolute path.
9333
bool FilePath::IsAbsolutePath() const {
9334
const char* const name = pathname_.c_str();
9335
#if GTEST_OS_WINDOWS
9336
return pathname_.length() >= 3 &&
9337
((name[0] >= 'a' && name[0] <= 'z') ||
9338
(name[0] >= 'A' && name[0] <= 'Z')) &&
9339
name[1] == ':' &&
9340
IsPathSeparator(name[2]);
9341
#else
9342
return IsPathSeparator(name[0]);
9343
#endif
9344
}
9345
9346
// Returns a pathname for a file that does not currently exist. The pathname
9347
// will be directory/base_name.extension or
9348
// directory/base_name_<number>.extension if directory/base_name.extension
9349
// already exists. The number will be incremented until a pathname is found
9350
// that does not already exist.
9351
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
9352
// There could be a race condition if two or more processes are calling this
9353
// function at the same time -- they could both pick the same filename.
9354
FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
9355
const FilePath& base_name,
9356
const char* extension) {
9357
FilePath full_pathname;
9358
int number = 0;
9359
do {
9360
full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
9361
} while (full_pathname.FileOrDirectoryExists());
9362
return full_pathname;
9363
}
9364
9365
// Returns true if FilePath ends with a path separator, which indicates that
9366
// it is intended to represent a directory. Returns false otherwise.
9367
// This does NOT check that a directory (or file) actually exists.
9368
bool FilePath::IsDirectory() const {
9369
return !pathname_.empty() &&
9370
IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
9371
}
9372
9373
// Create directories so that path exists. Returns true if successful or if
9374
// the directories already exist; returns false if unable to create directories
9375
// for any reason.
9376
bool FilePath::CreateDirectoriesRecursively() const {
9377
if (!this->IsDirectory()) {
9378
return false;
9379
}
9380
9381
if (pathname_.length() == 0 || this->DirectoryExists()) {
9382
return true;
9383
}
9384
9385
const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
9386
return parent.CreateDirectoriesRecursively() && this->CreateFolder();
9387
}
9388
9389
// Create the directory so that path exists. Returns true if successful or
9390
// if the directory already exists; returns false if unable to create the
9391
// directory for any reason, including if the parent directory does not
9392
// exist. Not named "CreateDirectory" because that's a macro on Windows.
9393
bool FilePath::CreateFolder() const {
9394
#if GTEST_OS_WINDOWS_MOBILE
9395
FilePath removed_sep(this->RemoveTrailingPathSeparator());
9396
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
9397
int result = CreateDirectory(unicode, NULL) ? 0 : -1;
9398
delete [] unicode;
9399
#elif GTEST_OS_WINDOWS
9400
int result = _mkdir(pathname_.c_str());
9401
#else
9402
int result = mkdir(pathname_.c_str(), 0777);
9403
#endif // GTEST_OS_WINDOWS_MOBILE
9404
9405
if (result == -1) {
9406
return this->DirectoryExists(); // An error is OK if the directory exists.
9407
}
9408
return true; // No error.
9409
}
9410
9411
// If input name has a trailing separator character, remove it and return the
9412
// name, otherwise return the name string unmodified.
9413
// On Windows platform, uses \ as the separator, other platforms use /.
9414
FilePath FilePath::RemoveTrailingPathSeparator() const {
9415
return IsDirectory()
9416
? FilePath(pathname_.substr(0, pathname_.length() - 1))
9417
: *this;
9418
}
9419
9420
// Removes any redundant separators that might be in the pathname.
9421
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
9422
// redundancies that might be in a pathname involving "." or "..".
9423
// FIXME: handle Windows network shares (e.g. \\server\share).
9424
void FilePath::Normalize() {
9425
if (pathname_.c_str() == NULL) {
9426
pathname_ = "";
9427
return;
9428
}
9429
const char* src = pathname_.c_str();
9430
char* const dest = new char[pathname_.length() + 1];
9431
char* dest_ptr = dest;
9432
memset(dest_ptr, 0, pathname_.length() + 1);
9433
9434
while (*src != '\0') {
9435
*dest_ptr = *src;
9436
if (!IsPathSeparator(*src)) {
9437
src++;
9438
} else {
9439
#if GTEST_HAS_ALT_PATH_SEP_
9440
if (*dest_ptr == kAlternatePathSeparator) {
9441
*dest_ptr = kPathSeparator;
9442
}
9443
#endif
9444
while (IsPathSeparator(*src))
9445
src++;
9446
}
9447
dest_ptr++;
9448
}
9449
*dest_ptr = '\0';
9450
pathname_ = dest;
9451
delete[] dest;
9452
}
9453
9454
} // namespace internal
9455
} // namespace testing
9456
// Copyright 2008, Google Inc.
9457
// All rights reserved.
9458
//
9459
// Redistribution and use in source and binary forms, with or without
9460
// modification, are permitted provided that the following conditions are
9461
// met:
9462
//
9463
// * Redistributions of source code must retain the above copyright
9464
// notice, this list of conditions and the following disclaimer.
9465
// * Redistributions in binary form must reproduce the above
9466
// copyright notice, this list of conditions and the following disclaimer
9467
// in the documentation and/or other materials provided with the
9468
// distribution.
9469
// * Neither the name of Google Inc. nor the names of its
9470
// contributors may be used to endorse or promote products derived from
9471
// this software without specific prior written permission.
9472
//
9473
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9474
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9475
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9476
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9477
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9478
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9479
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9480
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9481
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9482
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9483
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9484
9485
9486
9487
#include <limits.h>
9488
#include <stdlib.h>
9489
#include <stdio.h>
9490
#include <string.h>
9491
#include <fstream>
9492
9493
#if GTEST_OS_WINDOWS
9494
# include <windows.h>
9495
# include <io.h>
9496
# include <sys/stat.h>
9497
# include <map> // Used in ThreadLocal.
9498
#else
9499
# include <unistd.h>
9500
#endif // GTEST_OS_WINDOWS
9501
9502
#if GTEST_OS_MAC
9503
# include <mach/mach_init.h>
9504
# include <mach/task.h>
9505
# include <mach/vm_map.h>
9506
#endif // GTEST_OS_MAC
9507
9508
#if GTEST_OS_QNX
9509
# include <devctl.h>
9510
# include <fcntl.h>
9511
# include <sys/procfs.h>
9512
#endif // GTEST_OS_QNX
9513
9514
#if GTEST_OS_AIX
9515
# include <procinfo.h>
9516
# include <sys/types.h>
9517
#endif // GTEST_OS_AIX
9518
9519
#if GTEST_OS_FUCHSIA
9520
# include <zircon/process.h>
9521
# include <zircon/syscalls.h>
9522
#endif // GTEST_OS_FUCHSIA
9523
9524
9525
namespace testing {
9526
namespace internal {
9527
9528
#if defined(_MSC_VER) || defined(__BORLANDC__)
9529
// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
9530
const int kStdOutFileno = 1;
9531
const int kStdErrFileno = 2;
9532
#else
9533
const int kStdOutFileno = STDOUT_FILENO;
9534
const int kStdErrFileno = STDERR_FILENO;
9535
#endif // _MSC_VER
9536
9537
#if GTEST_OS_LINUX
9538
9539
namespace {
9540
template <typename T>
9541
T ReadProcFileField(const std::string& filename, int field) {
9542
std::string dummy;
9543
std::ifstream file(filename.c_str());
9544
while (field-- > 0) {
9545
file >> dummy;
9546
}
9547
T output = 0;
9548
file >> output;
9549
return output;
9550
}
9551
} // namespace
9552
9553
// Returns the number of active threads, or 0 when there is an error.
9554
size_t GetThreadCount() {
9555
const std::string filename =
9556
(Message() << "/proc/" << getpid() << "/stat").GetString();
9557
return ReadProcFileField<int>(filename, 19);
9558
}
9559
9560
#elif GTEST_OS_MAC
9561
9562
size_t GetThreadCount() {
9563
const task_t task = mach_task_self();
9564
mach_msg_type_number_t thread_count;
9565
thread_act_array_t thread_list;
9566
const kern_return_t status = task_threads(task, &thread_list, &thread_count);
9567
if (status == KERN_SUCCESS) {
9568
// task_threads allocates resources in thread_list and we need to free them
9569
// to avoid leaks.
9570
vm_deallocate(task,
9571
reinterpret_cast<vm_address_t>(thread_list),
9572
sizeof(thread_t) * thread_count);
9573
return static_cast<size_t>(thread_count);
9574
} else {
9575
return 0;
9576
}
9577
}
9578
9579
#elif GTEST_OS_QNX
9580
9581
// Returns the number of threads running in the process, or 0 to indicate that
9582
// we cannot detect it.
9583
size_t GetThreadCount() {
9584
const int fd = open("/proc/self/as", O_RDONLY);
9585
if (fd < 0) {
9586
return 0;
9587
}
9588
procfs_info process_info;
9589
const int status =
9590
devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
9591
close(fd);
9592
if (status == EOK) {
9593
return static_cast<size_t>(process_info.num_threads);
9594
} else {
9595
return 0;
9596
}
9597
}
9598
9599
#elif GTEST_OS_AIX
9600
9601
size_t GetThreadCount() {
9602
struct procentry64 entry;
9603
pid_t pid = getpid();
9604
int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1);
9605
if (status == 1) {
9606
return entry.pi_thcount;
9607
} else {
9608
return 0;
9609
}
9610
}
9611
9612
#elif GTEST_OS_FUCHSIA
9613
9614
size_t GetThreadCount() {
9615
int dummy_buffer;
9616
size_t avail;
9617
zx_status_t status = zx_object_get_info(
9618
zx_process_self(),
9619
ZX_INFO_PROCESS_THREADS,
9620
&dummy_buffer,
9621
0,
9622
nullptr,
9623
&avail);
9624
if (status == ZX_OK) {
9625
return avail;
9626
} else {
9627
return 0;
9628
}
9629
}
9630
9631
#else
9632
9633
size_t GetThreadCount() {
9634
// There's no portable way to detect the number of threads, so we just
9635
// return 0 to indicate that we cannot detect it.
9636
return 0;
9637
}
9638
9639
#endif // GTEST_OS_LINUX
9640
9641
#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
9642
9643
void SleepMilliseconds(int n) {
9644
::Sleep(n);
9645
}
9646
9647
AutoHandle::AutoHandle()
9648
: handle_(INVALID_HANDLE_VALUE) {}
9649
9650
AutoHandle::AutoHandle(Handle handle)
9651
: handle_(handle) {}
9652
9653
AutoHandle::~AutoHandle() {
9654
Reset();
9655
}
9656
9657
AutoHandle::Handle AutoHandle::Get() const {
9658
return handle_;
9659
}
9660
9661
void AutoHandle::Reset() {
9662
Reset(INVALID_HANDLE_VALUE);
9663
}
9664
9665
void AutoHandle::Reset(HANDLE handle) {
9666
// Resetting with the same handle we already own is invalid.
9667
if (handle_ != handle) {
9668
if (IsCloseable()) {
9669
::CloseHandle(handle_);
9670
}
9671
handle_ = handle;
9672
} else {
9673
GTEST_CHECK_(!IsCloseable())
9674
<< "Resetting a valid handle to itself is likely a programmer error "
9675
"and thus not allowed.";
9676
}
9677
}
9678
9679
bool AutoHandle::IsCloseable() const {
9680
// Different Windows APIs may use either of these values to represent an
9681
// invalid handle.
9682
return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
9683
}
9684
9685
Notification::Notification()
9686
: event_(::CreateEvent(NULL, // Default security attributes.
9687
TRUE, // Do not reset automatically.
9688
FALSE, // Initially unset.
9689
NULL)) { // Anonymous event.
9690
GTEST_CHECK_(event_.Get() != NULL);
9691
}
9692
9693
void Notification::Notify() {
9694
GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
9695
}
9696
9697
void Notification::WaitForNotification() {
9698
GTEST_CHECK_(
9699
::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
9700
}
9701
9702
Mutex::Mutex()
9703
: owner_thread_id_(0),
9704
type_(kDynamic),
9705
critical_section_init_phase_(0),
9706
critical_section_(new CRITICAL_SECTION) {
9707
::InitializeCriticalSection(critical_section_);
9708
}
9709
9710
Mutex::~Mutex() {
9711
// Static mutexes are leaked intentionally. It is not thread-safe to try
9712
// to clean them up.
9713
// FIXME: Switch to Slim Reader/Writer (SRW) Locks, which requires
9714
// nothing to clean it up but is available only on Vista and later.
9715
// https://docs.microsoft.com/en-us/windows/desktop/Sync/slim-reader-writer--srw--locks
9716
if (type_ == kDynamic) {
9717
::DeleteCriticalSection(critical_section_);
9718
delete critical_section_;
9719
critical_section_ = NULL;
9720
}
9721
}
9722
9723
void Mutex::Lock() {
9724
ThreadSafeLazyInit();
9725
::EnterCriticalSection(critical_section_);
9726
owner_thread_id_ = ::GetCurrentThreadId();
9727
}
9728
9729
void Mutex::Unlock() {
9730
ThreadSafeLazyInit();
9731
// We don't protect writing to owner_thread_id_ here, as it's the
9732
// caller's responsibility to ensure that the current thread holds the
9733
// mutex when this is called.
9734
owner_thread_id_ = 0;
9735
::LeaveCriticalSection(critical_section_);
9736
}
9737
9738
// Does nothing if the current thread holds the mutex. Otherwise, crashes
9739
// with high probability.
9740
void Mutex::AssertHeld() {
9741
ThreadSafeLazyInit();
9742
GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
9743
<< "The current thread is not holding the mutex @" << this;
9744
}
9745
9746
namespace {
9747
9748
// Use the RAII idiom to flag mem allocs that are intentionally never
9749
// deallocated. The motivation is to silence the false positive mem leaks
9750
// that are reported by the debug version of MS's CRT which can only detect
9751
// if an alloc is missing a matching deallocation.
9752
// Example:
9753
// MemoryIsNotDeallocated memory_is_not_deallocated;
9754
// critical_section_ = new CRITICAL_SECTION;
9755
//
9756
class MemoryIsNotDeallocated
9757
{
9758
public:
9759
MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
9760
#ifdef _MSC_VER
9761
old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
9762
// Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
9763
// doesn't report mem leak if there's no matching deallocation.
9764
_CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
9765
#endif // _MSC_VER
9766
}
9767
9768
~MemoryIsNotDeallocated() {
9769
#ifdef _MSC_VER
9770
// Restore the original _CRTDBG_ALLOC_MEM_DF flag
9771
_CrtSetDbgFlag(old_crtdbg_flag_);
9772
#endif // _MSC_VER
9773
}
9774
9775
private:
9776
int old_crtdbg_flag_;
9777
9778
GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
9779
};
9780
9781
} // namespace
9782
9783
// Initializes owner_thread_id_ and critical_section_ in static mutexes.
9784
void Mutex::ThreadSafeLazyInit() {
9785
// Dynamic mutexes are initialized in the constructor.
9786
if (type_ == kStatic) {
9787
switch (
9788
::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
9789
case 0:
9790
// If critical_section_init_phase_ was 0 before the exchange, we
9791
// are the first to test it and need to perform the initialization.
9792
owner_thread_id_ = 0;
9793
{
9794
// Use RAII to flag that following mem alloc is never deallocated.
9795
MemoryIsNotDeallocated memory_is_not_deallocated;
9796
critical_section_ = new CRITICAL_SECTION;
9797
}
9798
::InitializeCriticalSection(critical_section_);
9799
// Updates the critical_section_init_phase_ to 2 to signal
9800
// initialization complete.
9801
GTEST_CHECK_(::InterlockedCompareExchange(
9802
&critical_section_init_phase_, 2L, 1L) ==
9803
1L);
9804
break;
9805
case 1:
9806
// Somebody else is already initializing the mutex; spin until they
9807
// are done.
9808
while (::InterlockedCompareExchange(&critical_section_init_phase_,
9809
2L,
9810
2L) != 2L) {
9811
// Possibly yields the rest of the thread's time slice to other
9812
// threads.
9813
::Sleep(0);
9814
}
9815
break;
9816
9817
case 2:
9818
break; // The mutex is already initialized and ready for use.
9819
9820
default:
9821
GTEST_CHECK_(false)
9822
<< "Unexpected value of critical_section_init_phase_ "
9823
<< "while initializing a static mutex.";
9824
}
9825
}
9826
}
9827
9828
namespace {
9829
9830
class ThreadWithParamSupport : public ThreadWithParamBase {
9831
public:
9832
static HANDLE CreateThread(Runnable* runnable,
9833
Notification* thread_can_start) {
9834
ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
9835
DWORD thread_id;
9836
// FIXME: Consider to use _beginthreadex instead.
9837
HANDLE thread_handle = ::CreateThread(
9838
NULL, // Default security.
9839
0, // Default stack size.
9840
&ThreadWithParamSupport::ThreadMain,
9841
param, // Parameter to ThreadMainStatic
9842
0x0, // Default creation flags.
9843
&thread_id); // Need a valid pointer for the call to work under Win98.
9844
GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
9845
<< ::GetLastError() << ".";
9846
if (thread_handle == NULL) {
9847
delete param;
9848
}
9849
return thread_handle;
9850
}
9851
9852
private:
9853
struct ThreadMainParam {
9854
ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
9855
: runnable_(runnable),
9856
thread_can_start_(thread_can_start) {
9857
}
9858
scoped_ptr<Runnable> runnable_;
9859
// Does not own.
9860
Notification* thread_can_start_;
9861
};
9862
9863
static DWORD WINAPI ThreadMain(void* ptr) {
9864
// Transfers ownership.
9865
scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
9866
if (param->thread_can_start_ != NULL)
9867
param->thread_can_start_->WaitForNotification();
9868
param->runnable_->Run();
9869
return 0;
9870
}
9871
9872
// Prohibit instantiation.
9873
ThreadWithParamSupport();
9874
9875
GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
9876
};
9877
9878
} // namespace
9879
9880
ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
9881
Notification* thread_can_start)
9882
: thread_(ThreadWithParamSupport::CreateThread(runnable,
9883
thread_can_start)) {
9884
}
9885
9886
ThreadWithParamBase::~ThreadWithParamBase() {
9887
Join();
9888
}
9889
9890
void ThreadWithParamBase::Join() {
9891
GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
9892
<< "Failed to join the thread with error " << ::GetLastError() << ".";
9893
}
9894
9895
// Maps a thread to a set of ThreadIdToThreadLocals that have values
9896
// instantiated on that thread and notifies them when the thread exits. A
9897
// ThreadLocal instance is expected to persist until all threads it has
9898
// values on have terminated.
9899
class ThreadLocalRegistryImpl {
9900
public:
9901
// Registers thread_local_instance as having value on the current thread.
9902
// Returns a value that can be used to identify the thread from other threads.
9903
static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
9904
const ThreadLocalBase* thread_local_instance) {
9905
DWORD current_thread = ::GetCurrentThreadId();
9906
MutexLock lock(&mutex_);
9907
ThreadIdToThreadLocals* const thread_to_thread_locals =
9908
GetThreadLocalsMapLocked();
9909
ThreadIdToThreadLocals::iterator thread_local_pos =
9910
thread_to_thread_locals->find(current_thread);
9911
if (thread_local_pos == thread_to_thread_locals->end()) {
9912
thread_local_pos = thread_to_thread_locals->insert(
9913
std::make_pair(current_thread, ThreadLocalValues())).first;
9914
StartWatcherThreadFor(current_thread);
9915
}
9916
ThreadLocalValues& thread_local_values = thread_local_pos->second;
9917
ThreadLocalValues::iterator value_pos =
9918
thread_local_values.find(thread_local_instance);
9919
if (value_pos == thread_local_values.end()) {
9920
value_pos =
9921
thread_local_values
9922
.insert(std::make_pair(
9923
thread_local_instance,
9924
linked_ptr<ThreadLocalValueHolderBase>(
9925
thread_local_instance->NewValueForCurrentThread())))
9926
.first;
9927
}
9928
return value_pos->second.get();
9929
}
9930
9931
static void OnThreadLocalDestroyed(
9932
const ThreadLocalBase* thread_local_instance) {
9933
std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
9934
// Clean up the ThreadLocalValues data structure while holding the lock, but
9935
// defer the destruction of the ThreadLocalValueHolderBases.
9936
{
9937
MutexLock lock(&mutex_);
9938
ThreadIdToThreadLocals* const thread_to_thread_locals =
9939
GetThreadLocalsMapLocked();
9940
for (ThreadIdToThreadLocals::iterator it =
9941
thread_to_thread_locals->begin();
9942
it != thread_to_thread_locals->end();
9943
++it) {
9944
ThreadLocalValues& thread_local_values = it->second;
9945
ThreadLocalValues::iterator value_pos =
9946
thread_local_values.find(thread_local_instance);
9947
if (value_pos != thread_local_values.end()) {
9948
value_holders.push_back(value_pos->second);
9949
thread_local_values.erase(value_pos);
9950
// This 'if' can only be successful at most once, so theoretically we
9951
// could break out of the loop here, but we don't bother doing so.
9952
}
9953
}
9954
}
9955
// Outside the lock, let the destructor for 'value_holders' deallocate the
9956
// ThreadLocalValueHolderBases.
9957
}
9958
9959
static void OnThreadExit(DWORD thread_id) {
9960
GTEST_CHECK_(thread_id != 0) << ::GetLastError();
9961
std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
9962
// Clean up the ThreadIdToThreadLocals data structure while holding the
9963
// lock, but defer the destruction of the ThreadLocalValueHolderBases.
9964
{
9965
MutexLock lock(&mutex_);
9966
ThreadIdToThreadLocals* const thread_to_thread_locals =
9967
GetThreadLocalsMapLocked();
9968
ThreadIdToThreadLocals::iterator thread_local_pos =
9969
thread_to_thread_locals->find(thread_id);
9970
if (thread_local_pos != thread_to_thread_locals->end()) {
9971
ThreadLocalValues& thread_local_values = thread_local_pos->second;
9972
for (ThreadLocalValues::iterator value_pos =
9973
thread_local_values.begin();
9974
value_pos != thread_local_values.end();
9975
++value_pos) {
9976
value_holders.push_back(value_pos->second);
9977
}
9978
thread_to_thread_locals->erase(thread_local_pos);
9979
}
9980
}
9981
// Outside the lock, let the destructor for 'value_holders' deallocate the
9982
// ThreadLocalValueHolderBases.
9983
}
9984
9985
private:
9986
// In a particular thread, maps a ThreadLocal object to its value.
9987
typedef std::map<const ThreadLocalBase*,
9988
linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
9989
// Stores all ThreadIdToThreadLocals having values in a thread, indexed by
9990
// thread's ID.
9991
typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
9992
9993
// Holds the thread id and thread handle that we pass from
9994
// StartWatcherThreadFor to WatcherThreadFunc.
9995
typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
9996
9997
static void StartWatcherThreadFor(DWORD thread_id) {
9998
// The returned handle will be kept in thread_map and closed by
9999
// watcher_thread in WatcherThreadFunc.
10000
HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
10001
FALSE,
10002
thread_id);
10003
GTEST_CHECK_(thread != NULL);
10004
// We need to pass a valid thread ID pointer into CreateThread for it
10005
// to work correctly under Win98.
10006
DWORD watcher_thread_id;
10007
HANDLE watcher_thread = ::CreateThread(
10008
NULL, // Default security.
10009
0, // Default stack size
10010
&ThreadLocalRegistryImpl::WatcherThreadFunc,
10011
reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
10012
CREATE_SUSPENDED,
10013
&watcher_thread_id);
10014
GTEST_CHECK_(watcher_thread != NULL);
10015
// Give the watcher thread the same priority as ours to avoid being
10016
// blocked by it.
10017
::SetThreadPriority(watcher_thread,
10018
::GetThreadPriority(::GetCurrentThread()));
10019
::ResumeThread(watcher_thread);
10020
::CloseHandle(watcher_thread);
10021
}
10022
10023
// Monitors exit from a given thread and notifies those
10024
// ThreadIdToThreadLocals about thread termination.
10025
static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
10026
const ThreadIdAndHandle* tah =
10027
reinterpret_cast<const ThreadIdAndHandle*>(param);
10028
GTEST_CHECK_(
10029
::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
10030
OnThreadExit(tah->first);
10031
::CloseHandle(tah->second);
10032
delete tah;
10033
return 0;
10034
}
10035
10036
// Returns map of thread local instances.
10037
static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
10038
mutex_.AssertHeld();
10039
MemoryIsNotDeallocated memory_is_not_deallocated;
10040
static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
10041
return map;
10042
}
10043
10044
// Protects access to GetThreadLocalsMapLocked() and its return value.
10045
static Mutex mutex_;
10046
// Protects access to GetThreadMapLocked() and its return value.
10047
static Mutex thread_map_mutex_;
10048
};
10049
10050
Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
10051
Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
10052
10053
ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
10054
const ThreadLocalBase* thread_local_instance) {
10055
return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
10056
thread_local_instance);
10057
}
10058
10059
void ThreadLocalRegistry::OnThreadLocalDestroyed(
10060
const ThreadLocalBase* thread_local_instance) {
10061
ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
10062
}
10063
10064
#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
10065
10066
#if GTEST_USES_POSIX_RE
10067
10068
// Implements RE. Currently only needed for death tests.
10069
10070
RE::~RE() {
10071
if (is_valid_) {
10072
// regfree'ing an invalid regex might crash because the content
10073
// of the regex is undefined. Since the regex's are essentially
10074
// the same, one cannot be valid (or invalid) without the other
10075
// being so too.
10076
regfree(&partial_regex_);
10077
regfree(&full_regex_);
10078
}
10079
free(const_cast<char*>(pattern_));
10080
}
10081
10082
// Returns true iff regular expression re matches the entire str.
10083
bool RE::FullMatch(const char* str, const RE& re) {
10084
if (!re.is_valid_) return false;
10085
10086
regmatch_t match;
10087
return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
10088
}
10089
10090
// Returns true iff regular expression re matches a substring of str
10091
// (including str itself).
10092
bool RE::PartialMatch(const char* str, const RE& re) {
10093
if (!re.is_valid_) return false;
10094
10095
regmatch_t match;
10096
return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
10097
}
10098
10099
// Initializes an RE from its string representation.
10100
void RE::Init(const char* regex) {
10101
pattern_ = posix::StrDup(regex);
10102
10103
// Reserves enough bytes to hold the regular expression used for a
10104
// full match.
10105
const size_t full_regex_len = strlen(regex) + 10;
10106
char* const full_pattern = new char[full_regex_len];
10107
10108
snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
10109
is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
10110
// We want to call regcomp(&partial_regex_, ...) even if the
10111
// previous expression returns false. Otherwise partial_regex_ may
10112
// not be properly initialized can may cause trouble when it's
10113
// freed.
10114
//
10115
// Some implementation of POSIX regex (e.g. on at least some
10116
// versions of Cygwin) doesn't accept the empty string as a valid
10117
// regex. We change it to an equivalent form "()" to be safe.
10118
if (is_valid_) {
10119
const char* const partial_regex = (*regex == '\0') ? "()" : regex;
10120
is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
10121
}
10122
EXPECT_TRUE(is_valid_)
10123
<< "Regular expression \"" << regex
10124
<< "\" is not a valid POSIX Extended regular expression.";
10125
10126
delete[] full_pattern;
10127
}
10128
10129
#elif GTEST_USES_SIMPLE_RE
10130
10131
// Returns true iff ch appears anywhere in str (excluding the
10132
// terminating '\0' character).
10133
bool IsInSet(char ch, const char* str) {
10134
return ch != '\0' && strchr(str, ch) != NULL;
10135
}
10136
10137
// Returns true iff ch belongs to the given classification. Unlike
10138
// similar functions in <ctype.h>, these aren't affected by the
10139
// current locale.
10140
bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
10141
bool IsAsciiPunct(char ch) {
10142
return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
10143
}
10144
bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
10145
bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
10146
bool IsAsciiWordChar(char ch) {
10147
return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
10148
('0' <= ch && ch <= '9') || ch == '_';
10149
}
10150
10151
// Returns true iff "\\c" is a supported escape sequence.
10152
bool IsValidEscape(char c) {
10153
return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
10154
}
10155
10156
// Returns true iff the given atom (specified by escaped and pattern)
10157
// matches ch. The result is undefined if the atom is invalid.
10158
bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
10159
if (escaped) { // "\\p" where p is pattern_char.
10160
switch (pattern_char) {
10161
case 'd': return IsAsciiDigit(ch);
10162
case 'D': return !IsAsciiDigit(ch);
10163
case 'f': return ch == '\f';
10164
case 'n': return ch == '\n';
10165
case 'r': return ch == '\r';
10166
case 's': return IsAsciiWhiteSpace(ch);
10167
case 'S': return !IsAsciiWhiteSpace(ch);
10168
case 't': return ch == '\t';
10169
case 'v': return ch == '\v';
10170
case 'w': return IsAsciiWordChar(ch);
10171
case 'W': return !IsAsciiWordChar(ch);
10172
}
10173
return IsAsciiPunct(pattern_char) && pattern_char == ch;
10174
}
10175
10176
return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
10177
}
10178
10179
// Helper function used by ValidateRegex() to format error messages.
10180
static std::string FormatRegexSyntaxError(const char* regex, int index) {
10181
return (Message() << "Syntax error at index " << index
10182
<< " in simple regular expression \"" << regex << "\": ").GetString();
10183
}
10184
10185
// Generates non-fatal failures and returns false if regex is invalid;
10186
// otherwise returns true.
10187
bool ValidateRegex(const char* regex) {
10188
if (regex == NULL) {
10189
// FIXME: fix the source file location in the
10190
// assertion failures to match where the regex is used in user
10191
// code.
10192
ADD_FAILURE() << "NULL is not a valid simple regular expression.";
10193
return false;
10194
}
10195
10196
bool is_valid = true;
10197
10198
// True iff ?, *, or + can follow the previous atom.
10199
bool prev_repeatable = false;
10200
for (int i = 0; regex[i]; i++) {
10201
if (regex[i] == '\\') { // An escape sequence
10202
i++;
10203
if (regex[i] == '\0') {
10204
ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10205
<< "'\\' cannot appear at the end.";
10206
return false;
10207
}
10208
10209
if (!IsValidEscape(regex[i])) {
10210
ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10211
<< "invalid escape sequence \"\\" << regex[i] << "\".";
10212
is_valid = false;
10213
}
10214
prev_repeatable = true;
10215
} else { // Not an escape sequence.
10216
const char ch = regex[i];
10217
10218
if (ch == '^' && i > 0) {
10219
ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10220
<< "'^' can only appear at the beginning.";
10221
is_valid = false;
10222
} else if (ch == '$' && regex[i + 1] != '\0') {
10223
ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10224
<< "'$' can only appear at the end.";
10225
is_valid = false;
10226
} else if (IsInSet(ch, "()[]{}|")) {
10227
ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10228
<< "'" << ch << "' is unsupported.";
10229
is_valid = false;
10230
} else if (IsRepeat(ch) && !prev_repeatable) {
10231
ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10232
<< "'" << ch << "' can only follow a repeatable token.";
10233
is_valid = false;
10234
}
10235
10236
prev_repeatable = !IsInSet(ch, "^$?*+");
10237
}
10238
}
10239
10240
return is_valid;
10241
}
10242
10243
// Matches a repeated regex atom followed by a valid simple regular
10244
// expression. The regex atom is defined as c if escaped is false,
10245
// or \c otherwise. repeat is the repetition meta character (?, *,
10246
// or +). The behavior is undefined if str contains too many
10247
// characters to be indexable by size_t, in which case the test will
10248
// probably time out anyway. We are fine with this limitation as
10249
// std::string has it too.
10250
bool MatchRepetitionAndRegexAtHead(
10251
bool escaped, char c, char repeat, const char* regex,
10252
const char* str) {
10253
const size_t min_count = (repeat == '+') ? 1 : 0;
10254
const size_t max_count = (repeat == '?') ? 1 :
10255
static_cast<size_t>(-1) - 1;
10256
// We cannot call numeric_limits::max() as it conflicts with the
10257
// max() macro on Windows.
10258
10259
for (size_t i = 0; i <= max_count; ++i) {
10260
// We know that the atom matches each of the first i characters in str.
10261
if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
10262
// We have enough matches at the head, and the tail matches too.
10263
// Since we only care about *whether* the pattern matches str
10264
// (as opposed to *how* it matches), there is no need to find a
10265
// greedy match.
10266
return true;
10267
}
10268
if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
10269
return false;
10270
}
10271
return false;
10272
}
10273
10274
// Returns true iff regex matches a prefix of str. regex must be a
10275
// valid simple regular expression and not start with "^", or the
10276
// result is undefined.
10277
bool MatchRegexAtHead(const char* regex, const char* str) {
10278
if (*regex == '\0') // An empty regex matches a prefix of anything.
10279
return true;
10280
10281
// "$" only matches the end of a string. Note that regex being
10282
// valid guarantees that there's nothing after "$" in it.
10283
if (*regex == '$')
10284
return *str == '\0';
10285
10286
// Is the first thing in regex an escape sequence?
10287
const bool escaped = *regex == '\\';
10288
if (escaped)
10289
++regex;
10290
if (IsRepeat(regex[1])) {
10291
// MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
10292
// here's an indirect recursion. It terminates as the regex gets
10293
// shorter in each recursion.
10294
return MatchRepetitionAndRegexAtHead(
10295
escaped, regex[0], regex[1], regex + 2, str);
10296
} else {
10297
// regex isn't empty, isn't "$", and doesn't start with a
10298
// repetition. We match the first atom of regex with the first
10299
// character of str and recurse.
10300
return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
10301
MatchRegexAtHead(regex + 1, str + 1);
10302
}
10303
}
10304
10305
// Returns true iff regex matches any substring of str. regex must be
10306
// a valid simple regular expression, or the result is undefined.
10307
//
10308
// The algorithm is recursive, but the recursion depth doesn't exceed
10309
// the regex length, so we won't need to worry about running out of
10310
// stack space normally. In rare cases the time complexity can be
10311
// exponential with respect to the regex length + the string length,
10312
// but usually it's must faster (often close to linear).
10313
bool MatchRegexAnywhere(const char* regex, const char* str) {
10314
if (regex == NULL || str == NULL)
10315
return false;
10316
10317
if (*regex == '^')
10318
return MatchRegexAtHead(regex + 1, str);
10319
10320
// A successful match can be anywhere in str.
10321
do {
10322
if (MatchRegexAtHead(regex, str))
10323
return true;
10324
} while (*str++ != '\0');
10325
return false;
10326
}
10327
10328
// Implements the RE class.
10329
10330
RE::~RE() {
10331
free(const_cast<char*>(pattern_));
10332
free(const_cast<char*>(full_pattern_));
10333
}
10334
10335
// Returns true iff regular expression re matches the entire str.
10336
bool RE::FullMatch(const char* str, const RE& re) {
10337
return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
10338
}
10339
10340
// Returns true iff regular expression re matches a substring of str
10341
// (including str itself).
10342
bool RE::PartialMatch(const char* str, const RE& re) {
10343
return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
10344
}
10345
10346
// Initializes an RE from its string representation.
10347
void RE::Init(const char* regex) {
10348
pattern_ = full_pattern_ = NULL;
10349
if (regex != NULL) {
10350
pattern_ = posix::StrDup(regex);
10351
}
10352
10353
is_valid_ = ValidateRegex(regex);
10354
if (!is_valid_) {
10355
// No need to calculate the full pattern when the regex is invalid.
10356
return;
10357
}
10358
10359
const size_t len = strlen(regex);
10360
// Reserves enough bytes to hold the regular expression used for a
10361
// full match: we need space to prepend a '^', append a '$', and
10362
// terminate the string with '\0'.
10363
char* buffer = static_cast<char*>(malloc(len + 3));
10364
full_pattern_ = buffer;
10365
10366
if (*regex != '^')
10367
*buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
10368
10369
// We don't use snprintf or strncpy, as they trigger a warning when
10370
// compiled with VC++ 8.0.
10371
memcpy(buffer, regex, len);
10372
buffer += len;
10373
10374
if (len == 0 || regex[len - 1] != '$')
10375
*buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
10376
10377
*buffer = '\0';
10378
}
10379
10380
#endif // GTEST_USES_POSIX_RE
10381
10382
const char kUnknownFile[] = "unknown file";
10383
10384
// Formats a source file path and a line number as they would appear
10385
// in an error message from the compiler used to compile this code.
10386
GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
10387
const std::string file_name(file == NULL ? kUnknownFile : file);
10388
10389
if (line < 0) {
10390
return file_name + ":";
10391
}
10392
#ifdef _MSC_VER
10393
return file_name + "(" + StreamableToString(line) + "):";
10394
#else
10395
return file_name + ":" + StreamableToString(line) + ":";
10396
#endif // _MSC_VER
10397
}
10398
10399
// Formats a file location for compiler-independent XML output.
10400
// Although this function is not platform dependent, we put it next to
10401
// FormatFileLocation in order to contrast the two functions.
10402
// Note that FormatCompilerIndependentFileLocation() does NOT append colon
10403
// to the file location it produces, unlike FormatFileLocation().
10404
GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
10405
const char* file, int line) {
10406
const std::string file_name(file == NULL ? kUnknownFile : file);
10407
10408
if (line < 0)
10409
return file_name;
10410
else
10411
return file_name + ":" + StreamableToString(line);
10412
}
10413
10414
GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
10415
: severity_(severity) {
10416
const char* const marker =
10417
severity == GTEST_INFO ? "[ INFO ]" :
10418
severity == GTEST_WARNING ? "[WARNING]" :
10419
severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
10420
GetStream() << ::std::endl << marker << " "
10421
<< FormatFileLocation(file, line).c_str() << ": ";
10422
}
10423
10424
// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
10425
GTestLog::~GTestLog() {
10426
GetStream() << ::std::endl;
10427
if (severity_ == GTEST_FATAL) {
10428
fflush(stderr);
10429
posix::Abort();
10430
}
10431
}
10432
10433
// Disable Microsoft deprecation warnings for POSIX functions called from
10434
// this class (creat, dup, dup2, and close)
10435
GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
10436
10437
#if GTEST_HAS_STREAM_REDIRECTION
10438
10439
// Object that captures an output stream (stdout/stderr).
10440
class CapturedStream {
10441
public:
10442
// The ctor redirects the stream to a temporary file.
10443
explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
10444
# if GTEST_OS_WINDOWS
10445
char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
10446
char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
10447
10448
::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
10449
const UINT success = ::GetTempFileNameA(temp_dir_path,
10450
"gtest_redir",
10451
0, // Generate unique file name.
10452
temp_file_path);
10453
GTEST_CHECK_(success != 0)
10454
<< "Unable to create a temporary file in " << temp_dir_path;
10455
const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
10456
GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
10457
<< temp_file_path;
10458
filename_ = temp_file_path;
10459
# else
10460
// There's no guarantee that a test has write access to the current
10461
// directory, so we create the temporary file in the /tmp directory
10462
// instead. We use /tmp on most systems, and /sdcard on Android.
10463
// That's because Android doesn't have /tmp.
10464
# if GTEST_OS_LINUX_ANDROID
10465
// Note: Android applications are expected to call the framework's
10466
// Context.getExternalStorageDirectory() method through JNI to get
10467
// the location of the world-writable SD Card directory. However,
10468
// this requires a Context handle, which cannot be retrieved
10469
// globally from native code. Doing so also precludes running the
10470
// code as part of a regular standalone executable, which doesn't
10471
// run in a Dalvik process (e.g. when running it through 'adb shell').
10472
//
10473
// The location /sdcard is directly accessible from native code
10474
// and is the only location (unofficially) supported by the Android
10475
// team. It's generally a symlink to the real SD Card mount point
10476
// which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
10477
// other OEM-customized locations. Never rely on these, and always
10478
// use /sdcard.
10479
char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
10480
# else
10481
char name_template[] = "/tmp/captured_stream.XXXXXX";
10482
# endif // GTEST_OS_LINUX_ANDROID
10483
const int captured_fd = mkstemp(name_template);
10484
filename_ = name_template;
10485
# endif // GTEST_OS_WINDOWS
10486
fflush(NULL);
10487
dup2(captured_fd, fd_);
10488
close(captured_fd);
10489
}
10490
10491
~CapturedStream() {
10492
remove(filename_.c_str());
10493
}
10494
10495
std::string GetCapturedString() {
10496
if (uncaptured_fd_ != -1) {
10497
// Restores the original stream.
10498
fflush(NULL);
10499
dup2(uncaptured_fd_, fd_);
10500
close(uncaptured_fd_);
10501
uncaptured_fd_ = -1;
10502
}
10503
10504
FILE* const file = posix::FOpen(filename_.c_str(), "r");
10505
const std::string content = ReadEntireFile(file);
10506
posix::FClose(file);
10507
return content;
10508
}
10509
10510
private:
10511
const int fd_; // A stream to capture.
10512
int uncaptured_fd_;
10513
// Name of the temporary file holding the stderr output.
10514
::std::string filename_;
10515
10516
GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
10517
};
10518
10519
GTEST_DISABLE_MSC_DEPRECATED_POP_()
10520
10521
static CapturedStream* g_captured_stderr = NULL;
10522
static CapturedStream* g_captured_stdout = NULL;
10523
10524
// Starts capturing an output stream (stdout/stderr).
10525
static void CaptureStream(int fd, const char* stream_name,
10526
CapturedStream** stream) {
10527
if (*stream != NULL) {
10528
GTEST_LOG_(FATAL) << "Only one " << stream_name
10529
<< " capturer can exist at a time.";
10530
}
10531
*stream = new CapturedStream(fd);
10532
}
10533
10534
// Stops capturing the output stream and returns the captured string.
10535
static std::string GetCapturedStream(CapturedStream** captured_stream) {
10536
const std::string content = (*captured_stream)->GetCapturedString();
10537
10538
delete *captured_stream;
10539
*captured_stream = NULL;
10540
10541
return content;
10542
}
10543
10544
// Starts capturing stdout.
10545
void CaptureStdout() {
10546
CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
10547
}
10548
10549
// Starts capturing stderr.
10550
void CaptureStderr() {
10551
CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
10552
}
10553
10554
// Stops capturing stdout and returns the captured string.
10555
std::string GetCapturedStdout() {
10556
return GetCapturedStream(&g_captured_stdout);
10557
}
10558
10559
// Stops capturing stderr and returns the captured string.
10560
std::string GetCapturedStderr() {
10561
return GetCapturedStream(&g_captured_stderr);
10562
}
10563
10564
#endif // GTEST_HAS_STREAM_REDIRECTION
10565
10566
10567
10568
10569
10570
size_t GetFileSize(FILE* file) {
10571
fseek(file, 0, SEEK_END);
10572
return static_cast<size_t>(ftell(file));
10573
}
10574
10575
std::string ReadEntireFile(FILE* file) {
10576
const size_t file_size = GetFileSize(file);
10577
char* const buffer = new char[file_size];
10578
10579
size_t bytes_last_read = 0; // # of bytes read in the last fread()
10580
size_t bytes_read = 0; // # of bytes read so far
10581
10582
fseek(file, 0, SEEK_SET);
10583
10584
// Keeps reading the file until we cannot read further or the
10585
// pre-determined file size is reached.
10586
do {
10587
bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
10588
bytes_read += bytes_last_read;
10589
} while (bytes_last_read > 0 && bytes_read < file_size);
10590
10591
const std::string content(buffer, bytes_read);
10592
delete[] buffer;
10593
10594
return content;
10595
}
10596
10597
#if GTEST_HAS_DEATH_TEST
10598
static const std::vector<std::string>* g_injected_test_argvs = NULL; // Owned.
10599
10600
std::vector<std::string> GetInjectableArgvs() {
10601
if (g_injected_test_argvs != NULL) {
10602
return *g_injected_test_argvs;
10603
}
10604
return GetArgvs();
10605
}
10606
10607
void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
10608
if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
10609
g_injected_test_argvs = new_argvs;
10610
}
10611
10612
void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
10613
SetInjectableArgvs(
10614
new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10615
}
10616
10617
#if GTEST_HAS_GLOBAL_STRING
10618
void SetInjectableArgvs(const std::vector< ::string>& new_argvs) {
10619
SetInjectableArgvs(
10620
new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10621
}
10622
#endif // GTEST_HAS_GLOBAL_STRING
10623
10624
void ClearInjectableArgvs() {
10625
delete g_injected_test_argvs;
10626
g_injected_test_argvs = NULL;
10627
}
10628
#endif // GTEST_HAS_DEATH_TEST
10629
10630
#if GTEST_OS_WINDOWS_MOBILE
10631
namespace posix {
10632
void Abort() {
10633
DebugBreak();
10634
TerminateProcess(GetCurrentProcess(), 1);
10635
}
10636
} // namespace posix
10637
#endif // GTEST_OS_WINDOWS_MOBILE
10638
10639
// Returns the name of the environment variable corresponding to the
10640
// given flag. For example, FlagToEnvVar("foo") will return
10641
// "GTEST_FOO" in the open-source version.
10642
static std::string FlagToEnvVar(const char* flag) {
10643
const std::string full_flag =
10644
(Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
10645
10646
Message env_var;
10647
for (size_t i = 0; i != full_flag.length(); i++) {
10648
env_var << ToUpper(full_flag.c_str()[i]);
10649
}
10650
10651
return env_var.GetString();
10652
}
10653
10654
// Parses 'str' for a 32-bit signed integer. If successful, writes
10655
// the result to *value and returns true; otherwise leaves *value
10656
// unchanged and returns false.
10657
bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
10658
// Parses the environment variable as a decimal integer.
10659
char* end = NULL;
10660
const long long_value = strtol(str, &end, 10); // NOLINT
10661
10662
// Has strtol() consumed all characters in the string?
10663
if (*end != '\0') {
10664
// No - an invalid character was encountered.
10665
Message msg;
10666
msg << "WARNING: " << src_text
10667
<< " is expected to be a 32-bit integer, but actually"
10668
<< " has value \"" << str << "\".\n";
10669
printf("%s", msg.GetString().c_str());
10670
fflush(stdout);
10671
return false;
10672
}
10673
10674
// Is the parsed value in the range of an Int32?
10675
const Int32 result = static_cast<Int32>(long_value);
10676
if (long_value == LONG_MAX || long_value == LONG_MIN ||
10677
// The parsed value overflows as a long. (strtol() returns
10678
// LONG_MAX or LONG_MIN when the input overflows.)
10679
result != long_value
10680
// The parsed value overflows as an Int32.
10681
) {
10682
Message msg;
10683
msg << "WARNING: " << src_text
10684
<< " is expected to be a 32-bit integer, but actually"
10685
<< " has value " << str << ", which overflows.\n";
10686
printf("%s", msg.GetString().c_str());
10687
fflush(stdout);
10688
return false;
10689
}
10690
10691
*value = result;
10692
return true;
10693
}
10694
10695
// Reads and returns the Boolean environment variable corresponding to
10696
// the given flag; if it's not set, returns default_value.
10697
//
10698
// The value is considered true iff it's not "0".
10699
bool BoolFromGTestEnv(const char* flag, bool default_value) {
10700
#if defined(GTEST_GET_BOOL_FROM_ENV_)
10701
return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
10702
#else
10703
const std::string env_var = FlagToEnvVar(flag);
10704
const char* const string_value = posix::GetEnv(env_var.c_str());
10705
return string_value == NULL ?
10706
default_value : strcmp(string_value, "0") != 0;
10707
#endif // defined(GTEST_GET_BOOL_FROM_ENV_)
10708
}
10709
10710
// Reads and returns a 32-bit integer stored in the environment
10711
// variable corresponding to the given flag; if it isn't set or
10712
// doesn't represent a valid 32-bit integer, returns default_value.
10713
Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
10714
#if defined(GTEST_GET_INT32_FROM_ENV_)
10715
return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
10716
#else
10717
const std::string env_var = FlagToEnvVar(flag);
10718
const char* const string_value = posix::GetEnv(env_var.c_str());
10719
if (string_value == NULL) {
10720
// The environment variable is not set.
10721
return default_value;
10722
}
10723
10724
Int32 result = default_value;
10725
if (!ParseInt32(Message() << "Environment variable " << env_var,
10726
string_value, &result)) {
10727
printf("The default value %s is used.\n",
10728
(Message() << default_value).GetString().c_str());
10729
fflush(stdout);
10730
return default_value;
10731
}
10732
10733
return result;
10734
#endif // defined(GTEST_GET_INT32_FROM_ENV_)
10735
}
10736
10737
// As a special case for the 'output' flag, if GTEST_OUTPUT is not
10738
// set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
10739
// system. The value of XML_OUTPUT_FILE is a filename without the
10740
// "xml:" prefix of GTEST_OUTPUT.
10741
// Note that this is meant to be called at the call site so it does
10742
// not check that the flag is 'output'
10743
// In essence this checks an env variable called XML_OUTPUT_FILE
10744
// and if it is set we prepend "xml:" to its value, if it not set we return ""
10745
std::string OutputFlagAlsoCheckEnvVar(){
10746
std::string default_value_for_output_flag = "";
10747
const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
10748
if (NULL != xml_output_file_env) {
10749
default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
10750
}
10751
return default_value_for_output_flag;
10752
}
10753
10754
// Reads and returns the string environment variable corresponding to
10755
// the given flag; if it's not set, returns default_value.
10756
const char* StringFromGTestEnv(const char* flag, const char* default_value) {
10757
#if defined(GTEST_GET_STRING_FROM_ENV_)
10758
return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
10759
#else
10760
const std::string env_var = FlagToEnvVar(flag);
10761
const char* const value = posix::GetEnv(env_var.c_str());
10762
return value == NULL ? default_value : value;
10763
#endif // defined(GTEST_GET_STRING_FROM_ENV_)
10764
}
10765
10766
} // namespace internal
10767
} // namespace testing
10768
// Copyright 2007, Google Inc.
10769
// All rights reserved.
10770
//
10771
// Redistribution and use in source and binary forms, with or without
10772
// modification, are permitted provided that the following conditions are
10773
// met:
10774
//
10775
// * Redistributions of source code must retain the above copyright
10776
// notice, this list of conditions and the following disclaimer.
10777
// * Redistributions in binary form must reproduce the above
10778
// copyright notice, this list of conditions and the following disclaimer
10779
// in the documentation and/or other materials provided with the
10780
// distribution.
10781
// * Neither the name of Google Inc. nor the names of its
10782
// contributors may be used to endorse or promote products derived from
10783
// this software without specific prior written permission.
10784
//
10785
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10786
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10787
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10788
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10789
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10790
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10791
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10792
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10793
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10794
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10795
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10796
10797
10798
// Google Test - The Google C++ Testing and Mocking Framework
10799
//
10800
// This file implements a universal value printer that can print a
10801
// value of any type T:
10802
//
10803
// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
10804
//
10805
// It uses the << operator when possible, and prints the bytes in the
10806
// object otherwise. A user can override its behavior for a class
10807
// type Foo by defining either operator<<(::std::ostream&, const Foo&)
10808
// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
10809
// defines Foo.
10810
10811
#include <stdio.h>
10812
#include <cctype>
10813
#include <cwchar>
10814
#include <ostream> // NOLINT
10815
#include <string>
10816
10817
namespace testing {
10818
10819
namespace {
10820
10821
using ::std::ostream;
10822
10823
// Prints a segment of bytes in the given object.
10824
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
10825
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
10826
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
10827
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
10828
size_t count, ostream* os) {
10829
char text[5] = "";
10830
for (size_t i = 0; i != count; i++) {
10831
const size_t j = start + i;
10832
if (i != 0) {
10833
// Organizes the bytes into groups of 2 for easy parsing by
10834
// human.
10835
if ((j % 2) == 0)
10836
*os << ' ';
10837
else
10838
*os << '-';
10839
}
10840
GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
10841
*os << text;
10842
}
10843
}
10844
10845
// Prints the bytes in the given value to the given ostream.
10846
void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
10847
ostream* os) {
10848
// Tells the user how big the object is.
10849
*os << count << "-byte object <";
10850
10851
const size_t kThreshold = 132;
10852
const size_t kChunkSize = 64;
10853
// If the object size is bigger than kThreshold, we'll have to omit
10854
// some details by printing only the first and the last kChunkSize
10855
// bytes.
10856
// FIXME: let the user control the threshold using a flag.
10857
if (count < kThreshold) {
10858
PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
10859
} else {
10860
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
10861
*os << " ... ";
10862
// Rounds up to 2-byte boundary.
10863
const size_t resume_pos = (count - kChunkSize + 1)/2*2;
10864
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
10865
}
10866
*os << ">";
10867
}
10868
10869
} // namespace
10870
10871
namespace internal2 {
10872
10873
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
10874
// given object. The delegation simplifies the implementation, which
10875
// uses the << operator and thus is easier done outside of the
10876
// ::testing::internal namespace, which contains a << operator that
10877
// sometimes conflicts with the one in STL.
10878
void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
10879
ostream* os) {
10880
PrintBytesInObjectToImpl(obj_bytes, count, os);
10881
}
10882
10883
} // namespace internal2
10884
10885
namespace internal {
10886
10887
// Depending on the value of a char (or wchar_t), we print it in one
10888
// of three formats:
10889
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
10890
// - as a hexadecimal escape sequence (e.g. '\x7F'), or
10891
// - as a special escape sequence (e.g. '\r', '\n').
10892
enum CharFormat {
10893
kAsIs,
10894
kHexEscape,
10895
kSpecialEscape
10896
};
10897
10898
// Returns true if c is a printable ASCII character. We test the
10899
// value of c directly instead of calling isprint(), which is buggy on
10900
// Windows Mobile.
10901
inline bool IsPrintableAscii(wchar_t c) {
10902
return 0x20 <= c && c <= 0x7E;
10903
}
10904
10905
// Prints a wide or narrow char c as a character literal without the
10906
// quotes, escaping it when necessary; returns how c was formatted.
10907
// The template argument UnsignedChar is the unsigned version of Char,
10908
// which is the type of c.
10909
template <typename UnsignedChar, typename Char>
10910
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
10911
switch (static_cast<wchar_t>(c)) {
10912
case L'\0':
10913
*os << "\\0";
10914
break;
10915
case L'\'':
10916
*os << "\\'";
10917
break;
10918
case L'\\':
10919
*os << "\\\\";
10920
break;
10921
case L'\a':
10922
*os << "\\a";
10923
break;
10924
case L'\b':
10925
*os << "\\b";
10926
break;
10927
case L'\f':
10928
*os << "\\f";
10929
break;
10930
case L'\n':
10931
*os << "\\n";
10932
break;
10933
case L'\r':
10934
*os << "\\r";
10935
break;
10936
case L'\t':
10937
*os << "\\t";
10938
break;
10939
case L'\v':
10940
*os << "\\v";
10941
break;
10942
default:
10943
if (IsPrintableAscii(c)) {
10944
*os << static_cast<char>(c);
10945
return kAsIs;
10946
} else {
10947
ostream::fmtflags flags = os->flags();
10948
*os << "\\x" << std::hex << std::uppercase
10949
<< static_cast<int>(static_cast<UnsignedChar>(c));
10950
os->flags(flags);
10951
return kHexEscape;
10952
}
10953
}
10954
return kSpecialEscape;
10955
}
10956
10957
// Prints a wchar_t c as if it's part of a string literal, escaping it when
10958
// necessary; returns how c was formatted.
10959
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
10960
switch (c) {
10961
case L'\'':
10962
*os << "'";
10963
return kAsIs;
10964
case L'"':
10965
*os << "\\\"";
10966
return kSpecialEscape;
10967
default:
10968
return PrintAsCharLiteralTo<wchar_t>(c, os);
10969
}
10970
}
10971
10972
// Prints a char c as if it's part of a string literal, escaping it when
10973
// necessary; returns how c was formatted.
10974
static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
10975
return PrintAsStringLiteralTo(
10976
static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
10977
}
10978
10979
// Prints a wide or narrow character c and its code. '\0' is printed
10980
// as "'\\0'", other unprintable characters are also properly escaped
10981
// using the standard C++ escape sequence. The template argument
10982
// UnsignedChar is the unsigned version of Char, which is the type of c.
10983
template <typename UnsignedChar, typename Char>
10984
void PrintCharAndCodeTo(Char c, ostream* os) {
10985
// First, print c as a literal in the most readable form we can find.
10986
*os << ((sizeof(c) > 1) ? "L'" : "'");
10987
const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
10988
*os << "'";
10989
10990
// To aid user debugging, we also print c's code in decimal, unless
10991
// it's 0 (in which case c was printed as '\\0', making the code
10992
// obvious).
10993
if (c == 0)
10994
return;
10995
*os << " (" << static_cast<int>(c);
10996
10997
// For more convenience, we print c's code again in hexadecimal,
10998
// unless c was already printed in the form '\x##' or the code is in
10999
// [1, 9].
11000
if (format == kHexEscape || (1 <= c && c <= 9)) {
11001
// Do nothing.
11002
} else {
11003
*os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
11004
}
11005
*os << ")";
11006
}
11007
11008
void PrintTo(unsigned char c, ::std::ostream* os) {
11009
PrintCharAndCodeTo<unsigned char>(c, os);
11010
}
11011
void PrintTo(signed char c, ::std::ostream* os) {
11012
PrintCharAndCodeTo<unsigned char>(c, os);
11013
}
11014
11015
// Prints a wchar_t as a symbol if it is printable or as its internal
11016
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
11017
void PrintTo(wchar_t wc, ostream* os) {
11018
PrintCharAndCodeTo<wchar_t>(wc, os);
11019
}
11020
11021
// Prints the given array of characters to the ostream. CharType must be either
11022
// char or wchar_t.
11023
// The array starts at begin, the length is len, it may include '\0' characters
11024
// and may not be NUL-terminated.
11025
template <typename CharType>
11026
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11027
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11028
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
11029
static CharFormat PrintCharsAsStringTo(
11030
const CharType* begin, size_t len, ostream* os) {
11031
const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
11032
*os << kQuoteBegin;
11033
bool is_previous_hex = false;
11034
CharFormat print_format = kAsIs;
11035
for (size_t index = 0; index < len; ++index) {
11036
const CharType cur = begin[index];
11037
if (is_previous_hex && IsXDigit(cur)) {
11038
// Previous character is of '\x..' form and this character can be
11039
// interpreted as another hexadecimal digit in its number. Break string to
11040
// disambiguate.
11041
*os << "\" " << kQuoteBegin;
11042
}
11043
is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
11044
// Remember if any characters required hex escaping.
11045
if (is_previous_hex) {
11046
print_format = kHexEscape;
11047
}
11048
}
11049
*os << "\"";
11050
return print_format;
11051
}
11052
11053
// Prints a (const) char/wchar_t array of 'len' elements, starting at address
11054
// 'begin'. CharType must be either char or wchar_t.
11055
template <typename CharType>
11056
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
11057
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
11058
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
11059
static void UniversalPrintCharArray(
11060
const CharType* begin, size_t len, ostream* os) {
11061
// The code
11062
// const char kFoo[] = "foo";
11063
// generates an array of 4, not 3, elements, with the last one being '\0'.
11064
//
11065
// Therefore when printing a char array, we don't print the last element if
11066
// it's '\0', such that the output matches the string literal as it's
11067
// written in the source code.
11068
if (len > 0 && begin[len - 1] == '\0') {
11069
PrintCharsAsStringTo(begin, len - 1, os);
11070
return;
11071
}
11072
11073
// If, however, the last element in the array is not '\0', e.g.
11074
// const char kFoo[] = { 'f', 'o', 'o' };
11075
// we must print the entire array. We also print a message to indicate
11076
// that the array is not NUL-terminated.
11077
PrintCharsAsStringTo(begin, len, os);
11078
*os << " (no terminating NUL)";
11079
}
11080
11081
// Prints a (const) char array of 'len' elements, starting at address 'begin'.
11082
void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
11083
UniversalPrintCharArray(begin, len, os);
11084
}
11085
11086
// Prints a (const) wchar_t array of 'len' elements, starting at address
11087
// 'begin'.
11088
void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
11089
UniversalPrintCharArray(begin, len, os);
11090
}
11091
11092
// Prints the given C string to the ostream.
11093
void PrintTo(const char* s, ostream* os) {
11094
if (s == NULL) {
11095
*os << "NULL";
11096
} else {
11097
*os << ImplicitCast_<const void*>(s) << " pointing to ";
11098
PrintCharsAsStringTo(s, strlen(s), os);
11099
}
11100
}
11101
11102
// MSVC compiler can be configured to define whar_t as a typedef
11103
// of unsigned short. Defining an overload for const wchar_t* in that case
11104
// would cause pointers to unsigned shorts be printed as wide strings,
11105
// possibly accessing more memory than intended and causing invalid
11106
// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
11107
// wchar_t is implemented as a native type.
11108
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
11109
// Prints the given wide C string to the ostream.
11110
void PrintTo(const wchar_t* s, ostream* os) {
11111
if (s == NULL) {
11112
*os << "NULL";
11113
} else {
11114
*os << ImplicitCast_<const void*>(s) << " pointing to ";
11115
PrintCharsAsStringTo(s, std::wcslen(s), os);
11116
}
11117
}
11118
#endif // wchar_t is native
11119
11120
namespace {
11121
11122
bool ContainsUnprintableControlCodes(const char* str, size_t length) {
11123
const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
11124
11125
for (size_t i = 0; i < length; i++) {
11126
unsigned char ch = *s++;
11127
if (std::iscntrl(ch)) {
11128
switch (ch) {
11129
case '\t':
11130
case '\n':
11131
case '\r':
11132
break;
11133
default:
11134
return true;
11135
}
11136
}
11137
}
11138
return false;
11139
}
11140
11141
bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
11142
11143
bool IsValidUTF8(const char* str, size_t length) {
11144
const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
11145
11146
for (size_t i = 0; i < length;) {
11147
unsigned char lead = s[i++];
11148
11149
if (lead <= 0x7f) {
11150
continue; // single-byte character (ASCII) 0..7F
11151
}
11152
if (lead < 0xc2) {
11153
return false; // trail byte or non-shortest form
11154
} else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
11155
++i; // 2-byte character
11156
} else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
11157
IsUTF8TrailByte(s[i]) &&
11158
IsUTF8TrailByte(s[i + 1]) &&
11159
// check for non-shortest form and surrogate
11160
(lead != 0xe0 || s[i] >= 0xa0) &&
11161
(lead != 0xed || s[i] < 0xa0)) {
11162
i += 2; // 3-byte character
11163
} else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
11164
IsUTF8TrailByte(s[i]) &&
11165
IsUTF8TrailByte(s[i + 1]) &&
11166
IsUTF8TrailByte(s[i + 2]) &&
11167
// check for non-shortest form
11168
(lead != 0xf0 || s[i] >= 0x90) &&
11169
(lead != 0xf4 || s[i] < 0x90)) {
11170
i += 3; // 4-byte character
11171
} else {
11172
return false;
11173
}
11174
}
11175
return true;
11176
}
11177
11178
void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
11179
if (!ContainsUnprintableControlCodes(str, length) &&
11180
IsValidUTF8(str, length)) {
11181
*os << "\n As Text: \"" << str << "\"";
11182
}
11183
}
11184
11185
} // anonymous namespace
11186
11187
// Prints a ::string object.
11188
#if GTEST_HAS_GLOBAL_STRING
11189
void PrintStringTo(const ::string& s, ostream* os) {
11190
if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
11191
if (GTEST_FLAG(print_utf8)) {
11192
ConditionalPrintAsText(s.data(), s.size(), os);
11193
}
11194
}
11195
}
11196
#endif // GTEST_HAS_GLOBAL_STRING
11197
11198
void PrintStringTo(const ::std::string& s, ostream* os) {
11199
if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
11200
if (GTEST_FLAG(print_utf8)) {
11201
ConditionalPrintAsText(s.data(), s.size(), os);
11202
}
11203
}
11204
}
11205
11206
// Prints a ::wstring object.
11207
#if GTEST_HAS_GLOBAL_WSTRING
11208
void PrintWideStringTo(const ::wstring& s, ostream* os) {
11209
PrintCharsAsStringTo(s.data(), s.size(), os);
11210
}
11211
#endif // GTEST_HAS_GLOBAL_WSTRING
11212
11213
#if GTEST_HAS_STD_WSTRING
11214
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
11215
PrintCharsAsStringTo(s.data(), s.size(), os);
11216
}
11217
#endif // GTEST_HAS_STD_WSTRING
11218
11219
} // namespace internal
11220
11221
} // namespace testing
11222
// Copyright 2008, Google Inc.
11223
// All rights reserved.
11224
//
11225
// Redistribution and use in source and binary forms, with or without
11226
// modification, are permitted provided that the following conditions are
11227
// met:
11228
//
11229
// * Redistributions of source code must retain the above copyright
11230
// notice, this list of conditions and the following disclaimer.
11231
// * Redistributions in binary form must reproduce the above
11232
// copyright notice, this list of conditions and the following disclaimer
11233
// in the documentation and/or other materials provided with the
11234
// distribution.
11235
// * Neither the name of Google Inc. nor the names of its
11236
// contributors may be used to endorse or promote products derived from
11237
// this software without specific prior written permission.
11238
//
11239
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11240
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11241
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11242
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11243
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11244
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11245
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11246
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11247
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11248
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11249
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11250
11251
//
11252
// The Google C++ Testing and Mocking Framework (Google Test)
11253
11254
11255
namespace testing {
11256
11257
using internal::GetUnitTestImpl;
11258
11259
// Gets the summary of the failure message by omitting the stack trace
11260
// in it.
11261
std::string TestPartResult::ExtractSummary(const char* message) {
11262
const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
11263
return stack_trace == NULL ? message :
11264
std::string(message, stack_trace);
11265
}
11266
11267
// Prints a TestPartResult object.
11268
std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
11269
return os
11270
<< result.file_name() << ":" << result.line_number() << ": "
11271
<< (result.type() == TestPartResult::kSuccess ? "Success" :
11272
result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
11273
"Non-fatal failure") << ":\n"
11274
<< result.message() << std::endl;
11275
}
11276
11277
// Appends a TestPartResult to the array.
11278
void TestPartResultArray::Append(const TestPartResult& result) {
11279
array_.push_back(result);
11280
}
11281
11282
// Returns the TestPartResult at the given index (0-based).
11283
const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
11284
if (index < 0 || index >= size()) {
11285
printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
11286
internal::posix::Abort();
11287
}
11288
11289
return array_[index];
11290
}
11291
11292
// Returns the number of TestPartResult objects in the array.
11293
int TestPartResultArray::size() const {
11294
return static_cast<int>(array_.size());
11295
}
11296
11297
namespace internal {
11298
11299
HasNewFatalFailureHelper::HasNewFatalFailureHelper()
11300
: has_new_fatal_failure_(false),
11301
original_reporter_(GetUnitTestImpl()->
11302
GetTestPartResultReporterForCurrentThread()) {
11303
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
11304
}
11305
11306
HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
11307
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
11308
original_reporter_);
11309
}
11310
11311
void HasNewFatalFailureHelper::ReportTestPartResult(
11312
const TestPartResult& result) {
11313
if (result.fatally_failed())
11314
has_new_fatal_failure_ = true;
11315
original_reporter_->ReportTestPartResult(result);
11316
}
11317
11318
} // namespace internal
11319
11320
} // namespace testing
11321
// Copyright 2008 Google Inc.
11322
// All Rights Reserved.
11323
//
11324
// Redistribution and use in source and binary forms, with or without
11325
// modification, are permitted provided that the following conditions are
11326
// met:
11327
//
11328
// * Redistributions of source code must retain the above copyright
11329
// notice, this list of conditions and the following disclaimer.
11330
// * Redistributions in binary form must reproduce the above
11331
// copyright notice, this list of conditions and the following disclaimer
11332
// in the documentation and/or other materials provided with the
11333
// distribution.
11334
// * Neither the name of Google Inc. nor the names of its
11335
// contributors may be used to endorse or promote products derived from
11336
// this software without specific prior written permission.
11337
//
11338
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11339
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11340
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11341
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11342
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11343
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11344
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11345
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11346
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11347
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11348
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11349
11350
11351
11352
11353
namespace testing {
11354
namespace internal {
11355
11356
#if GTEST_HAS_TYPED_TEST_P
11357
11358
// Skips to the first non-space char in str. Returns an empty string if str
11359
// contains only whitespace characters.
11360
static const char* SkipSpaces(const char* str) {
11361
while (IsSpace(*str))
11362
str++;
11363
return str;
11364
}
11365
11366
static std::vector<std::string> SplitIntoTestNames(const char* src) {
11367
std::vector<std::string> name_vec;
11368
src = SkipSpaces(src);
11369
for (; src != NULL; src = SkipComma(src)) {
11370
name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
11371
}
11372
return name_vec;
11373
}
11374
11375
// Verifies that registered_tests match the test names in
11376
// registered_tests_; returns registered_tests if successful, or
11377
// aborts the program otherwise.
11378
const char* TypedTestCasePState::VerifyRegisteredTestNames(
11379
const char* file, int line, const char* registered_tests) {
11380
typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
11381
registered_ = true;
11382
11383
std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
11384
11385
Message errors;
11386
11387
std::set<std::string> tests;
11388
for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
11389
name_it != name_vec.end(); ++name_it) {
11390
const std::string& name = *name_it;
11391
if (tests.count(name) != 0) {
11392
errors << "Test " << name << " is listed more than once.\n";
11393
continue;
11394
}
11395
11396
bool found = false;
11397
for (RegisteredTestIter it = registered_tests_.begin();
11398
it != registered_tests_.end();
11399
++it) {
11400
if (name == it->first) {
11401
found = true;
11402
break;
11403
}
11404
}
11405
11406
if (found) {
11407
tests.insert(name);
11408
} else {
11409
errors << "No test named " << name
11410
<< " can be found in this test case.\n";
11411
}
11412
}
11413
11414
for (RegisteredTestIter it = registered_tests_.begin();
11415
it != registered_tests_.end();
11416
++it) {
11417
if (tests.count(it->first) == 0) {
11418
errors << "You forgot to list test " << it->first << ".\n";
11419
}
11420
}
11421
11422
const std::string& errors_str = errors.GetString();
11423
if (errors_str != "") {
11424
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
11425
errors_str.c_str());
11426
fflush(stderr);
11427
posix::Abort();
11428
}
11429
11430
return registered_tests;
11431
}
11432
11433
#endif // GTEST_HAS_TYPED_TEST_P
11434
11435
void* g_parameter_ = NULL;
11436
11437
} // namespace internal
11438
} // namespace testing
11439
11440