"test/infiniop/dequantize_awq.py" did not exist on "505e0d4b35151ab08551d17166fc640626704902"
gtest.h 86.5 KB
Newer Older
shiqian's avatar
shiqian committed
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
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
//
// The Google C++ Testing Framework (Google Test)
//
// This header file defines the public API for Google Test.  It should be
// included by any test program that uses Google Test.
//
// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
// leave some internal implementation details in this header file.
// They are clearly marked by comments like this:
//
//   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
//
// Such code is NOT meant to be used by a user directly, and is subject
// to CHANGE WITHOUT NOTICE.  Therefore DO NOT DEPEND ON IT in a user
// program!
//
// Acknowledgment: Google Test borrowed the idea of automatic test
// registration from Barthelemy Dagenais' (barthelemy@prologique.com)
// easyUnit framework.

#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_H_

54
#include <limits>
55
#include <ostream>
56
57
#include <vector>

58
59
60
61
62
63
64
65
66
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h"
#include "gtest/gtest-death-test.h"
#include "gtest/gtest-message.h"
#include "gtest/gtest-param-test.h"
#include "gtest/gtest-printers.h"
#include "gtest/gtest_prod.h"
#include "gtest/gtest-test-part.h"
#include "gtest/gtest-typed-test.h"
shiqian's avatar
shiqian committed
67
68

// Depending on the platform, different string classes are available.
69
70
71
72
// On Linux, in addition to ::std::string, Google also makes use of
// class ::string, which has the same interface as ::std::string, but
// has a different implementation.
//
73
// You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that
74
75
// ::string is available AND is a distinct type to ::std::string, or
// define it to 0 to indicate otherwise.
shiqian's avatar
shiqian committed
76
//
77
78
// If ::std::string and ::string are the same class on your platform
// due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0.
shiqian's avatar
shiqian committed
79
//
80
// If you do not define GTEST_HAS_GLOBAL_STRING, it is defined
81
// heuristically.
shiqian's avatar
shiqian committed
82
83
84

namespace testing {

Gennadiy Civil's avatar
 
Gennadiy Civil committed
85
86
// Silence C4100 (unreferenced formal parameter) and 4805
// unsafe mix of type 'const int' and type 'const bool'
Gennadiy Civil's avatar
 
Gennadiy Civil committed
87
88
#ifdef _MSC_VER
# pragma warning(push)
Gennadiy Civil's avatar
 
Gennadiy Civil committed
89
# pragma warning(disable:4805)
Gennadiy Civil's avatar
 
Gennadiy Civil committed
90
# pragma warning(disable:4100)
Gennadiy Civil's avatar
 
Gennadiy Civil committed
91
92
93
#endif


94
// Declares the flags.
shiqian's avatar
shiqian committed
95

96
97
98
99
100
101
// This flag temporary enables the disabled tests.
GTEST_DECLARE_bool_(also_run_disabled_tests);

// This flag brings the debugger on an assertion failure.
GTEST_DECLARE_bool_(break_on_failure);

102
103
// This flag controls whether Google Test catches all test-thrown exceptions
// and logs them as failures.
104
105
GTEST_DECLARE_bool_(catch_exceptions);

106
107
// This flag enables using colors in terminal output. Available values are
// "yes" to enable colors, "no" (disable colors), or "auto" (the default)
108
109
110
// to let Google Test decide.
GTEST_DECLARE_string_(color);

111
// This flag sets up the filter to select by name using a glob pattern
112
113
114
// the tests to run. If the filter is not given all tests are executed.
GTEST_DECLARE_string_(filter);

115
// This flag causes the Google Test to list tests. None of the tests listed
116
117
118
119
120
121
122
// are actually run if the flag is provided.
GTEST_DECLARE_bool_(list_tests);

// This flag controls whether Google Test emits a detailed XML report to a file
// in addition to its normal textual output.
GTEST_DECLARE_string_(output);

123
// This flags control whether Google Test prints the elapsed time for each
124
125
126
// test.
GTEST_DECLARE_bool_(print_time);

Gennadiy Civil's avatar
Gennadiy Civil committed
127
128
129
// This flags control whether Google Test prints UTF8 characters as text.
GTEST_DECLARE_bool_(print_utf8);

130
131
132
// This flag specifies the random number seed.
GTEST_DECLARE_int32_(random_seed);

133
// This flag sets how many times the tests are repeated. The default value
134
135
// is 1. If the value is -1 the tests are repeating forever.
GTEST_DECLARE_int32_(repeat);
shiqian's avatar
shiqian committed
136
137
138

// This flag controls whether Google Test includes Google Test internal
// stack frames in failure stack traces.
shiqian's avatar
shiqian committed
139
GTEST_DECLARE_bool_(show_internal_stack_frames);
shiqian's avatar
shiqian committed
140

141
// When this flag is specified, tests' order is randomized on every iteration.
142
143
GTEST_DECLARE_bool_(shuffle);

144
145
146
147
// This flag specifies the maximum number of stack frames to be
// printed in a failure message.
GTEST_DECLARE_int32_(stack_trace_depth);

148
149
// When this flag is specified, a failed assertion will throw an
// exception if exceptions are enabled, or exit the program with a
150
// non-zero code otherwise. For use with an external test framework.
151
152
GTEST_DECLARE_bool_(throw_on_failure);

153
154
155
156
157
// When this flag is set with a "host:port" string, on supported
// platforms test results are streamed to the specified port on
// the specified host machine.
GTEST_DECLARE_string_(stream_result_to);

158
159
160
// The upper limit for valid stack trace depths.
const int kMaxStackTraceDepth = 100;

shiqian's avatar
shiqian committed
161
162
namespace internal {

163
class AssertHelper;
164
165
class DefaultGlobalTestPartResultReporter;
class ExecDeathTest;
166
class NoExecDeathTest;
167
class FinalSuccessChecker;
shiqian's avatar
shiqian committed
168
class GTestFlagSaver;
kosak's avatar
kosak committed
169
class StreamingListenerTest;
170
class TestResultAccessor;
171
class TestEventListenersAccessor;
172
class TestEventRepeater;
173
class UnitTestRecordPropertyTestHelper;
174
class WindowsDeathTest;
175
class UnitTestImpl* GetUnitTestImpl();
176
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
177
                                    const std::string& message);
shiqian's avatar
shiqian committed
178
179
180

}  // namespace internal

181
182
183
184
185
186
187
188
// The friend relationship of some of these classes is cyclic.
// If we don't forward declare them the compiler might confuse the classes
// in friendship clauses with same named classes on the scope.
class Test;
class TestCase;
class TestInfo;
class UnitTest;

shiqian's avatar
shiqian committed
189
190
// A class for indicating whether an assertion was successful.  When
// the assertion wasn't successful, the AssertionResult object
191
// remembers a non-empty message that describes how it failed.
shiqian's avatar
shiqian committed
192
//
193
// To create an instance of this class, use one of the factory functions
shiqian's avatar
shiqian committed
194
195
// (AssertionSuccess() and AssertionFailure()).
//
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
// This class is useful for two purposes:
//   1. Defining predicate functions to be used with Boolean test assertions
//      EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
//   2. Defining predicate-format functions to be
//      used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
//
// For example, if you define IsEven predicate:
//
//   testing::AssertionResult IsEven(int n) {
//     if ((n % 2) == 0)
//       return testing::AssertionSuccess();
//     else
//       return testing::AssertionFailure() << n << " is odd";
//   }
//
// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
// will print the message
//
//   Value of: IsEven(Fib(5))
//     Actual: false (5 is odd)
//   Expected: true
//
// instead of a more opaque
//
//   Value of: IsEven(Fib(5))
//     Actual: false
//   Expected: true
//
// in case IsEven is a simple Boolean predicate.
//
// If you expect your predicate to be reused and want to support informative
// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
// about half as often as positive ones in our tests), supply messages for
// both success and failure cases:
//
//   testing::AssertionResult IsEven(int n) {
//     if ((n % 2) == 0)
//       return testing::AssertionSuccess() << n << " is even";
//     else
//       return testing::AssertionFailure() << n << " is odd";
//   }
//
// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
//
//   Value of: IsEven(Fib(6))
//     Actual: true (8 is even)
//   Expected: false
//
// NB: Predicates that support negative Boolean assertions have reduced
// performance in positive ones so be careful not to use them in tests
// that have lots (tens of thousands) of positive Boolean assertions.
//
// To use this class with EXPECT_PRED_FORMAT assertions such as:
shiqian's avatar
shiqian committed
249
250
251
252
//
//   // Verifies that Foo() returns an even number.
//   EXPECT_PRED_FORMAT1(IsEven, Foo());
//
253
// you need to define:
shiqian's avatar
shiqian committed
254
255
//
//   testing::AssertionResult IsEven(const char* expr, int n) {
256
257
258
259
260
//     if ((n % 2) == 0)
//       return testing::AssertionSuccess();
//     else
//       return testing::AssertionFailure()
//         << "Expected: " << expr << " is even\n  Actual: it's " << n;
shiqian's avatar
shiqian committed
261
262
263
264
265
266
//   }
//
// If Foo() returns 5, you will see the following message:
//
//   Expected: Foo() is even
//     Actual: it's 5
267
//
268
class GTEST_API_ AssertionResult {
shiqian's avatar
shiqian committed
269
 public:
270
271
272
  // Copy constructor.
  // Used in EXPECT_TRUE/FALSE(assertion_result).
  AssertionResult(const AssertionResult& other);
billydonahue's avatar
billydonahue committed
273

274
#if defined(_MSC_VER) && _MSC_VER < 1910
billydonahue's avatar
billydonahue committed
275
  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
276
#endif
billydonahue's avatar
billydonahue committed
277

278
  // Used in the EXPECT_TRUE/FALSE(bool_expression).
billydonahue's avatar
billydonahue committed
279
280
281
282
283
284
285
286
287
288
289
290
291
292
  //
  // T must be contextually convertible to bool.
  //
  // The second parameter prevents this overload from being considered if
  // the argument is implicitly convertible to AssertionResult. In that case
  // we want AssertionResult's copy constructor to be used.
  template <typename T>
  explicit AssertionResult(
      const T& success,
      typename internal::EnableIf<
          !internal::ImplicitlyConvertible<T, AssertionResult>::value>::type*
          /*enabler*/ = NULL)
      : success_(success) {}

293
#if defined(_MSC_VER) && _MSC_VER < 1910
billydonahue's avatar
billydonahue committed
294
  GTEST_DISABLE_MSC_WARNINGS_POP_()
295
#endif
billydonahue's avatar
billydonahue committed
296
297
298
299
300
301

  // Assignment operator.
  AssertionResult& operator=(AssertionResult other) {
    swap(other);
    return *this;
  }
shiqian's avatar
shiqian committed
302
303

  // Returns true iff the assertion succeeded.
304
305
306
307
308
309
310
311
312
313
  operator bool() const { return success_; }  // NOLINT

  // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  AssertionResult operator!() const;

