-
Notifications
You must be signed in to change notification settings - Fork 30.9k
/
Copy pathgtest.cc
6960 lines (6046 loc) Β· 256 KB
/
gtest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The Google C++ Testing and Mocking Framework (Google Test)
#include "gtest/gtest.h"
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>
#include <algorithm>
#include <chrono> // NOLINT
#include <cmath>
#include <csignal> // NOLINT: raise(3) is used on some platforms
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <initializer_list>
#include <iomanip>
#include <ios>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <ostream> // NOLINT
#include <set>
#include <sstream>
#include <unordered_set>
#include <utility>
#include <vector>
#include "gtest/gtest-assertion-result.h"
#include "gtest/gtest-spi.h"
#include "gtest/internal/custom/gtest.h"
#include "gtest/internal/gtest-port.h"
#ifdef GTEST_OS_LINUX
#include <fcntl.h> // NOLINT
#include <limits.h> // NOLINT
#include <sched.h> // NOLINT
// Declares vsnprintf(). This header is not available on Windows.
#include <strings.h> // NOLINT
#include <sys/mman.h> // NOLINT
#include <sys/time.h> // NOLINT
#include <unistd.h> // NOLINT
#include <string>
#elif defined(GTEST_OS_ZOS)
#include <sys/time.h> // NOLINT
// On z/OS we additionally need strings.h for strcasecmp.
#include <strings.h> // NOLINT
#elif defined(GTEST_OS_WINDOWS_MOBILE) // We are on Windows CE.
#include <windows.h> // NOLINT
#undef min
#elif defined(GTEST_OS_WINDOWS) // We are on Windows proper.
#include <windows.h> // NOLINT
#undef min
#ifdef _MSC_VER
#include <crtdbg.h> // NOLINT
#endif
#include <io.h> // NOLINT
#include <sys/stat.h> // NOLINT
#include <sys/timeb.h> // NOLINT
#include <sys/types.h> // NOLINT
#ifdef GTEST_OS_WINDOWS_MINGW
#include <sys/time.h> // NOLINT
#endif // GTEST_OS_WINDOWS_MINGW
#else
// cpplint thinks that the header is already included, so we want to
// silence it.
#include <sys/time.h> // NOLINT
#include <unistd.h> // NOLINT
#endif // GTEST_OS_LINUX
#if GTEST_HAS_EXCEPTIONS
#include <stdexcept>
#endif
#if GTEST_CAN_STREAM_RESULTS_
#include <arpa/inet.h> // NOLINT
#include <netdb.h> // NOLINT
#include <sys/socket.h> // NOLINT
#include <sys/types.h> // NOLINT
#endif
#include "src/gtest-internal-inl.h"
#ifdef GTEST_OS_WINDOWS
#define vsnprintf _vsnprintf
#endif // GTEST_OS_WINDOWS
#ifdef GTEST_OS_MAC
#ifndef GTEST_OS_IOS
#include <crt_externs.h>
#endif
#endif
#ifdef GTEST_HAS_ABSL
#include "absl/container/flat_hash_set.h"
#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/stacktrace.h"
#include "absl/debugging/symbolize.h"
#include "absl/flags/parse.h"
#include "absl/flags/usage.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#endif // GTEST_HAS_ABSL
// Checks builtin compiler feature |x| while avoiding an extra layer of #ifdefs
// at the callsite.
#if defined(__has_builtin)
#define GTEST_HAS_BUILTIN(x) __has_builtin(x)
#else
#define GTEST_HAS_BUILTIN(x) 0
#endif // defined(__has_builtin)
#if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
#define GTEST_HAS_ABSL_FLAGS
#endif
namespace testing {
using internal::CountIf;
using internal::ForEach;
using internal::GetElementOr;
using internal::Shuffle;
// Constants.
// A test whose test suite name or test name matches this filter is
// disabled and not run.
static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
// A test suite whose name matches this filter is considered a death
// test suite and will be run before test suites whose name doesn't
// match this filter.
static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
// A test filter that matches everything.
static const char kUniversalFilter[] = "*";
// The default output format.
static const char kDefaultOutputFormat[] = "xml";
// The default output file.
static const char kDefaultOutputFile[] = "test_detail";
// The environment variable name for the test shard index.
static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
// The environment variable name for the total number of test shards.
static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
// The environment variable name for the test shard status file.
static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
namespace internal {
// The text used in failure messages to indicate the start of the
// stack trace.
const char kStackTraceMarker[] = "\nStack trace:\n";
// g_help_flag is true if and only if the --help flag or an equivalent form
// is specified on the command line.
bool g_help_flag = false;
#if GTEST_HAS_FILE_SYSTEM
// Utility function to Open File for Writing
static FILE* OpenFileForWriting(const std::string& output_file) {
FILE* fileout = nullptr;
FilePath output_file_path(output_file);
FilePath output_dir(output_file_path.RemoveFileName());
if (output_dir.CreateDirectoriesRecursively()) {
fileout = posix::FOpen(output_file.c_str(), "w");
}
if (fileout == nullptr) {
GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
}
return fileout;
}
#endif // GTEST_HAS_FILE_SYSTEM
} // namespace internal
// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
// environment variable.
static const char* GetDefaultFilter() {
const char* const testbridge_test_only =
internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
if (testbridge_test_only != nullptr) {
return testbridge_test_only;
}
return kUniversalFilter;
}
// Bazel passes in the argument to '--test_runner_fail_fast' via the
// TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
static bool GetDefaultFailFast() {
const char* const testbridge_test_runner_fail_fast =
internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
if (testbridge_test_runner_fail_fast != nullptr) {
return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
}
return false;
}
} // namespace testing
GTEST_DEFINE_bool_(
fail_fast,
testing::internal::BoolFromGTestEnv("fail_fast",
testing::GetDefaultFailFast()),
"True if and only if a test failure should stop further test execution.");
GTEST_DEFINE_bool_(
also_run_disabled_tests,
testing::internal::BoolFromGTestEnv("also_run_disabled_tests", false),
"Run disabled tests too, in addition to the tests normally being run.");
GTEST_DEFINE_bool_(
break_on_failure,
testing::internal::BoolFromGTestEnv("break_on_failure", false),
"True if and only if a failed assertion should be a debugger "
"break-point.");
GTEST_DEFINE_bool_(catch_exceptions,
testing::internal::BoolFromGTestEnv("catch_exceptions",
true),
"True if and only if " GTEST_NAME_
" should catch exceptions and treat them as test failures.");
GTEST_DEFINE_string_(
color, testing::internal::StringFromGTestEnv("color", "auto"),
"Whether to use colors in the output. Valid values: yes, no, "
"and auto. 'auto' means to use colors if the output is "
"being sent to a terminal and the TERM environment variable "
"is set to a terminal type that supports colors.");
GTEST_DEFINE_string_(
filter,
testing::internal::StringFromGTestEnv("filter",
testing::GetDefaultFilter()),
"A colon-separated list of glob (not regex) patterns "
"for filtering the tests to run, optionally followed by a "
"'-' and a : separated list of negative patterns (tests to "
"exclude). A test is run if it matches one of the positive "
"patterns and does not match any of the negative patterns.");
GTEST_DEFINE_bool_(
install_failure_signal_handler,
testing::internal::BoolFromGTestEnv("install_failure_signal_handler",
false),
"If true and supported on the current platform, " GTEST_NAME_
" should "
"install a signal handler that dumps debugging information when fatal "
"signals are raised.");
GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them.");
// The net priority order after flag processing is thus:
// --gtest_output command line flag
// GTEST_OUTPUT environment variable
// XML_OUTPUT_FILE environment variable
// ''
GTEST_DEFINE_string_(
output,
testing::internal::StringFromGTestEnv(
"output", testing::internal::OutputFlagAlsoCheckEnvVar().c_str()),
"A format (defaults to \"xml\" but can be specified to be \"json\"), "
"optionally followed by a colon and an output file name or directory. "
"A directory is indicated by a trailing pathname separator. "
"Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
"If a directory is specified, output files will be created "
"within that directory, with file-names based on the test "
"executable's name and, if necessary, made unique by adding "
"digits.");
GTEST_DEFINE_bool_(
brief, testing::internal::BoolFromGTestEnv("brief", false),
"True if only test failures should be displayed in text output.");
GTEST_DEFINE_bool_(print_time,
testing::internal::BoolFromGTestEnv("print_time", true),
"True if and only if " GTEST_NAME_
" should display elapsed time in text output.");
GTEST_DEFINE_bool_(print_utf8,
testing::internal::BoolFromGTestEnv("print_utf8", true),
"True if and only if " GTEST_NAME_
" prints UTF8 characters as text.");
GTEST_DEFINE_int32_(
random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0),
"Random number seed to use when shuffling test orders. Must be in range "
"[1, 99999], or 0 to use a seed based on the current time.");
GTEST_DEFINE_int32_(
repeat, testing::internal::Int32FromGTestEnv("repeat", 1),
"How many times to repeat each test. Specify a negative number "
"for repeating forever. Useful for shaking out flaky tests.");
GTEST_DEFINE_bool_(
recreate_environments_when_repeating,
testing::internal::BoolFromGTestEnv("recreate_environments_when_repeating",
false),
"Controls whether global test environments are recreated for each repeat "
"of the tests. If set to false the global test environments are only set "
"up once, for the first iteration, and only torn down once, for the last. "
"Useful for shaking out flaky tests with stable, expensive test "
"environments. If --gtest_repeat is set to a negative number, meaning "
"there is no last run, the environments will always be recreated to avoid "
"leaks.");
GTEST_DEFINE_bool_(show_internal_stack_frames, false,
"True if and only if " GTEST_NAME_
" should include internal stack frames when "
"printing test failure stack traces.");
GTEST_DEFINE_bool_(shuffle,
testing::internal::BoolFromGTestEnv("shuffle", false),
"True if and only if " GTEST_NAME_
" should randomize tests' order on every run.");
GTEST_DEFINE_int32_(
stack_trace_depth,
testing::internal::Int32FromGTestEnv("stack_trace_depth",
testing::kMaxStackTraceDepth),
"The maximum number of stack frames to print when an "
"assertion fails. The valid range is 0 through 100, inclusive.");
GTEST_DEFINE_string_(
stream_result_to,
testing::internal::StringFromGTestEnv("stream_result_to", ""),
"This flag specifies the host name and the port number on which to stream "
"test results. Example: \"localhost:555\". The flag is effective only on "
"Linux and macOS.");
GTEST_DEFINE_bool_(
throw_on_failure,
testing::internal::BoolFromGTestEnv("throw_on_failure", false),
"When this flag is specified, a failed assertion will throw an exception "
"if exceptions are enabled or exit the program with a non-zero code "
"otherwise. For use with an external test framework.");
#if GTEST_USE_OWN_FLAGFILE_FLAG_
GTEST_DEFINE_string_(
flagfile, testing::internal::StringFromGTestEnv("flagfile", ""),
"This flag specifies the flagfile to read command-line flags from.");
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
namespace testing {
namespace internal {
const uint32_t Random::kMaxRange;
// Generates a random number from [0, range), using a Linear
// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
// than kMaxRange.
uint32_t Random::Generate(uint32_t range) {
// These constants are the same as are used in glibc's rand(3).
// Use wider types than necessary to prevent unsigned overflow diagnostics.
state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange;
GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0).";
GTEST_CHECK_(range <= kMaxRange)
<< "Generation of a number in [0, " << range << ") was requested, "
<< "but this can only generate numbers in [0, " << kMaxRange << ").";
// Converting via modulus introduces a bit of downward bias, but
// it's simple, and a linear congruential generator isn't too good
// to begin with.
return state_ % range;
}
// GTestIsInitialized() returns true if and only if the user has initialized
// Google Test. Useful for catching the user mistake of not initializing
// Google Test before calling RUN_ALL_TESTS().
static bool GTestIsInitialized() { return !GetArgvs().empty(); }
// Iterates over a vector of TestSuites, keeping a running sum of the
// results of calling a given int-returning method on each.
// Returns the sum.
static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
int (TestSuite::*method)() const) {
int sum = 0;
for (size_t i = 0; i < case_list.size(); i++) {
sum += (case_list[i]->*method)();
}
return sum;
}
// Returns true if and only if the test suite passed.
static bool TestSuitePassed(const TestSuite* test_suite) {
return test_suite->should_run() && test_suite->Passed();
}
// Returns true if and only if the test suite failed.
static bool TestSuiteFailed(const TestSuite* test_suite) {
return test_suite->should_run() && test_suite->Failed();
}
// Returns true if and only if test_suite contains at least one test that
// should run.
static bool ShouldRunTestSuite(const TestSuite* test_suite) {
return test_suite->should_run();
}
namespace {
// Returns true if test part results of type `type` should include a stack
// trace.
bool ShouldEmitStackTraceForResultType(TestPartResult::Type type) {
// Suppress emission of the stack trace for SUCCEED() since it likely never
// requires investigation, and GTEST_SKIP() since skipping is an intentional
// act by the developer rather than a failure requiring investigation.
return type != TestPartResult::kSuccess && type != TestPartResult::kSkip;
}
} // namespace
// AssertHelper constructor.
AssertHelper::AssertHelper(TestPartResult::Type type, const char* file,
int line, const char* message)
: data_(new AssertHelperData(type, file, line, message)) {}
AssertHelper::~AssertHelper() { delete data_; }
// Message assignment, for assertion streaming support.
void AssertHelper::operator=(const Message& message) const {
UnitTest::GetInstance()->AddTestPartResult(
data_->type, data_->file, data_->line,
AppendUserMessage(data_->message, message),
ShouldEmitStackTraceForResultType(data_->type)
? UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
: ""
// Skips the stack frame for this function itself.
); // NOLINT
}
namespace {
// When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
// to creates test cases for it, a synthetic test case is
// inserted to report ether an error or a log message.
//
// This configuration bit will likely be removed at some point.
constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
// A test that fails at a given file/line location with a given message.
class FailureTest : public Test {
public:
explicit FailureTest(const CodeLocation& loc, std::string error_message,
bool as_error)
: loc_(loc),
error_message_(std::move(error_message)),
as_error_(as_error) {}
void TestBody() override {
if (as_error_) {
AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
loc_.line, "") = Message() << error_message_;
} else {
std::cout << error_message_ << std::endl;
}
}
private:
const CodeLocation loc_;
const std::string error_message_;
const bool as_error_;
};
} // namespace
std::set<std::string>* GetIgnoredParameterizedTestSuites() {
return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
}
// Add a given test_suit to the list of them allow to go un-instantiated.
MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
GetIgnoredParameterizedTestSuites()->insert(test_suite);
}
// If this parameterized test suite has no instantiations (and that
// has not been marked as okay), emit a test case reporting that.
void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
bool has_test_p) {
const auto& ignored = *GetIgnoredParameterizedTestSuites();
if (ignored.find(name) != ignored.end()) return;
const char kMissingInstantiation[] = //
" is defined via TEST_P, but never instantiated. None of the test "
"cases "
"will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
"ones provided expand to nothing."
"\n\n"
"Ideally, TEST_P definitions should only ever be included as part of "
"binaries that intend to use them. (As opposed to, for example, being "
"placed in a library that may be linked in to get other utilities.)";
const char kMissingTestCase[] = //
" is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
"defined via TEST_P . No test cases will run."
"\n\n"
"Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
"code that always depend on code that provides TEST_P. Failing to do "
"so is often an indication of dead code, e.g. the last TEST_P was "
"removed but the rest got left behind.";
std::string message =
"Parameterized test suite " + name +
(has_test_p ? kMissingInstantiation : kMissingTestCase) +
"\n\n"
"To suppress this error for this test suite, insert the following line "
"(in a non-header) in the namespace it is defined in:"
"\n\n"
"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
name + ");";
std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
RegisterTest( //
"GoogleTestVerification", full_name.c_str(),
nullptr, // No type parameter.
nullptr, // No value parameter.
location.file.c_str(), location.line, [message, location] {
return new FailureTest(location, message,
kErrorOnUninstantiatedParameterizedTest);
});
}
void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
CodeLocation code_location) {
GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
test_suite_name, std::move(code_location));
}
void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation(
case_name);
}
void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
const char* test_suite_name, CodeLocation code_location) {
suites_.emplace(std::string(test_suite_name),
TypeParameterizedTestSuiteInfo(std::move(code_location)));
}
void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
const char* test_suite_name) {
auto it = suites_.find(std::string(test_suite_name));
if (it != suites_.end()) {
it->second.instantiated = true;
} else {
GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '"
<< test_suite_name << "'";
}
}
void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
const auto& ignored = *GetIgnoredParameterizedTestSuites();
for (const auto& testcase : suites_) {
if (testcase.second.instantiated) continue;
if (ignored.find(testcase.first) != ignored.end()) continue;
std::string message =
"Type parameterized test suite " + testcase.first +
" is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
"via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
"\n\n"
"Ideally, TYPED_TEST_P definitions should only ever be included as "
"part of binaries that intend to use them. (As opposed to, for "
"example, being placed in a library that may be linked in to get "
"other "
"utilities.)"
"\n\n"
"To suppress this error for this test suite, insert the following "
"line "
"(in a non-header) in the namespace it is defined in:"
"\n\n"
"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
testcase.first + ");";
std::string full_name =
"UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
RegisterTest( //
"GoogleTestVerification", full_name.c_str(),
nullptr, // No type parameter.
nullptr, // No value parameter.
testcase.second.code_location.file.c_str(),
testcase.second.code_location.line, [message, testcase] {
return new FailureTest(testcase.second.code_location, message,
kErrorOnUninstantiatedTypeParameterizedTest);
});
}
}
// A copy of all command line arguments. Set by InitGoogleTest().
static ::std::vector<std::string> g_argvs;
::std::vector<std::string> GetArgvs() {
#if defined(GTEST_CUSTOM_GET_ARGVS_)
// GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
// ::string. This code converts it to the appropriate type.
const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
return ::std::vector<std::string>(custom.begin(), custom.end());
#else // defined(GTEST_CUSTOM_GET_ARGVS_)
return g_argvs;
#endif // defined(GTEST_CUSTOM_GET_ARGVS_)
}
#if GTEST_HAS_FILE_SYSTEM
// Returns the current application's name, removing directory path if that
// is present.
FilePath GetCurrentExecutableName() {
FilePath result;
auto args = GetArgvs();
if (!args.empty()) {
#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2)
result.Set(FilePath(args[0]).RemoveExtension("exe"));
#else
result.Set(FilePath(args[0]));
#endif // GTEST_OS_WINDOWS
}
return result.RemoveDirectoryName();
}
#endif // GTEST_HAS_FILE_SYSTEM
// Functions for processing the gtest_output flag.
// Returns the output format, or "" for normal printed output.
std::string UnitTestOptions::GetOutputFormat() {
std::string s = GTEST_FLAG_GET(output);
const char* const gtest_output_flag = s.c_str();
const char* const colon = strchr(gtest_output_flag, ':');
return (colon == nullptr)
? std::string(gtest_output_flag)
: std::string(gtest_output_flag,
static_cast<size_t>(colon - gtest_output_flag));
}
#if GTEST_HAS_FILE_SYSTEM
// Returns the name of the requested output file, or the default if none
// was explicitly specified.
std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
std::string s = GTEST_FLAG_GET(output);
const char* const gtest_output_flag = s.c_str();
std::string format = GetOutputFormat();
if (format.empty()) format = std::string(kDefaultOutputFormat);
const char* const colon = strchr(gtest_output_flag, ':');
if (colon == nullptr)
return internal::FilePath::MakeFileName(
internal::FilePath(
UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(kDefaultOutputFile), 0, format.c_str())
.string();
internal::FilePath output_name(colon + 1);
if (!output_name.IsAbsolutePath())
output_name = internal::FilePath::ConcatPaths(
internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(colon + 1));
if (!output_name.IsDirectory()) return output_name.string();
internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
output_name, internal::GetCurrentExecutableName(),
GetOutputFormat().c_str()));
return result.string();
}
#endif // GTEST_HAS_FILE_SYSTEM
// Returns true if and only if the wildcard pattern matches the string. Each
// pattern consists of regular characters, single-character wildcards (?), and
// multi-character wildcards (*).
//
// This function implements a linear-time string globbing algorithm based on
// https://research.swtch.com/glob.
static bool PatternMatchesString(const std::string& name_str,
const char* pattern, const char* pattern_end) {
const char* name = name_str.c_str();
const char* const name_begin = name;
const char* const name_end = name + name_str.size();
const char* pattern_next = pattern;
const char* name_next = name;
while (pattern < pattern_end || name < name_end) {
if (pattern < pattern_end) {
switch (*pattern) {
default: // Match an ordinary character.
if (name < name_end && *name == *pattern) {
++pattern;
++name;
continue;
}
break;
case '?': // Match any single character.
if (name < name_end) {
++pattern;
++name;
continue;
}
break;
case '*':
// Match zero or more characters. Start by skipping over the wildcard
// and matching zero characters from name. If that fails, restart and
// match one more character than the last attempt.
pattern_next = pattern;
name_next = name + 1;
++pattern;
continue;
}
}
// Failed to match a character. Restart if possible.
if (name_begin < name_next && name_next <= name_end) {
pattern = pattern_next;
name = name_next;
continue;
}
return false;
}
return true;
}
namespace {
bool IsGlobPattern(const std::string& pattern) {
return std::any_of(pattern.begin(), pattern.end(),
[](const char c) { return c == '?' || c == '*'; });
}
class UnitTestFilter {
public:
UnitTestFilter() = default;
// Constructs a filter from a string of patterns separated by `:`.
explicit UnitTestFilter(const std::string& filter) {
// By design "" filter matches "" string.
std::vector<std::string> all_patterns;
SplitString(filter, ':', &all_patterns);
const auto exact_match_patterns_begin = std::partition(
all_patterns.begin(), all_patterns.end(), &IsGlobPattern);
glob_patterns_.reserve(static_cast<size_t>(
std::distance(all_patterns.begin(), exact_match_patterns_begin)));
std::move(all_patterns.begin(), exact_match_patterns_begin,
std::inserter(glob_patterns_, glob_patterns_.begin()));
std::move(
exact_match_patterns_begin, all_patterns.end(),
std::inserter(exact_match_patterns_, exact_match_patterns_.begin()));
}
// Returns true if and only if name matches at least one of the patterns in
// the filter.
bool MatchesName(const std::string& name) const {
return exact_match_patterns_.find(name) != exact_match_patterns_.end() ||
std::any_of(glob_patterns_.begin(), glob_patterns_.end(),
[&name](const std::string& pattern) {
return PatternMatchesString(
name, pattern.c_str(),
pattern.c_str() + pattern.size());
});
}
private:
std::vector<std::string> glob_patterns_;
std::unordered_set<std::string> exact_match_patterns_;
};
class PositiveAndNegativeUnitTestFilter {
public:
// Constructs a positive and a negative filter from a string. The string
// contains a positive filter optionally followed by a '-' character and a
// negative filter. In case only a negative filter is provided the positive
// filter will be assumed "*".
// A filter is a list of patterns separated by ':'.
explicit PositiveAndNegativeUnitTestFilter(const std::string& filter) {
std::vector<std::string> positive_and_negative_filters;
// NOTE: `SplitString` always returns a non-empty container.
SplitString(filter, '-', &positive_and_negative_filters);
const auto& positive_filter = positive_and_negative_filters.front();
if (positive_and_negative_filters.size() > 1) {
positive_filter_ = UnitTestFilter(
positive_filter.empty() ? kUniversalFilter : positive_filter);
// TODO(b/214626361): Fail on multiple '-' characters
// For the moment to preserve old behavior we concatenate the rest of the
// string parts with `-` as separator to generate the negative filter.
auto negative_filter_string = positive_and_negative_filters[1];
for (std::size_t i = 2; i < positive_and_negative_filters.size(); i++)
negative_filter_string =
negative_filter_string + '-' + positive_and_negative_filters[i];
negative_filter_ = UnitTestFilter(negative_filter_string);
} else {
// In case we don't have a negative filter and positive filter is ""
// we do not use kUniversalFilter by design as opposed to when we have a
// negative filter.
positive_filter_ = UnitTestFilter(positive_filter);
}
}
// Returns true if and only if test name (this is generated by appending test
// suit name and test name via a '.' character) matches the positive filter
// and does not match the negative filter.
bool MatchesTest(const std::string& test_suite_name,
const std::string& test_name) const {
return MatchesName(test_suite_name + "." + test_name);
}
// Returns true if and only if name matches the positive filter and does not
// match the negative filter.
bool MatchesName(const std::string& name) const {
return positive_filter_.MatchesName(name) &&
!negative_filter_.MatchesName(name);
}
private:
UnitTestFilter positive_filter_;
UnitTestFilter negative_filter_;
};
} // namespace
bool UnitTestOptions::MatchesFilter(const std::string& name_str,
const char* filter) {
return UnitTestFilter(filter).MatchesName(name_str);
}
// Returns true if and only if the user-specified filter matches the test
// suite name and the test name.
bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
const std::string& test_name) {
// Split --gtest_filter at '-', if there is one, to separate into
// positive filter and negative filter portions
return PositiveAndNegativeUnitTestFilter(GTEST_FLAG_GET(filter))
.MatchesTest(test_suite_name, test_name);
}
#if GTEST_HAS_SEH
static std::string FormatSehExceptionMessage(DWORD exception_code,
const char* location) {
Message message;
message << "SEH exception with code 0x" << std::setbase(16) << exception_code
<< std::setbase(10) << " thrown in " << location << ".";
return message.GetString();
}
int UnitTestOptions::GTestProcessSEH(DWORD seh_code, const char* location) {
// Google Test should handle a SEH exception if:
// 1. the user wants it to, AND
// 2. this is not a breakpoint exception or stack overflow, AND
// 3. this is not a C++ exception (VC++ implements them via SEH,
// apparently).
//
// SEH exception code for C++ exceptions.
// (see https://support.microsoft.com/kb/185294 for more information).
const DWORD kCxxExceptionCode = 0xe06d7363;
if (!GTEST_FLAG_GET(catch_exceptions) || seh_code == kCxxExceptionCode ||
seh_code == EXCEPTION_BREAKPOINT ||
seh_code == EXCEPTION_STACK_OVERFLOW) {
return EXCEPTION_CONTINUE_SEARCH; // Don't handle these exceptions
}
internal::ReportFailureInUnknownLocation(
TestPartResult::kFatalFailure,
FormatSehExceptionMessage(seh_code, location) +
"\n"
"Stack trace:\n" +
::testing::internal::GetCurrentOsStackTraceExceptTop(1));
return EXCEPTION_EXECUTE_HANDLER;
}
#endif // GTEST_HAS_SEH
} // namespace internal
// The c'tor sets this object as the test part result reporter used by
// Google Test. The 'result' parameter specifies where to report the
// results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
TestPartResultArray* result)
: intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
Init();
}
// The c'tor sets this object as the test part result reporter used by
// Google Test. The 'result' parameter specifies where to report the
// results.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
InterceptMode intercept_mode, TestPartResultArray* result)
: intercept_mode_(intercept_mode), result_(result) {
Init();
}
void ScopedFakeTestPartResultReporter::Init() {
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
old_reporter_ = impl->GetGlobalTestPartResultReporter();
impl->SetGlobalTestPartResultReporter(this);
} else {
old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
impl->SetTestPartResultReporterForCurrentThread(this);
}
}
// The d'tor restores the test part result reporter used by Google Test
// before.
ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
impl->SetGlobalTestPartResultReporter(old_reporter_);
} else {
impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
}
}
// Increments the test part result count and remembers the result.
// This method is from the TestPartResultReporterInterface interface.
void ScopedFakeTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) {
result_->Append(result);
}
namespace internal {
// Returns the type ID of ::testing::Test. We should always call this
// instead of GetTypeId< ::testing::Test>() to get the type ID of
// testing::Test. This is to work around a suspected linker bug when
// using Google Test as a framework on Mac OS X. The bug causes
// GetTypeId< ::testing::Test>() to return different values depending
// on whether the call is from the Google Test framework itself or
// from user test code. GetTestTypeId() is guaranteed to always
// return the same value, as it always calls GetTypeId<>() from the
// gtest.cc, which is within the Google Test framework.
TypeId GetTestTypeId() { return GetTypeId<Test>(); }
// The value of GetTestTypeId() as seen from within the Google Test
// library. This is solely for testing GetTestTypeId().
extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
// This predicate-formatter checks that 'results' contains a test part
// failure of the given type and that the failure message contains the
// given substring.
static AssertionResult HasOneFailure(const char* /* results_expr */,
const char* /* type_expr */,
const char* /* substr_expr */,
const TestPartResultArray& results,