  // Returns the text streamed into this AssertionResult. Test assertions
  // use it when they fail (i.e., the predicate's outcome doesn't match the
  // assertion's expectation). When nothing has been streamed into the
  // object, returns an empty string.
  const char* message() const {
314
    return message_.get() != NULL ?  message_->c_str() : "";
315
316
317
318
  }
  // TODO(vladl@google.com): Remove this after making sure no clients use it.
  // Deprecated; please use message() instead.
  const char* failure_message() const { return message(); }
shiqian's avatar
shiqian committed
319

320
  // Streams a custom failure message into this object.
321
322
323
324
325
326
327
328
329
330
331
332
  template <typename T> AssertionResult& operator<<(const T& value) {
    AppendMessage(Message() << value);
    return *this;
  }

  // Allows streaming basic output manipulators such as endl or flush into
  // this object.
  AssertionResult& operator<<(
      ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
    AppendMessage(Message() << basic_manipulator);
    return *this;
  }
shiqian's avatar
shiqian committed
333
334

 private:
335
336
337
338
339
340
  // Appends the contents of message to message_.
  void AppendMessage(const Message& a_message) {
    if (message_.get() == NULL)
      message_.reset(new ::std::string);
    message_->append(a_message.GetString().c_str());
  }
341

billydonahue's avatar
billydonahue committed
342
343
344
  // Swap the contents of this AssertionResult with other.
  void swap(AssertionResult& other);

345
346
347
348
349
350
  // Stores result of the assertion predicate.
  bool success_;
  // Stores the message describing the condition in case the expectation
  // construct is not satisfied with the predicate's outcome.
  // Referenced via a pointer to avoid taking too much stack frame space
  // with test assertions.
351
352
  internal::scoped_ptr< ::std::string> message_;
};
shiqian's avatar
shiqian committed
353
354

// Makes a successful assertion result.
355
GTEST_API_ AssertionResult AssertionSuccess();
shiqian's avatar
shiqian committed
356

357
// Makes a failed assertion result.
358
GTEST_API_ AssertionResult AssertionFailure();
359

shiqian's avatar
shiqian committed
360
// Makes a failed assertion result with the given failure message.
361
// Deprecated; use AssertionFailure() << msg.
362
GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
shiqian's avatar
shiqian committed
363

Gennadiy Civil's avatar
Gennadiy Civil committed
364
365
366
367
368
369
370
371
372
}  // namespace testing

// Includes the auto-generated header that implements a family of generic
// predicate assertion macros. This include comes late because it relies on
// APIs declared above.
#include "gtest/gtest_pred_impl.h"

namespace testing {

shiqian's avatar
shiqian committed
373
374
375
376
377
378
379
380
381
382
// The abstract class that all tests inherit from.
//
// In Google Test, a unit test program contains one or many TestCases, and
// each TestCase contains one or many Tests.
//
// When you define a test using the TEST macro, you don't need to
// explicitly derive from Test - the TEST macro automatically does
// this for you.
//
// The only time you derive from Test is when defining a test fixture
Gennadiy Civil's avatar
Gennadiy Civil committed
383
// to be used in a TEST_F.  For example:
shiqian's avatar
shiqian committed
384
385
386
//
//   class FooTest : public testing::Test {
//    protected:
387
388
//     void SetUp() override { ... }
//     void TearDown() override { ... }
shiqian's avatar
shiqian committed
389
390
391
392
393
394
395
//     ...
//   };
//
//   TEST_F(FooTest, Bar) { ... }
//   TEST_F(FooTest, Baz) { ... }
//
// Test is not copyable.
396
class GTEST_API_ Test {
shiqian's avatar
shiqian committed
397
 public:
398
  friend class TestInfo;
shiqian's avatar
shiqian committed
399
400
401

  // Defines types for pointers to functions that set up and tear down
  // a test case.
402
403
  typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc;
  typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc;
shiqian's avatar
shiqian committed
404
405
406
407

  // The d'tor is virtual as we intend to inherit from Test.
  virtual ~Test();

408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
  // Sets up the stuff shared by all tests in this test case.
  //
  // Google Test will call Foo::SetUpTestCase() before running the first
  // test in test case Foo.  Hence a sub-class can define its own
  // SetUpTestCase() method to shadow the one defined in the super
  // class.
  static void SetUpTestCase() {}

  // Tears down the stuff shared by all tests in this test case.
  //
  // Google Test will call Foo::TearDownTestCase() after running the last
  // test in test case Foo.  Hence a sub-class can define its own
  // TearDownTestCase() method to shadow the one defined in the super
  // class.
  static void TearDownTestCase() {}

shiqian's avatar
shiqian committed
424
425
426
  // Returns true iff the current test has a fatal failure.
  static bool HasFatalFailure();

427
428
429
430
431
432
433
  // Returns true iff the current test has a non-fatal failure.
  static bool HasNonfatalFailure();

  // Returns true iff the current test has a (either fatal or
  // non-fatal) failure.
  static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }

434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
  // Logs a property for the current test, test case, or for the entire
  // invocation of the test program when used outside of the context of a
  // test case.  Only the last value for a given key is remembered.  These
  // are public static so they can be called from utility functions that are
  // not members of the test fixture.  Calls to RecordProperty made during
  // lifespan of the test (from the moment its constructor starts to the
  // moment its destructor finishes) will be output in XML as attributes of
  // the <testcase> element.  Properties recorded from fixture's
  // SetUpTestCase or TearDownTestCase are logged as attributes of the
  // corresponding <testsuite> element.  Calls to RecordProperty made in the
  // global context (before or after invocation of RUN_ALL_TESTS and from
  // SetUp/TearDown method of Environment objects registered with Google
  // Test) will be output as attributes of the <testsuites> element.
  static void RecordProperty(const std::string& key, const std::string& value);
  static void RecordProperty(const std::string& key, int value);
shiqian's avatar
shiqian committed
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

 protected:
  // Creates a Test object.
  Test();

  // Sets up the test fixture.
  virtual void SetUp();

  // Tears down the test fixture.
  virtual void TearDown();

 private:
  // Returns true iff the current test has the same fixture class as
  // the first test in the current test case.
  static bool HasSameFixtureClass();

  // Runs the test after the test fixture has been set up.
  //
  // A sub-class must implement this to define the test logic.
  //
  // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
  // Instead, use the TEST or TEST_F macro.
  virtual void TestBody() = 0;

  // Sets up, executes, and tears down the test.
  void Run();

476
477
478
479
  // Deletes self.  We deliberately pick an unusual name for this
  // internal method to avoid clashing with names used in user TESTs.
  void DeleteSelf_() { delete this; }

480
  const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_;
shiqian's avatar
shiqian committed
481

482
  // Often a user misspells SetUp() as Setup() and spends a long time
shiqian's avatar
shiqian committed
483
484
485
486
487
  // wondering why it is never called by Google Test.  The declaration of
  // the following method is solely for catching such an error at
  // compile time:
  //
  //   - The return type is deliberately chosen to be not void, so it
488
489
  //   will be a conflict if void Setup() is declared in the user's
  //   test fixture.
shiqian's avatar
shiqian committed
490
491
  //
  //   - This method is private, so it will be another compiler error
492
  //   if the method is called from the user's test fixture.
shiqian's avatar
shiqian committed
493
494
495
496
497
498
499
500
501
  //
  // DO NOT OVERRIDE THIS FUNCTION.
  //
  // If you see an error about overriding the following function or
  // about it being private, you have mis-spelled SetUp() as Setup().
  struct Setup_should_be_spelled_SetUp {};
  virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }

  // We disallow copying Tests.
shiqian's avatar
shiqian committed
502
  GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
shiqian's avatar
shiqian committed
503
504
};

505
506
typedef internal::TimeInMillis TimeInMillis;

507
508
509
510
511
512
513
514
515
// A copyable object representing a user specified test property which can be
// output as a key/value string pair.
//
// Don't inherit from TestProperty as its destructor is not virtual.
class TestProperty {
 public:
  // C'tor.  TestProperty does NOT have a default constructor.
  // Always use this constructor (with parameters) to create a
  // TestProperty object.
516
  TestProperty(const std::string& a_key, const std::string& a_value) :
517
    key_(a_key), value_(a_value) {
518
519
520
521
522
523
524
525
526
527
528
529
530
  }

  // Gets the user supplied key.
  const char* key() const {
    return key_.c_str();
  }

  // Gets the user supplied value.
  const char* value() const {
    return value_.c_str();
  }

  // Sets a new value, overriding the one supplied in the constructor.
531
  void SetValue(const std::string& new_value) {
532
533
534
535
536
    value_ = new_value;
  }

 private:
  // The key supplied by the user.
537
  std::string key_;
538
  // The value supplied by the user.
539
  std::string value_;
540
541
};

542
543
544
545
546
547
// The result of a single Test.  This includes a list of
// TestPartResults, a list of TestProperties, a count of how many
// death tests there are in the Test, and how much time it took to run
// the Test.
//
// TestResult is not copyable.
548
class GTEST_API_ TestResult {
549
550
551
552
553
554
555
556
557
558
559
 public:
  // Creates an empty TestResult.
  TestResult();

  // D'tor.  Do not inherit from TestResult.
  ~TestResult();

  // Gets the number of all test parts.  This is the sum of the number
  // of successful test parts and the number of failed test parts.
  int total_part_count() const;

560
561
562
  // Returns the number of the test properties.
  int test_property_count() const;

563
564
565
566
  // Returns true iff the test passed (i.e. no test part failed).
  bool Passed() const { return !Failed(); }

  // Returns true iff the test failed.
567
  bool Failed() const;
568
569
570
571
572
573
574
575
576
577

  // Returns true iff the test fatally failed.
  bool HasFatalFailure() const;

  // Returns true iff the test has a non-fatal failure.
  bool HasNonfatalFailure() const;

  // Returns the elapsed time, in milliseconds.
  TimeInMillis elapsed_time() const { return elapsed_time_; }

Gennadiy Civil's avatar
Gennadiy Civil committed
578
579
  // Returns the i-th test part result among all the results. i can range from 0
  // to total_part_count() - 1. If i is not in that range, aborts the program.
580
  const TestPartResult& GetTestPartResult(int i) const;
581
582

  // Returns the i-th test property. i can range from 0 to
583
584
585
  // test_property_count() - 1. If i is not in that range, aborts the
  // program.
  const TestProperty& GetTestProperty(int i) const;
586

587
 private:
588
  friend class TestInfo;
589
  friend class TestCase;
590
  friend class UnitTest;
591
592
593
594
595
  friend class internal::DefaultGlobalTestPartResultReporter;
  friend class internal::ExecDeathTest;
  friend class internal::TestResultAccessor;
  friend class internal::UnitTestImpl;
  friend class internal::WindowsDeathTest;
596

597
  // Gets the vector of TestPartResults.
598
599
  const std::vector<TestPartResult>& test_part_results() const {
    return test_part_results_;
600
601
  }

602
  // Gets the vector of TestProperties.
603
604
  const std::vector<TestProperty>& test_properties() const {
    return test_properties_;
605
606
607
608
  }

  // Sets the elapsed time.
  void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
609
610
611
612
613

  // Adds a test property to the list. The property is validated and may add
  // a non-fatal failure if invalid (e.g., if it conflicts with reserved
  // key names). If a property is already recorded for the same key, the
  // value will be updated, rather than storing multiple values for the same
614
615
616
617
  // key.  xml_element specifies the element for which the property is being
  // recorded and is used for validation.
  void RecordProperty(const std::string& xml_element,
                      const TestProperty& test_property);
618
619
620
621

  // Adds a failure if the key is a reserved attribute of Google Test
  // testcase tags.  Returns true if the property is valid.
  // TODO(russr): Validate attribute names are legal and human readable.
622
623
  static bool ValidateTestProperty(const std::string& xml_element,
                                   const TestProperty& test_property);
624

625
626
627
  // Adds a test part result to the list.
  void AddTestPartResult(const TestPartResult& test_part_result);

628
629
630
631
632
633
634
635
636
637
638
  // Returns the death test count.
  int death_test_count() const { return death_test_count_; }

  // Increments the death test count, returning the new count.
  int increment_death_test_count() { return ++death_test_count_; }

  // Clears the test part results.
  void ClearTestPartResults();

  // Clears the object.
  void Clear();
639

640
641
  // Protects mutable state of the property vector and of owned
  // properties, whose values may be updated.
642
643
  internal::Mutex test_properites_mutex_;

644
  // The vector of TestPartResults
645
  std::vector<TestPartResult> test_part_results_;
646
  // The vector of TestProperties
647
  std::vector<TestProperty> test_properties_;
648
649
650
651
652
653
654
655
656
  // Running count of death tests.
  int death_test_count_;
  // The elapsed time, in milliseconds.
  TimeInMillis elapsed_time_;

  // We disallow copying TestResult.
  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
};  // class TestResult

shiqian's avatar
shiqian committed
657
658
659
660
661
662
663
664
665
666
667
// A TestInfo object stores the following information about a test:
//
//   Test case name
//   Test name
//   Whether the test should be run
//   A function pointer that creates the test object when invoked
//   Test result
//
// The constructor of TestInfo registers itself with the UnitTest
// singleton such that the RUN_ALL_TESTS() macro knows which tests to
// run.
668
class GTEST_API_ TestInfo {
shiqian's avatar
shiqian committed
669
670
671
672
673
674
 public:
  // Destructs a TestInfo object.  This function is not virtual, so
  // don't inherit from TestInfo.
  ~TestInfo();

  // Returns the test case name.
675
  const char* test_case_name() const { return test_case_name_.c_str(); }
shiqian's avatar
shiqian committed
676
677

  // Returns the test name.
678
  const char* name() const { return name_.c_str(); }
shiqian's avatar
shiqian committed
679

680
681
682
683
684
685
686
  // Returns the name of the parameter type, or NULL if this is not a typed
  // or a type-parameterized test.
  const char* type_param() const {
    if (type_param_.get() != NULL)
      return type_param_->c_str();
    return NULL;
  }
687

688
689
690
691
692
693
694
  // Returns the text representation of the value parameter, or NULL if this
  // is not a value-parameterized test.
  const char* value_param() const {
    if (value_param_.get() != NULL)
      return value_param_->c_str();
    return NULL;
  }
695

kosak's avatar
kosak committed
696
697
698
699
700
701
  // Returns the file name where this test is defined.
  const char* file() const { return location_.file.c_str(); }

  // Returns the line where this test is defined.
  int line() const { return location_.line; }

702
703
704
  // Return true if this test should not be run because it's in another shard.
  bool is_in_another_shard() const { return is_in_another_shard_; }

705
706
707
  // Returns true if this test should run, that is if the test is not
  // disabled (or it is disabled but the also_run_disabled_tests flag has
  // been specified) and its full name matches the user-specified filter.
shiqian's avatar
shiqian committed
708
709
710
711
712
713
714
715
716
717
718
719
720
  //
  // Google Test allows the user to filter the tests by their full names.
  // The full name of a test Bar in test case Foo is defined as
  // "Foo.Bar".  Only the tests that match the filter will run.
  //
  // A filter is a colon-separated list of glob (not regex) patterns,
  // optionally followed by a '-' and a colon-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.
  //
  // For example, *A*:Foo.* is a filter that matches any string that
  // contains the character 'A' or starts with "Foo.".
721
  bool should_run() const { return should_run_; }
shiqian's avatar
shiqian committed
722

723
724
  // Returns true iff this test will appear in the XML report.
  bool is_reportable() const {
725
726
727
    // The XML report includes tests matching the filter, excluding those
    // run in other shards.
    return matches_filter_ && !is_in_another_shard_;
728
729
  }

shiqian's avatar
shiqian committed
730
  // Returns the result of the test.
731
  const TestResult* result() const { return &result_; }
732

shiqian's avatar
shiqian committed
733
 private:
zhanyong.wan's avatar
zhanyong.wan committed
734
#if GTEST_HAS_DEATH_TEST
shiqian's avatar
shiqian committed
735
736
  friend class internal::DefaultDeathTestFactory;
#endif  // GTEST_HAS_DEATH_TEST
737
738
  friend class Test;
  friend class TestCase;
shiqian's avatar
shiqian committed
739
  friend class internal::UnitTestImpl;
kosak's avatar
kosak committed
740
  friend class internal::StreamingListenerTest;
741
  friend TestInfo* internal::MakeAndRegisterTestInfo(
742
743
      const char* test_case_name,
      const char* name,
744
745
      const char* type_param,
      const char* value_param,
kosak's avatar
kosak committed
746
      internal::CodeLocation code_location,
747
748
749
750
      internal::TypeId fixture_class_id,
      Test::SetUpTestCaseFunc set_up_tc,
      Test::TearDownTestCaseFunc tear_down_tc,
      internal::TestFactoryBase* factory);
shiqian's avatar
shiqian committed
751

752
753
  // Constructs a TestInfo object. The newly constructed instance assumes
  // ownership of the factory object.
754
755
756
757
  TestInfo(const std::string& test_case_name,
           const std::string& name,
           const char* a_type_param,   // NULL if not a type-parameterized test
           const char* a_value_param,  // NULL if not a value-parameterized test
kosak's avatar
kosak committed
758
           internal::CodeLocation a_code_location,
759
760
           internal::TypeId fixture_class_id,
           internal::TestFactoryBase* factory);
shiqian's avatar
shiqian committed
761

762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
  // Increments the number of death tests encountered in this test so
  // far.
  int increment_death_test_count() {
    return result_.increment_death_test_count();
  }

  // Creates the test object, runs it, records its result, and then
  // deletes it.
  void Run();

  static void ClearTestResult(TestInfo* test_info) {
    test_info->result_.Clear();
  }

  // These fields are immutable properties of the test.
  const std::string test_case_name_;     // Test case name
  const std::string name_;               // Test name
779
780
781
782
783
784
  // Name of the parameter type, or NULL if this is not a typed or a
  // type-parameterized test.
  const internal::scoped_ptr<const ::std::string> type_param_;
  // Text representation of the value parameter, or NULL if this is not a
  // value-parameterized test.
  const internal::scoped_ptr<const ::std::string> value_param_;
kosak's avatar
kosak committed
785
  internal::CodeLocation location_;
786
787
788
789
790
  const internal::TypeId fixture_class_id_;   // ID of the test fixture class
  bool should_run_;                 // True iff this test should run
  bool is_disabled_;                // True iff this test is disabled
  bool matches_filter_;             // True if this test matches the
                                    // user-specified filter.
791
  bool is_in_another_shard_;        // Will be run in another shard.
792
793
794
795
796
797
  internal::TestFactoryBase* const factory_;  // The factory that creates
                                              // the test object

  // This field is mutable and needs to be reset before running the
  // test for the second time.
  TestResult result_;
shiqian's avatar
shiqian committed
798

shiqian's avatar
shiqian committed
799
  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
shiqian's avatar
shiqian committed
800
801
};

802
// A test case, which consists of a vector of TestInfos.
803
804
//
// TestCase is not copyable.
805
class GTEST_API_ TestCase {
806
807
808
809
810
811
812
813
814
 public:
  // Creates a TestCase with the given name.
  //
  // TestCase does NOT have a default constructor.  Always use this
  // constructor to create a TestCase object.
  //
  // Arguments:
  //
  //   name:         name of the test case
815
816
  //   a_type_param: the name of the test's type parameter, or NULL if
  //                 this is not a type-parameterized test.
817
818
  //   set_up_tc:    pointer to the function that sets up the test case
  //   tear_down_tc: pointer to the function that tears down the test case
819
  TestCase(const char* name, const char* a_type_param,
820
821
822
823
824
825
826
827
828
           Test::SetUpTestCaseFunc set_up_tc,
           Test::TearDownTestCaseFunc tear_down_tc);

  // Destructor of TestCase.
  virtual ~TestCase();

  // Gets the name of the TestCase.
  const char* name() const { return name_.c_str(); }

829
830
831
832
833
834
835
  // Returns the name of the parameter type, or NULL if this is not a
  // type-parameterized test case.
  const char* type_param() const {
    if (type_param_.get() != NULL)
      return type_param_->c_str();
    return NULL;
  }
836
837
838
839
840
841
842
843
844
845

  // Returns true if any test in this test case should run.
  bool should_run() const { return should_run_; }

  // Gets the number of successful tests in this test case.
  int successful_test_count() const;

  // Gets the number of failed tests in this test case.
  int failed_test_count() const;

846
847
848
  // Gets the number of disabled tests that will be reported in the XML report.
  int reportable_disabled_test_count() const;

849
850
851
  // Gets the number of disabled tests in this test case.
  int disabled_test_count() const;

852
853
854
  // Gets the number of tests to be printed in the XML report.
  int reportable_test_count() const;

855
856
857
858
859
860
861
862
863
864
865
866
867
  // Get the number of tests in this test case that should run.
  int test_to_run_count() const;

  // Gets the number of all tests in this test case.
  int total_test_count() const;

  // Returns true iff the test case passed.
  bool Passed() const { return !Failed(); }

  // Returns true iff the test case failed.
  bool Failed() const { return failed_test_count() > 0; }

  // Returns the elapsed time, in milliseconds.
868
  TimeInMillis elapsed_time() const { return elapsed_time_; }
869

870
871
872
873
  // Returns the i-th test among all the tests. i can range from 0 to
  // total_test_count() - 1. If i is not in that range, returns NULL.
  const TestInfo* GetTestInfo(int i) const;

874
875
876
877
  // Returns the TestResult that holds test properties recorded during
  // execution of SetUpTestCase and TearDownTestCase.
  const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }

878
 private:
879
  friend class Test;
880
  friend class internal::UnitTestImpl;
881

882
  // Gets the (mutable) vector of TestInfos in this TestCase.
883
  std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
884

885
  // Gets the (immutable) vector of TestInfos in this TestCase.
886
887
  const std::vector<TestInfo*>& test_info_list() const {
    return test_info_list_;
888
889
  }

890
891
892
893
  // Returns the i-th test among all the tests. i can range from 0 to
  // total_test_count() - 1. If i is not in that range, returns NULL.
  TestInfo* GetMutableTestInfo(int i);

894
895
896
  // Sets the should_run member.
  void set_should_run(bool should) { should_run_ = should; }

897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
  // Adds a TestInfo to this test case.  Will delete the TestInfo upon
  // destruction of the TestCase object.
  void AddTestInfo(TestInfo * test_info);

  // Clears the results of all tests in this test case.
  void ClearResult();

  // Clears the results of all tests in the given test case.
  static void ClearTestCaseResult(TestCase* test_case) {
    test_case->ClearResult();
  }

  // Runs every test in this TestCase.
  void Run();

912
913
914
915
916
917
918
919
  // Runs SetUpTestCase() for this TestCase.  This wrapper is needed
  // for catching exceptions thrown from SetUpTestCase().
  void RunSetUpTestCase() { (*set_up_tc_)(); }

  // Runs TearDownTestCase() for this TestCase.  This wrapper is
  // needed for catching exceptions thrown from TearDownTestCase().
  void RunTearDownTestCase() { (*tear_down_tc_)(); }

920
  // Returns true iff test passed.
921
922
923
  static bool TestPassed(const TestInfo* test_info) {
    return test_info->should_run() && test_info->result()->Passed();
  }
924
925

  // Returns true iff test failed.
926
927
928
  static bool TestFailed(const TestInfo* test_info) {
    return test_info->should_run() && test_info->result()->Failed();
  }
929

930
931
932
933
934
935
  // Returns true iff the test is disabled and will be reported in the XML
  // report.
  static bool TestReportableDisabled(const TestInfo* test_info) {
    return test_info->is_reportable() && test_info->is_disabled_;
  }

936
  // Returns true iff test is disabled.
937
938
939
  static bool TestDisabled(const TestInfo* test_info) {
    return test_info->is_disabled_;
  }
940

941
942
943
944
945
  // Returns true iff this test will appear in the XML report.
  static bool TestReportable(const TestInfo* test_info) {
    return test_info->is_reportable();
  }

946
  // Returns true if the given test should run.
947
948
949
  static bool ShouldRunTest(const TestInfo* test_info) {
    return test_info->should_run();
  }
950

951
952
953
954
955
956
  // Shuffles the tests in this test case.
  void ShuffleTests(internal::Random* random);

  // Restores the test order to before the first shuffle.
  void UnshuffleTests();

957
  // Name of the test case.
958
  std::string name_;
959
960
961
  // Name of the parameter type, or NULL if this is not a typed or a
  // type-parameterized test.
  const internal::scoped_ptr<const ::std::string> type_param_;
962
963
  // The vector of TestInfos in their original order.  It owns the
  // elements in the vector.
964
  std::vector<TestInfo*> test_info_list_;
965
966
967
  // Provides a level of indirection for the test list to allow easy
  // shuffling and restoring the test order.  The i-th element in this
  // vector is the index of the i-th test in the shuffled test list.
968
  std::vector<int> test_indices_;
969
970
971
972
973
974
975
  // Pointer to the function that sets up the test case.
  Test::SetUpTestCaseFunc set_up_tc_;
  // Pointer to the function that tears down the test case.
  Test::TearDownTestCaseFunc tear_down_tc_;
  // True iff any test in this test case should run.
  bool should_run_;
  // Elapsed time, in milliseconds.
976
  TimeInMillis elapsed_time_;
977
978
979
  // Holds test properties recorded during execution of SetUpTestCase and
  // TearDownTestCase.
  TestResult ad_hoc_test_result_;
980
981
982
983
984

  // We disallow copying TestCases.
  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase);
};

shiqian's avatar
shiqian committed
985
// An Environment object is capable of setting up and tearing down an
986
// environment.  You should subclass this to define your own
shiqian's avatar
shiqian committed
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
// environment(s).
//
// An Environment object does the set-up and tear-down in virtual
// methods SetUp() and TearDown() instead of the constructor and the
// destructor, as:
//
//   1. You cannot safely throw from a destructor.  This is a problem
//      as in some cases Google Test is used where exceptions are enabled, and
//      we may want to implement ASSERT_* using exceptions where they are
//      available.
//   2. You cannot use ASSERT_* directly in a constructor or
//      destructor.
class Environment {
 public:
  // The d'tor is virtual as we need to subclass Environment.
  virtual ~Environment() {}

  // Override this to define how to set up the environment.
  virtual void SetUp() {}

  // Override this to define how to tear down the environment.
  virtual void TearDown() {}
 private:
  // If you see an error about overriding the following function or
  // about it being private, you have mis-spelled SetUp() as Setup().
  struct Setup_should_be_spelled_SetUp {};
  virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
};

1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
#if GTEST_HAS_EXCEPTIONS

// Exception which can be thrown from TestEventListener::OnTestPartResult.
class GTEST_API_ AssertionException
    : public internal::GoogleTestFailureException {
 public:
  explicit AssertionException(const TestPartResult& result)
      : GoogleTestFailureException(result) {}
};

#endif  // GTEST_HAS_EXCEPTIONS

1028
1029
// The interface for tracing execution of tests. The methods are organized in
// the order the corresponding events are fired.
1030
class TestEventListener {
1031
 public:
1032
  virtual ~TestEventListener() {}
1033

1034
1035
  // Fired before any test activity starts.
  virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
1036

1037
1038
1039
1040
1041
1042
1043
1044
  // Fired before each iteration of tests starts.  There may be more than
  // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
  // index, starting from 0.
  virtual void OnTestIterationStart(const UnitTest& unit_test,
                                    int iteration) = 0;

  // Fired before environment set-up for each iteration of tests starts.
  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
1045

1046
1047
  // Fired after environment set-up for each iteration of tests ends.
  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
1048

1049
1050
  // Fired before the test case starts.
  virtual void OnTestCaseStart(const TestCase& test_case) = 0;
1051

1052
  // Fired before the test starts.
1053
1054
  virtual void OnTestStart(const TestInfo& test_info) = 0;

1055
  // Fired after a failed assertion or a SUCCEED() invocation.
1056
1057
  // If you want to throw an exception from this function to skip to the next
  // TEST, it must be AssertionException defined above, or inherited from it.
1058
1059
  virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;

1060
  // Fired after the test ends.
1061
1062
  virtual void OnTestEnd(const TestInfo& test_info) = 0;

1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
  // Fired after the test case ends.
  virtual void OnTestCaseEnd(const TestCase& test_case) = 0;

  // Fired before environment tear-down for each iteration of tests starts.
  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;

  // Fired after environment tear-down for each iteration of tests ends.
  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;

  // Fired after each iteration of tests finishes.
  virtual void OnTestIterationEnd(const UnitTest& unit_test,
                                  int iteration) = 0;

  // Fired after all test activities have ended.
  virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
1078
1079
1080
1081
};

// The convenience class for users who need to override just one or two
// methods and are not concerned that a possible change to a signature of
1082
1083
1084
1085
// the methods they override will not be caught during the build.  For
// comments about each method please see the definition of TestEventListener
// above.
class EmptyTestEventListener : public TestEventListener {
1086
 public:
1087
1088
1089
1090
1091
  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
  virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
                                    int /*iteration*/) {}
  virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {}
  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
1092
1093
  virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
  virtual void OnTestStart(const TestInfo& /*test_info*/) {}
1094
  virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {}
1095
1096
1097
1098
1099
1100
1101
  virtual void OnTestEnd(const TestInfo& /*test_info*/) {}
  virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
  virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {}
  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
  virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
                                  int /*iteration*/) {}
  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
1102
1103
};

1104
// TestEventListeners lets users add listeners to track events in Google Test.
1105
class GTEST_API_ TestEventListeners {
1106
 public:
1107
1108
  TestEventListeners();
  ~TestEventListeners();
1109
1110
1111
1112

  // Appends an event listener to the end of the list. Google Test assumes
  // the ownership of the listener (i.e. it will delete the listener when
  // the test program finishes).
1113
  void Append(TestEventListener* listener);
1114
1115
1116
1117

  // Removes the given event listener from the list and returns it.  It then
  // becomes the caller's responsibility to delete the listener. Returns
  // NULL if the listener is not found in the list.
1118
  TestEventListener* Release(TestEventListener* listener);
1119
1120
1121
1122
1123
1124

  // Returns the standard listener responsible for the default console
  // output.  Can be removed from the listeners list to shut down default
  // console output.  Note that removing this object from the listener list
  // with Release transfers its ownership to the caller and makes this
  // function return NULL the next time.
1125
  TestEventListener* default_result_printer() const {
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
    return default_result_printer_;
  }

  // Returns the standard listener responsible for the default XML output
  // controlled by the --gtest_output=xml flag.  Can be removed from the
  // listeners list by users who want to shut down the default XML output
  // controlled by this flag and substitute it with custom one.  Note that
  // removing this object from the listener list with Release transfers its
  // ownership to the caller and makes this function return NULL the next
  // time.
1136
  TestEventListener* default_xml_generator() const {
1137
1138
1139
1140
    return default_xml_generator_;
  }

 private:
1141
  friend class TestCase;
1142
  friend class TestInfo;
1143
1144
  friend class internal::DefaultGlobalTestPartResultReporter;
  friend class internal::NoExecDeathTest;
1145
  friend class internal::TestEventListenersAccessor;
1146
1147
  friend class internal::UnitTestImpl;

1148
1149
1150
  // Returns repeater that broadcasts the TestEventListener events to all
  // subscribers.
  TestEventListener* repeater();
1151
1152
1153
1154
1155
1156

  // Sets the default_result_printer attribute to the provided listener.
  // The listener is also added to the listener list and previous
  // default_result_printer is removed from it and deleted. The listener can
  // also be NULL in which case it will not be added to the list. Does
  // nothing if the previous and the current listener objects are the same.
1157
  void SetDefaultResultPrinter(TestEventListener* listener);
1158
1159
1160
1161
1162
1163

  // Sets the default_xml_generator attribute to the provided listener.  The
  // listener is also added to the listener list and previous
  // default_xml_generator is removed from it and deleted. The listener can
  // also be NULL in which case it will not be added to the list. Does
  // nothing if the previous and the current listener objects are the same.
1164
  void SetDefaultXmlGenerator(TestEventListener* listener);
1165
1166
1167
1168
1169
1170
1171

  // Controls whether events will be forwarded by the repeater to the
  // listeners in the list.
  bool EventForwardingEnabled() const;
  void SuppressEventForwarding();

  // The actual list of listeners.
1172
  internal::TestEventRepeater* repeater_;
1173
  // Listener responsible for the standard result output.
1174
  TestEventListener* default_result_printer_;
1175
  // Listener responsible for the creation of the XML output file.
1176
  TestEventListener* default_xml_generator_;
1177

1178
1179
  // We disallow copying TestEventListeners.
  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
1180
1181
};

1182
// A UnitTest consists of a vector of TestCases.
shiqian's avatar
shiqian committed
1183
1184
1185
1186
1187
1188
1189
1190
1191
//
// This is a singleton class.  The only instance of UnitTest is
// created when UnitTest::GetInstance() is first called.  This
// instance is never deleted.
//
// UnitTest is not copyable.
//
// This class is thread-safe as long as the methods are called
// according to their specification.
1192
class GTEST_API_ UnitTest {
shiqian's avatar
shiqian committed
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
 public:
  // Gets the singleton UnitTest object.  The first time this method
  // is called, a UnitTest object is constructed and returned.
  // Consecutive calls will return the same object.
  static UnitTest* GetInstance();

  // Runs all tests in this UnitTest object and prints the result.
  // Returns 0 if successful, or 1 otherwise.
  //
  // This method can only be called from the main thread.
  //
  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
shiqian's avatar
shiqian committed
1205
  int Run() GTEST_MUST_USE_RESULT_;
shiqian's avatar
shiqian committed
1206

1207
1208
1209
1210
  // Returns the working directory when the first TEST() or TEST_F()
  // was executed.  The UnitTest object owns the string.
  const char* original_working_dir() const;

shiqian's avatar
shiqian committed
1211
1212
  // Returns the TestCase object for the test that's currently running,
  // or NULL if no test is running.
1213
1214
  const TestCase* current_test_case() const
      GTEST_LOCK_EXCLUDED_(mutex_);
shiqian's avatar
shiqian committed
1215
1216
1217

  // Returns the TestInfo object for the test that's currently running,
  // or NULL if no test is running.
1218
1219
  const TestInfo* current_test_info() const
      GTEST_LOCK_EXCLUDED_(mutex_);
shiqian's avatar
shiqian committed
1220

1221
1222
1223
  // Returns the random seed used at the start of the current test run.
  int random_seed() const;

1224
1225
  // Returns the ParameterizedTestCaseRegistry object used to keep track of
  // value-parameterized tests and instantiate and register them.
1226
1227
  //
  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1228
1229
  internal::ParameterizedTestCaseRegistry& parameterized_test_registry()
      GTEST_LOCK_EXCLUDED_(mutex_);
1230

1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
  // Gets the number of successful test cases.
  int successful_test_case_count() const;

  // Gets the number of failed test cases.
  int failed_test_case_count() const;

  // Gets the number of all test cases.
  int total_test_case_count() const;

  // Gets the number of all test cases that contain at least one test
  // that should run.
  int test_case_to_run_count() const;

  // Gets the number of successful tests.
  int successful_test_count() const;

  // Gets the number of failed tests.
  int failed_test_count() const;

1250
1251
1252
  // Gets the number of disabled tests that will be reported in the XML report.
  int reportable_disabled_test_count() const;

1253
1254
1255
  // Gets the number of disabled tests.
  int disabled_test_count() const;

1256
1257
1258
  // Gets the number of tests to be printed in the XML report.
  int reportable_test_count() const;

1259
1260
1261
1262
1263
1264
  // Gets the number of all tests.
  int total_test_count() const;

  // Gets the number of tests that should run.
  int test_to_run_count() const;

1265
1266
1267
1268
  // Gets the time of the test program start, in ms from the start of the
  // UNIX epoch.
  TimeInMillis start_timestamp() const;

1269
  // Gets the elapsed time, in milliseconds.
1270
  TimeInMillis elapsed_time() const;
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280

  // Returns true iff the unit test passed (i.e. all test cases passed).
  bool Passed() const;

  // Returns true iff the unit test failed (i.e. some test case failed
  // or something outside of all tests failed).
  bool Failed() const;

  // Gets the i-th test case among all the test cases. i can range from 0 to
  // total_test_case_count() - 1. If i is not in that range, returns NULL.
1281
  const TestCase* GetTestCase(int i) const;
1282

1283
1284
1285
1286
  // Returns the TestResult containing information on test failures and
  // properties logged outside of individual test cases.
  const TestResult& ad_hoc_test_result() const;

1287
1288
  // Returns the list of event listeners that can be used to track events
  // inside Google Test.
1289
  TestEventListeners& listeners();
1290

1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
 private:
  // Registers and returns a global test environment.  When a test
  // program is run, all global test environments will be set-up in
  // the order they were registered.  After all tests in the program
  // have finished, all global test environments will be torn-down in
  // the *reverse* order they were registered.
  //
  // The UnitTest object takes ownership of the given environment.
  //
  // This method can only be called from the main thread.
  Environment* AddEnvironment(Environment* env);

  // Adds a TestPartResult to the current TestResult object.  All
  // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
  // eventually call this to report their results.  The user code
  // should use the assertion macros instead of calling this directly.
  void AddTestPartResult(TestPartResult::Type result_type,
                         const char* file_name,
                         int line_number,
1310
1311
                         const std::string& message,
                         const std::string& os_stack_trace)
1312
      GTEST_LOCK_EXCLUDED_(mutex_);
1313

1314
1315
1316
1317
1318
1319
  // Adds a TestProperty to the current TestResult object when invoked from
  // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
  // from SetUpTestCase or TearDownTestCase, or to the global property set
  // when invoked elsewhere.  If the result already contains a property with
  // the same key, the value will be updated.
  void RecordProperty(const std::string& key, const std::string& value);
1320

1321
1322
1323
1324
  // Gets the i-th test case among all the test cases. i can range from 0 to
  // total_test_case_count() - 1. If i is not in that range, returns NULL.
  TestCase* GetMutableTestCase(int i);

1325
1326
1327
1328
  // Accessors for the implementation object.
  internal::UnitTestImpl* impl() { return impl_; }
  const internal::UnitTestImpl* impl() const { return impl_; }

Nico Weber's avatar
Nico Weber committed
1329
  // These classes and functions are friends as they need to access private
1330
  // members of UnitTest.
1331
  friend class ScopedTrace;
1332
1333
  friend class Test;
  friend class internal::AssertHelper;
kosak's avatar
kosak committed
1334
  friend class internal::StreamingListenerTest;
1335
  friend class internal::UnitTestRecordPropertyTestHelper;
1336
1337
1338
  friend Environment* AddGlobalTestEnvironment(Environment* env);
  friend internal::UnitTestImpl* internal::GetUnitTestImpl();
  friend void internal::ReportFailureInUnknownLocation(
1339
      TestPartResult::Type result_type,
1340
      const std::string& message);
shiqian's avatar
shiqian committed
1341
1342
1343
1344
1345
1346
1347
1348
1349

  // Creates an empty UnitTest.
  UnitTest();

  // D'tor
  virtual ~UnitTest();

  // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  // Google Test trace stack.
1350
1351
  void PushGTestTrace(const internal::TraceInfo& trace)
      GTEST_LOCK_EXCLUDED_(mutex_);
shiqian's avatar
shiqian committed
1352
1353

  // Pops a trace from the per-thread Google Test trace stack.
1354
1355
  void PopGTestTrace()
      GTEST_LOCK_EXCLUDED_(mutex_);
shiqian's avatar
shiqian committed
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367

  // Protects mutable state in *impl_.  This is mutable as some const
  // methods need to lock it too.
  mutable internal::Mutex mutex_;

  // Opaque implementation object.  This field is never changed once
  // the object is constructed.  We don't mark it as const here, as
  // doing so will cause a warning in the constructor of UnitTest.
  // Mutable state in *impl_ is protected by mutex_.
  internal::UnitTestImpl* impl_;

  // We disallow copying UnitTest.
shiqian's avatar
shiqian committed
1368
  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
shiqian's avatar
shiqian committed
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
};

// A convenient wrapper for adding an environment for the test
// program.
//
// You should call this before RUN_ALL_TESTS() is called, probably in
// main().  If you use gtest_main, you need to call this before main()
// starts for it to take effect.  For example, you can define a global
// variable like this:
//
//   testing::Environment* const foo_env =
//       testing::AddGlobalTestEnvironment(new FooEnvironment);
//
// However, we strongly recommend you to write your own main() and
// call AddGlobalTestEnvironment() there, as relying on initialization
// of global variables makes the code harder to read and may cause
// problems when you register multiple environments from different
// translation units and the environments have dependencies among them
// (remember that the compiler doesn't guarantee the order in which
// global variables from different translation units are initialized).
inline Environment* AddGlobalTestEnvironment(Environment* env) {
  return UnitTest::GetInstance()->AddEnvironment(env);
}

// Initializes Google Test.  This must be called before calling
// RUN_ALL_TESTS().  In particular, it parses a command line for the
// flags that Google Test recognizes.  Whenever a Google Test flag is
// seen, it is removed from argv, and *argc is decremented.
//
// No value is returned.  Instead, the Google Test flag variables are
// updated.
1400
1401
//
// Calling the function for the second time has no user-visible effect.
1402
GTEST_API_ void InitGoogleTest(int* argc, char** argv);
shiqian's avatar
shiqian committed
1403
1404
1405

// This overloaded version can be used in Windows programs compiled in
// UNICODE mode.
1406
GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
shiqian's avatar
shiqian committed
1407
1408
1409

namespace internal {

1410
1411
1412
1413
// Separate the error generating code from the code path to reduce the stack
// frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
// when calling EXPECT_* in a tight loop.
template <typename T1, typename T2>
1414
1415
1416
1417
1418
1419
1420
AssertionResult CmpHelperEQFailure(const char* lhs_expression,
                                   const char* rhs_expression,
                                   const T1& lhs, const T2& rhs) {
  return EqFailure(lhs_expression,
                   rhs_expression,
                   FormatForComparisonFailureMessage(lhs, rhs),
                   FormatForComparisonFailureMessage(rhs, lhs),
1421
1422
1423
                   false);
}

shiqian's avatar
shiqian committed
1424
1425
// The helper function for {ASSERT|EXPECT}_EQ.
template <typename T1, typename T2>
1426
1427
1428
1429
1430
AssertionResult CmpHelperEQ(const char* lhs_expression,
                            const char* rhs_expression,
                            const T1& lhs,
                            const T2& rhs) {
  if (lhs == rhs) {
shiqian's avatar
shiqian committed
1431
1432
    return AssertionSuccess();
  }
1433

1434
  return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
shiqian's avatar
shiqian committed
1435
1436
1437
1438
1439
}

// With this overloaded version, we allow anonymous enums to be used
// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
// can be implicitly cast to BiggestInt.
1440
1441
1442
1443
GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression,
                                       const char* rhs_expression,
                                       BiggestInt lhs,
                                       BiggestInt rhs);
shiqian's avatar
shiqian committed
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453

// The helper class for {ASSERT|EXPECT}_EQ.  The template argument
// lhs_is_null_literal is true iff the first argument to ASSERT_EQ()
// is a null pointer literal.  The following default implementation is
// for lhs_is_null_literal being false.
template <bool lhs_is_null_literal>
class EqHelper {
 public:
  // This templatized version is for the general case.
  template <typename T1, typename T2>
1454
1455
1456
1457
1458
  static AssertionResult Compare(const char* lhs_expression,
                                 const char* rhs_expression,
                                 const T1& lhs,
                                 const T2& rhs) {
    return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
shiqian's avatar
shiqian committed
1459
1460
1461
1462
1463
1464
1465
1466
  }

  // With this overloaded version, we allow anonymous enums to be used
  // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
  // enums can be implicitly cast to BiggestInt.
  //
  // Even though its body looks the same as the above version, we
  // cannot merge the two, as it will make anonymous enums unhappy.
1467
1468
1469
1470
1471
  static AssertionResult Compare(const char* lhs_expression,
                                 const char* rhs_expression,
                                 BiggestInt lhs,
                                 BiggestInt rhs) {
    return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
shiqian's avatar
shiqian committed
1472
1473
1474
1475
  }
};

// This specialization is used when the first argument to ASSERT_EQ()
1476
// is a null pointer literal, like NULL, false, or 0.
shiqian's avatar
shiqian committed
1477
1478
1479
1480
1481
1482
1483
1484
template <>
class EqHelper<true> {
 public:
  // We define two overloaded versions of Compare().  The first
  // version will be picked when the second argument to ASSERT_EQ() is
  // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or
  // EXPECT_EQ(false, a_bool).
  template <typename T1, typename T2>
1485
  static AssertionResult Compare(
1486
1487
1488
1489
      const char* lhs_expression,
      const char* rhs_expression,
      const T1& lhs,
      const T2& rhs,
1490
1491
1492
1493
1494
1495
      // The following line prevents this overload from being considered if T2
      // is not a pointer type.  We need this because ASSERT_EQ(NULL, my_ptr)
      // expands to Compare("", "", NULL, my_ptr), which requires a conversion
      // to match the Secret* in the other overload, which would otherwise make
      // this template match better.
      typename EnableIf<!is_pointer<T2>::value>::type* = 0) {
1496
    return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
shiqian's avatar
shiqian committed
1497
1498
  }

1499
1500
1501
1502
  // This version will be picked when the second argument to ASSERT_EQ() is a
  // pointer, e.g. ASSERT_EQ(NULL, a_pointer).
  template <typename T>
  static AssertionResult Compare(
1503
1504
      const char* lhs_expression,
      const char* rhs_expression,
1505
1506
1507
1508
1509
1510
      // We used to have a second template parameter instead of Secret*.  That
      // template parameter would deduce to 'long', making this a better match
      // than the first overload even without the first overload's EnableIf.
      // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to
      // non-pointer argument" (even a deduced integral argument), so the old
      // implementation caused warnings in user code.
1511
1512
1513
1514
1515
      Secret* /* lhs (NULL) */,
      T* rhs) {
    // We already know that 'lhs' is a null pointer.
    return CmpHelperEQ(lhs_expression, rhs_expression,
                       static_cast<T*>(NULL), rhs);
shiqian's avatar
shiqian committed
1516
1517
1518
  }
};

1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
// Separate the error generating code from the code path to reduce the stack
// frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
// when calling EXPECT_OP in a tight loop.
template <typename T1, typename T2>
AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
                                   const T1& val1, const T2& val2,
                                   const char* op) {
  return AssertionFailure()
         << "Expected: (" << expr1 << ") " << op << " (" << expr2
         << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
         << " vs " << FormatForComparisonFailureMessage(val2, val1);
}

shiqian's avatar
shiqian committed
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
// A macro for implementing the helper functions needed to implement
// ASSERT_?? and EXPECT_??.  It is here just to avoid copy-and-paste
// of similar code.
//
// For each templatized helper function, we also define an overloaded
// version for BiggestInt in order to reduce code bloat and allow
// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled
// with gcc 4.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1542

shiqian's avatar
shiqian committed
1543
#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
shiqian's avatar
shiqian committed
1544
1545
1546
1547
1548
1549
template <typename T1, typename T2>\
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
                                   const T1& val1, const T2& val2) {\
  if (val1 op val2) {\
    return AssertionSuccess();\
  } else {\
1550
    return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
shiqian's avatar
shiqian committed
1551
1552
  }\
}\
zhanyong.wan's avatar
zhanyong.wan committed
1553
1554
GTEST_API_ AssertionResult CmpHelper##op_name(\
    const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2)
shiqian's avatar
shiqian committed
1555
1556
1557
1558

// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.

// Implements the helper function for {ASSERT|EXPECT}_NE
zhanyong.wan's avatar
zhanyong.wan committed
1559
GTEST_IMPL_CMP_HELPER_(NE, !=);
shiqian's avatar
shiqian committed
1560
// Implements the helper function for {ASSERT|EXPECT}_LE
zhanyong.wan's avatar
zhanyong.wan committed
1561
GTEST_IMPL_CMP_HELPER_(LE, <=);
shiqian's avatar
shiqian committed
1562
// Implements the helper function for {ASSERT|EXPECT}_LT
1563
GTEST_IMPL_CMP_HELPER_(LT, <);
shiqian's avatar
shiqian committed
1564
// Implements the helper function for {ASSERT|EXPECT}_GE
zhanyong.wan's avatar
zhanyong.wan committed
1565
GTEST_IMPL_CMP_HELPER_(GE, >=);
shiqian's avatar
shiqian committed
1566
// Implements the helper function for {ASSERT|EXPECT}_GT
1567
GTEST_IMPL_CMP_HELPER_(GT, >);
shiqian's avatar
shiqian committed
1568

shiqian's avatar
shiqian committed
1569
#undef GTEST_IMPL_CMP_HELPER_
shiqian's avatar
shiqian committed
1570
1571
1572
1573

// The helper function for {ASSERT|EXPECT}_STREQ.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1574
1575
1576
1577
GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
                                          const char* s2_expression,
                                          const char* s1,
                                          const char* s2);
shiqian's avatar
shiqian committed
1578
1579
1580
1581

// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1582
1583
1584
1585
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
                                              const char* s2_expression,
                                              const char* s1,
                                              const char* s2);
shiqian's avatar
shiqian committed
1586
1587
1588
1589

// The helper function for {ASSERT|EXPECT}_STRNE.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1590
1591
1592
1593
GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
                                          const char* s2_expression,
                                          const char* s1,
                                          const char* s2);
shiqian's avatar
shiqian committed
1594
1595
1596
1597

// The helper function for {ASSERT|EXPECT}_STRCASENE.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1598
1599
1600
1601
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
                                              const char* s2_expression,
                                              const char* s1,
                                              const char* s2);
shiqian's avatar
shiqian committed
1602
1603
1604
1605
1606


// Helper function for *_STREQ on wide strings.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1607
1608
1609
1610
GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
                                          const char* s2_expression,
                                          const wchar_t* s1,
                                          const wchar_t* s2);
shiqian's avatar
shiqian committed
1611
1612
1613
1614

// Helper function for *_STRNE on wide strings.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1615
1616
1617
1618
GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
                                          const char* s2_expression,
                                          const wchar_t* s1,
                                          const wchar_t* s2);
shiqian's avatar
shiqian committed
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629

}  // namespace internal

// IsSubstring() and IsNotSubstring() are intended to be used as the
// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
// themselves.  They check whether needle is a substring of haystack
// (NULL is considered a substring of itself only), and return an
// appropriate error message when they fail.
//
// The {needle,haystack}_expr arguments are the stringified
// expressions that generated the two real arguments.
zhanyong.wan's avatar
zhanyong.wan committed
1630
GTEST_API_ AssertionResult IsSubstring(
shiqian's avatar
shiqian committed
1631
1632
    const char* needle_expr, const char* haystack_expr,
    const char* needle, const char* haystack);
zhanyong.wan's avatar
zhanyong.wan committed
1633
GTEST_API_ AssertionResult IsSubstring(
shiqian's avatar
shiqian committed
1634
1635
    const char* needle_expr, const char* haystack_expr,
    const wchar_t* needle, const wchar_t* haystack);
zhanyong.wan's avatar
zhanyong.wan committed
1636
GTEST_API_ AssertionResult IsNotSubstring(
shiqian's avatar
shiqian committed
1637
1638
    const char* needle_expr, const char* haystack_expr,
    const char* needle, const char* haystack);
zhanyong.wan's avatar
zhanyong.wan committed
1639
GTEST_API_ AssertionResult IsNotSubstring(
shiqian's avatar
shiqian committed
1640
1641
    const char* needle_expr, const char* haystack_expr,
    const wchar_t* needle, const wchar_t* haystack);
zhanyong.wan's avatar
zhanyong.wan committed
1642
GTEST_API_ AssertionResult IsSubstring(
shiqian's avatar
shiqian committed
1643
1644
    const char* needle_expr, const char* haystack_expr,
    const ::std::string& needle, const ::std::string& haystack);
zhanyong.wan's avatar
zhanyong.wan committed
1645
GTEST_API_ AssertionResult IsNotSubstring(
shiqian's avatar
shiqian committed
1646
1647
1648
1649
    const char* needle_expr, const char* haystack_expr,
    const ::std::string& needle, const ::std::string& haystack);

#if GTEST_HAS_STD_WSTRING
zhanyong.wan's avatar
zhanyong.wan committed
1650
GTEST_API_ AssertionResult IsSubstring(
shiqian's avatar
shiqian committed
1651
1652
    const char* needle_expr, const char* haystack_expr,
    const ::std::wstring& needle, const ::std::wstring& haystack);
zhanyong.wan's avatar
zhanyong.wan committed
1653
GTEST_API_ AssertionResult IsNotSubstring(
shiqian's avatar
shiqian committed
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
    const char* needle_expr, const char* haystack_expr,
    const ::std::wstring& needle, const ::std::wstring& haystack);
#endif  // GTEST_HAS_STD_WSTRING

namespace internal {

// Helper template function for comparing floating-points.
//
// Template parameter:
//
//   RawType: the raw floating-point type (either float or double)
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename RawType>
1668
1669
1670
1671
1672
AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
                                         const char* rhs_expression,
                                         RawType lhs_value,
                                         RawType rhs_value) {
  const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
shiqian's avatar
shiqian committed
1673
1674
1675
1676
1677

  if (lhs.AlmostEquals(rhs)) {
    return AssertionSuccess();
  }

1678
1679
1680
  ::std::stringstream lhs_ss;
  lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
         << lhs_value;
shiqian's avatar
shiqian committed
1681

1682
1683
1684
  ::std::stringstream rhs_ss;
  rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
         << rhs_value;
shiqian's avatar
shiqian committed
1685

1686
1687
1688
1689
  return EqFailure(lhs_expression,
                   rhs_expression,
                   StringStreamToString(&lhs_ss),
                   StringStreamToString(&rhs_ss),
shiqian's avatar
shiqian committed
1690
1691
1692
1693
1694
1695
                   false);
}

// Helper function for implementing ASSERT_NEAR.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1696
1697
1698
1699
1700
1701
GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
                                                const char* expr2,
                                                const char* abs_error_expr,
                                                double val1,
                                                double val2,
                                                double abs_error);
shiqian's avatar
shiqian committed
1702
1703
1704

// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// A class that enables one to stream messages to assertion macros
1705
class GTEST_API_ AssertHelper {
shiqian's avatar
shiqian committed
1706
1707
 public:
  // Constructor.
1708
1709
1710
  AssertHelper(TestPartResult::Type type,
               const char* file,
               int line,
shiqian's avatar
shiqian committed
1711
               const char* message);
1712
1713
  ~AssertHelper();

shiqian's avatar
shiqian committed
1714
  // Message assignment is a semantic trick to enable assertion
shiqian's avatar
shiqian committed
1715
  // streaming; see the GTEST_MESSAGE_ macro below.
shiqian's avatar
shiqian committed
1716
  void operator=(const Message& message) const;
1717

shiqian's avatar
shiqian committed
1718
 private:
1719
1720
1721
1722
1723
  // We put our data in a struct so that the size of the AssertHelper class can
  // be as small as possible.  This is important because gcc is incapable of
  // re-using stack space even for temporary variables, so every EXPECT_EQ
  // reserves stack space for another AssertHelper.
  struct AssertHelperData {
1724
1725
1726
    AssertHelperData(TestPartResult::Type t,
                     const char* srcfile,
                     int line_num,
1727
1728
1729
                     const char* msg)
        : type(t), file(srcfile), line(line_num), message(msg) { }

1730
    TestPartResult::Type const type;
1731
1732
1733
    const char* const file;
    int const line;
    std::string const message;
1734
1735
1736
1737
1738
1739

   private:
    GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
  };

  AssertHelperData* const data_;
shiqian's avatar
shiqian committed
1740

shiqian's avatar
shiqian committed
1741
  GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
shiqian's avatar
shiqian committed
1742
1743
1744
1745
};

}  // namespace internal

1746
1747
1748
1749
1750
// The pure interface class that all value-parameterized tests inherit from.
// A value-parameterized class must inherit from both ::testing::Test and
// ::testing::WithParamInterface. In most cases that just means inheriting
// from ::testing::TestWithParam, but more complicated test hierarchies
// may need to inherit from Test and WithParamInterface at different levels.
1751
//
1752
// This interface has support for accessing the test parameter value via
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
// the GetParam() method.
//
// Use it with one of the parameter generator defining functions, like Range(),
// Values(), ValuesIn(), Bool(), and Combine().
//
// class FooTest : public ::testing::TestWithParam<int> {
//  protected:
//   FooTest() {
//     // Can use GetParam() here.
//   }
//   virtual ~FooTest() {
//     // Can use GetParam() here.
//   }
//   virtual void SetUp() {
//     // Can use GetParam() here.
//   }
//   virtual void TearDown {
//     // Can use GetParam() here.
//   }
// };
// TEST_P(FooTest, DoesBar) {
//   // Can use GetParam() method here.
//   Foo foo;
//   ASSERT_TRUE(foo.DoesBar(GetParam()));
// }
// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));

template <typename T>
1781
class WithParamInterface {
1782
1783
 public:
  typedef T ParamType;
1784
  virtual ~WithParamInterface() {}
1785
1786

  // The current parameter value. Is also available in the test fixture's
1787
1788
1789
1790
  // constructor. This member function is non-static, even though it only
  // references static data, to reduce the opportunity for incorrect uses
  // like writing 'WithParamInterface<bool>::GetParam()' for a test that
  // uses a fixture whose parameter type is int.
1791
1792
1793
1794
1795
1796
  const ParamType& GetParam() const {
    GTEST_CHECK_(parameter_ != NULL)
        << "GetParam() can only be called inside a value-parameterized test "
        << "-- did you intend to write TEST_P instead of TEST_F?";
    return *parameter_;
  }
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807

 private:
  // Sets parameter value. The caller is responsible for making sure the value
  // remains alive and unchanged throughout the current test.
  static void SetParam(const ParamType* parameter) {
    parameter_ = parameter;
  }

  // Static value used for accessing parameter during a test lifetime.
  static const ParamType* parameter_;

1808
  // TestClass must be a subclass of WithParamInterface<T> and Test.
1809
1810
1811
1812
  template <class TestClass> friend class internal::ParameterizedTestFactory;
};

template <typename T>
1813
1814
1815
1816
1817
1818
1819
1820
const T* WithParamInterface<T>::parameter_ = NULL;

// Most value-parameterized classes can ignore the existence of
// WithParamInterface, and can just inherit from ::testing::TestWithParam.

template <typename T>
class TestWithParam : public Test, public WithParamInterface<T> {
};
1821

shiqian's avatar
shiqian committed
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
// Macros for indicating success/failure in test code.

// ADD_FAILURE unconditionally adds a failure to the current test.
// SUCCEED generates a success - it doesn't automatically make the
// current test successful, as a test is only successful when it has
// no failure.
//
// EXPECT_* verifies that a certain condition is satisfied.  If not,
// it behaves like ADD_FAILURE.  In particular:
//
//   EXPECT_TRUE  verifies that a Boolean condition is true.
//   EXPECT_FALSE verifies that a Boolean condition is false.
//
// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
// that they will also abort the current function on failure.  People
// usually want the fail-fast behavior of FAIL and ASSERT_*, but those
// writing data-driven tests often find themselves using ADD_FAILURE
// and EXPECT_* more.

// Generates a nonfatal failure with a generic message.
shiqian's avatar
shiqian committed
1842
#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
shiqian's avatar
shiqian committed
1843

1844
1845
1846
1847
1848
1849
// Generates a nonfatal failure at the given source file location with
// a generic message.
#define ADD_FAILURE_AT(file, line) \
  GTEST_MESSAGE_AT_(file, line, "Failed", \
                    ::testing::TestPartResult::kNonFatalFailure)

shiqian's avatar
shiqian committed
1850
// Generates a fatal failure with a generic message.
1851
1852
1853
1854
1855
#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")

// Define this macro to 1 to omit the definition of FAIL(), which is a
// generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_FAIL
1856
# define FAIL() GTEST_FAIL()
1857
#endif
shiqian's avatar
shiqian committed
1858
1859

// Generates a success with a generic message.
1860
1861
1862
1863
1864
#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")

// Define this macro to 1 to omit the definition of SUCCEED(), which
// is a generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_SUCCEED
1865
# define SUCCEED() GTEST_SUCCEED()
1866
#endif
shiqian's avatar
shiqian committed
1867

1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
// Macros for testing exceptions.
//
//    * {ASSERT|EXPECT}_THROW(statement, expected_exception):
//         Tests that the statement throws the expected exception.
//    * {ASSERT|EXPECT}_NO_THROW(statement):
//         Tests that the statement doesn't throw any exception.
//    * {ASSERT|EXPECT}_ANY_THROW(statement):
//         Tests that the statement throws an exception.

#define EXPECT_THROW(statement, expected_exception) \
shiqian's avatar
shiqian committed
1878
  GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
1879
#define EXPECT_NO_THROW(statement) \
shiqian's avatar
shiqian committed
1880
  GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1881
#define EXPECT_ANY_THROW(statement) \
shiqian's avatar
shiqian committed
1882
  GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1883
#define ASSERT_THROW(statement, expected_exception) \
shiqian's avatar
shiqian committed
1884
  GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
1885
#define ASSERT_NO_THROW(statement) \
shiqian's avatar
shiqian committed
1886
  GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
1887
#define ASSERT_ANY_THROW(statement) \
shiqian's avatar
shiqian committed
1888
  GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
1889

1890
1891
1892
// Boolean assertions. Condition can be either a Boolean expression or an
// AssertionResult. For more information on how to use AssertionResult with
// these macros see comments on that class.
shiqian's avatar
shiqian committed
1893
#define EXPECT_TRUE(condition) \
Gennadiy Civil's avatar
Gennadiy Civil committed
1894
  GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
shiqian's avatar
shiqian committed
1895
                      GTEST_NONFATAL_FAILURE_)
shiqian's avatar
shiqian committed
1896
#define EXPECT_FALSE(condition) \
shiqian's avatar
shiqian committed
1897
1898
  GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
                      GTEST_NONFATAL_FAILURE_)
shiqian's avatar
shiqian committed
1899
#define ASSERT_TRUE(condition) \
Gennadiy Civil's avatar
Gennadiy Civil committed
1900
  GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
shiqian's avatar
shiqian committed
1901
                      GTEST_FATAL_FAILURE_)
shiqian's avatar
shiqian committed
1902
#define ASSERT_FALSE(condition) \
shiqian's avatar
shiqian committed
1903
1904
  GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
                      GTEST_FATAL_FAILURE_)
shiqian's avatar
shiqian committed
1905
1906
1907

// Macros for testing equalities and inequalities.
//
1908
1909
1910
1911
1912
1913
//    * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
//    * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
//    * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
//    * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
//    * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
//    * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
shiqian's avatar
shiqian committed
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
//
// When they are not, Google Test prints both the tested expressions and
// their actual values.  The values must be compatible built-in types,
// or you will get a compiler error.  By "compatible" we mean that the
// values can be compared by the respective operator.
//
// Note:
//
//   1. It is possible to make a user-defined type work with
//   {ASSERT|EXPECT}_??(), but that requires overloading the
//   comparison operators and is thus discouraged by the Google C++
//   Usage Guide.  Therefore, you are advised to use the
//   {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
//   equal.
//
//   2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
//   pointers (in particular, C strings).  Therefore, if you use it
//   with two C strings, you are testing how their locations in memory
//   are related, not how their content is related.  To compare two C
//   strings by content, use {ASSERT|EXPECT}_STR*().
//
1935
1936
//   3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
//   {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
shiqian's avatar
shiqian committed
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
//   what the actual value is when it fails, and similarly for the
//   other comparisons.
//
//   4. Do not depend on the order in which {ASSERT|EXPECT}_??()
//   evaluate their arguments, which is undefined.
//
//   5. These macros evaluate their arguments exactly once.
//
// Examples:
//
Gennadiy Civil's avatar
Gennadiy Civil committed
1947
1948
//   EXPECT_NE(Foo(), 5);
//   EXPECT_EQ(a_pointer, NULL);
shiqian's avatar
shiqian committed
1949
1950
1951
//   ASSERT_LT(i, array_size);
//   ASSERT_GT(records.size(), 0) << "There is no record left.";

1952
#define EXPECT_EQ(val1, val2) \
shiqian's avatar
shiqian committed
1953
  EXPECT_PRED_FORMAT2(::testing::internal:: \
1954
1955
1956
1957
                      EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \
                      val1, val2)
#define EXPECT_NE(val1, val2) \
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
shiqian's avatar
shiqian committed
1958
1959
1960
1961
1962
1963
1964
1965
1966
#define EXPECT_LE(val1, val2) \
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
#define EXPECT_LT(val1, val2) \
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
#define EXPECT_GE(val1, val2) \
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
#define EXPECT_GT(val1, val2) \
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)

1967
#define GTEST_ASSERT_EQ(val1, val2) \
shiqian's avatar
shiqian committed
1968
  ASSERT_PRED_FORMAT2(::testing::internal:: \
1969
1970
                      EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \
                      val1, val2)
1971
#define GTEST_ASSERT_NE(val1, val2) \
shiqian's avatar
shiqian committed
1972
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
1973
#define GTEST_ASSERT_LE(val1, val2) \
shiqian's avatar
shiqian committed
1974
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
1975
#define GTEST_ASSERT_LT(val1, val2) \
shiqian's avatar
shiqian committed
1976
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
1977
#define GTEST_ASSERT_GE(val1, val2) \
shiqian's avatar
shiqian committed
1978
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
1979
#define GTEST_ASSERT_GT(val1, val2) \
shiqian's avatar
shiqian committed
1980
1981
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)

1982
1983
1984
1985
// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
// ASSERT_XY(), which clashes with some users' own code.

#if !GTEST_DONT_DEFINE_ASSERT_EQ
1986
# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
1987
1988
1989
#endif

#if !GTEST_DONT_DEFINE_ASSERT_NE
1990
# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
1991
1992
1993
#endif

#if !GTEST_DONT_DEFINE_ASSERT_LE
1994
# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
1995
1996
1997
#endif

#if !GTEST_DONT_DEFINE_ASSERT_LT
1998
# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
1999
2000
2001
#endif

#if !GTEST_DONT_DEFINE_ASSERT_GE
2002
# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
2003
2004
2005
#endif

#if !GTEST_DONT_DEFINE_ASSERT_GT
2006
# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
2007
2008
#endif

2009
// C-string Comparisons.  All tests treat NULL and any non-NULL string
shiqian's avatar
shiqian committed
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
// as different.  Two NULLs are equal.
//
//    * {ASSERT|EXPECT}_STREQ(s1, s2):     Tests that s1 == s2
//    * {ASSERT|EXPECT}_STRNE(s1, s2):     Tests that s1 != s2
//    * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
//    * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
//
// For wide or narrow string objects, you can use the
// {ASSERT|EXPECT}_??() macros.
//
// Don't depend on the order in which the arguments are evaluated,
// which is undefined.
//
// These macros evaluate their arguments exactly once.

2025
2026
#define EXPECT_STREQ(s1, s2) \
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
shiqian's avatar
shiqian committed
2027
2028
#define EXPECT_STRNE(s1, s2) \
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2029
2030
#define EXPECT_STRCASEEQ(s1, s2) \
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
shiqian's avatar
shiqian committed
2031
2032
2033
#define EXPECT_STRCASENE(s1, s2)\
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)

2034
2035
#define ASSERT_STREQ(s1, s2) \
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
shiqian's avatar
shiqian committed
2036
2037
#define ASSERT_STRNE(s1, s2) \
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2038
2039
#define ASSERT_STRCASEEQ(s1, s2) \
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
shiqian's avatar
shiqian committed
2040
2041
2042
2043
2044
#define ASSERT_STRCASENE(s1, s2)\
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)

// Macros for comparing floating-point numbers.
//
2045
//    * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
shiqian's avatar
shiqian committed
2046
//         Tests that two float values are almost equal.
2047
//    * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
shiqian's avatar
shiqian committed
2048
2049
2050
2051
2052
2053
2054
2055
2056
//         Tests that two double values are almost equal.
//    * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
//         Tests that v1 and v2 are within the given distance to each other.
//
// Google Test uses ULP-based comparison to automatically pick a default
// error bound that is appropriate for the operands.  See the
// FloatingPoint template class in gtest-internal.h if you are
// interested in the implementation details.

2057
#define EXPECT_FLOAT_EQ(val1, val2)\
shiqian's avatar
shiqian committed
2058
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2059
                      val1, val2)
shiqian's avatar
shiqian committed
2060

2061
#define EXPECT_DOUBLE_EQ(val1, val2)\
shiqian's avatar
shiqian committed
2062
  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2063
                      val1, val2)
shiqian's avatar
shiqian committed
2064

2065
#define ASSERT_FLOAT_EQ(val1, val2)\
shiqian's avatar
shiqian committed
2066
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2067
                      val1, val2)
shiqian's avatar
shiqian committed
2068

2069
#define ASSERT_DOUBLE_EQ(val1, val2)\
shiqian's avatar
shiqian committed
2070
  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2071
                      val1, val2)
shiqian's avatar
shiqian committed
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087

#define EXPECT_NEAR(val1, val2, abs_error)\
  EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
                      val1, val2, abs_error)

#define ASSERT_NEAR(val1, val2, abs_error)\
  ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
                      val1, val2, abs_error)

// These predicate format functions work on floating-point values, and
// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
//
//   EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);

// Asserts that val1 is less than, or almost equal to, val2.  Fails
// otherwise.  In particular, it fails if either val1 or val2 is NaN.
2088
2089
2090
2091
GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
                                   float val1, float val2);
GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
                                    double val1, double val2);
shiqian's avatar
shiqian committed
2092
2093


zhanyong.wan's avatar
zhanyong.wan committed
2094
#if GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
2095
2096
2097
2098
2099
2100

// Macros that test for HRESULT failure and success, these are only useful
// on Windows, and rely on Windows SDK macros and APIs to compile.
//
//    * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
//
2101
2102
2103
2104
// When expr unexpectedly fails or succeeds, Google Test prints the
// expected result and the actual result with both a human-readable
// string representation of the error, if available, as well as the
// hex result code.
2105
# define EXPECT_HRESULT_SUCCEEDED(expr) \
shiqian's avatar
shiqian committed
2106
2107
    EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))

2108
# define ASSERT_HRESULT_SUCCEEDED(expr) \
shiqian's avatar
shiqian committed
2109
2110
    ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))

2111
# define EXPECT_HRESULT_FAILED(expr) \
shiqian's avatar
shiqian committed
2112
2113
    EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))

2114
# define ASSERT_HRESULT_FAILED(expr) \
shiqian's avatar
shiqian committed
2115
2116
2117
2118
    ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))

#endif  // GTEST_OS_WINDOWS

shiqian's avatar
shiqian committed
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
// Macros that execute statement and check that it doesn't generate new fatal
// failures in the current thread.
//
//   * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
//
// Examples:
//
//   EXPECT_NO_FATAL_FAILURE(Process());
//   ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
//
#define ASSERT_NO_FATAL_FAILURE(statement) \
    GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
#define EXPECT_NO_FATAL_FAILURE(statement) \
    GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
shiqian's avatar
shiqian committed
2133

2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
// Causes a trace (including the given source file path and line number,
// and the given message) to be included in every test failure message generated
// by code in the scope of the lifetime of an instance of this class. The effect
// is undone with the destruction of the instance.
//
// The message argument can be anything streamable to std::ostream.
//
// Example:
//   testing::ScopedTrace trace("file.cc", 123, "message");
//
class GTEST_API_ ScopedTrace {
 public:
  // The c'tor pushes the given source file location and message onto
  // a trace stack maintained by Google Test.

  // Template version. Uses Message() to convert the values into strings.
  // Slow, but flexible.
  template <typename T>
  ScopedTrace(const char* file, int line, const T& message) {
    PushTrace(file, line, (Message() << message).GetString());
  }

  // Optimize for some known types.
  ScopedTrace(const char* file, int line, const char* message) {
    PushTrace(file, line, message ? message : "(null)");
  }

#if GTEST_HAS_GLOBAL_STRING
  ScopedTrace(const char* file, int line, const ::string& message) {
    PushTrace(file, line, message);
  }
#endif

  ScopedTrace(const char* file, int line, const std::string& message) {
    PushTrace(file, line, message);
  }

  // The d'tor pops the info pushed by the c'tor.
  //
  // Note that the d'tor is not virtual in order to be efficient.
  // Don't inherit from ScopedTrace!
  ~ScopedTrace();

 private:
  void PushTrace(const char* file, int line, std::string message);

  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
} GTEST_ATTRIBUTE_UNUSED_;  // A ScopedTrace object does its job in its
                            // c'tor and d'tor.  Therefore it doesn't
                            // need to be used otherwise.

shiqian's avatar
shiqian committed
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
// Causes a trace (including the source file path, the current line
// number, and the given message) to be included in every test failure
// message generated by code in the current scope.  The effect is
// undone when the control leaves the current scope.
//
// The message argument can be anything streamable to std::ostream.
//
// In the implementation, we include the current line number as part
// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
// to appear in the same block - as long as they are on different
// lines.
Gennadiy Civil's avatar
Gennadiy Civil committed
2196
2197
2198
2199
//
// Assuming that each thread maintains its own stack of traces.
// Therefore, a SCOPED_TRACE() would (correctly) only affect the
// assertions in its own thread.
shiqian's avatar
shiqian committed
2200
#define SCOPED_TRACE(message) \
2201
  ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
Gennadiy Civil's avatar
Gennadiy Civil committed
2202
2203
    __FILE__, __LINE__, (message))

shiqian's avatar
shiqian committed
2204

2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
// Compile-time assertion for type equality.
// StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are
// the same type.  The value it returns is not interesting.
//
// Instead of making StaticAssertTypeEq a class template, we make it a
// function template that invokes a helper class template.  This
// prevents a user from misusing StaticAssertTypeEq<T1, T2> by
// defining objects of that type.
//
// CAVEAT:
//
// When used inside a method of a class template,
// StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
// instantiated.  For example, given:
//
//   template <typename T> class Foo {
//    public:
//     void Bar() { testing::StaticAssertTypeEq<int, T>(); }
//   };
//
// the code:
//
//   void Test1() { Foo<bool> foo; }
//
// will NOT generate a compiler error, as Foo<bool>::Bar() is never
// actually instantiated.  Instead, you need:
//
//   void Test2() { Foo<bool> foo; foo.Bar(); }
//
// to cause a compiler error.
template <typename T1, typename T2>
bool StaticAssertTypeEq() {
2237
  (void)internal::StaticAssertTypeEqHelper<T1, T2>();
2238
2239
  return true;
}
shiqian's avatar
shiqian committed
2240
2241
2242
2243
2244
2245
2246
2247
2248

// Defines a test.
//
// The first parameter is the name of the test case, and the second
// parameter is the name of the test within the test case.
//
// The convention is to end the test case name with "Test".  For
// example, a test case for the Foo class can be named FooTest.
//
2249
2250
// Test code should appear between braces after an invocation of
// this macro.  Example:
shiqian's avatar
shiqian committed
2251
2252
2253
2254
2255
2256
//
//   TEST(FooTest, InitializesCorrectly) {
//     Foo foo;
//     EXPECT_TRUE(foo.StatusIsOK());
//   }

2257
2258
2259
2260
2261
2262
2263
2264
2265
// Note that we call GetTestTypeId() instead of GetTypeId<
// ::testing::Test>() here 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 Google Test
// framework.
2266
#define GTEST_TEST(test_case_name, test_name)\
2267
  GTEST_TEST_(test_case_name, test_name, \
2268
              ::testing::Test, ::testing::internal::GetTestTypeId())
shiqian's avatar
shiqian committed
2269

2270
2271
2272
// Define this macro to 1 to omit the definition of TEST(), which
// is a generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_TEST
2273
# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name)
2274
#endif
shiqian's avatar
shiqian committed
2275
2276
2277
2278
2279
2280
2281
2282

// Defines a test that uses a test fixture.
//
// The first parameter is the name of the test fixture class, which
// also doubles as the test case name.  The second parameter is the
// name of the test within the test case.
//
// A test fixture class must be declared earlier.  The user should put
2283
// the test code between braces after using this macro.  Example:
shiqian's avatar
shiqian committed
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
//
//   class FooTest : public testing::Test {
//    protected:
//     virtual void SetUp() { b_.AddElement(3); }
//
//     Foo a_;
//     Foo b_;
//   };
//
//   TEST_F(FooTest, InitializesCorrectly) {
//     EXPECT_TRUE(a_.StatusIsOK());
//   }
//
//   TEST_F(FooTest, ReturnsElementCountCorrectly) {
Gennadiy Civil's avatar
Gennadiy Civil committed
2298
2299
//     EXPECT_EQ(a_.size(), 0);
//     EXPECT_EQ(b_.size(), 1);
shiqian's avatar
shiqian committed
2300
2301
2302
//   }

#define TEST_F(test_fixture, test_name)\
2303
  GTEST_TEST_(test_fixture, test_name, test_fixture, \
2304
              ::testing::internal::GetTypeId<test_fixture>())
shiqian's avatar
shiqian committed
2305

2306
2307
2308
2309
// Returns a path to temporary directory.
// Tries to determine an appropriate directory for the platform.
GTEST_API_ std::string TempDir();

Gennadiy Civil's avatar
 
Gennadiy Civil committed
2310
#ifdef _MSC_VER
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2311
#  pragma warning(pop)
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2312
2313
#endif

2314
2315
2316
}  // namespace testing

// Use this function in main() to run all tests.  It returns 0 if all
shiqian's avatar
shiqian committed
2317
2318
2319
2320
// tests are successful, or 1 otherwise.
//
// RUN_ALL_TESTS() should be invoked after the command line has been
// parsed by InitGoogleTest().
2321
2322
2323
2324
//
// This function was formerly a macro; thus, it is in the global
// namespace and has an all-caps name.
int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
shiqian's avatar
shiqian committed
2325

2326
2327
2328
inline int RUN_ALL_TESTS() {
  return ::testing::UnitTest::GetInstance()->Run();
}
shiqian's avatar
shiqian committed
2329
2330

#endif  // GTEST_INCLUDE_GTEST_GTEST_H_