gtest-internal-inl.h revision 13481
112SN/A// Copyright 2005, Google Inc. 21762SN/A// All rights reserved. 312SN/A// 412SN/A// Redistribution and use in source and binary forms, with or without 512SN/A// modification, are permitted provided that the following conditions are 612SN/A// met: 712SN/A// 812SN/A// * Redistributions of source code must retain the above copyright 912SN/A// notice, this list of conditions and the following disclaimer. 1012SN/A// * Redistributions in binary form must reproduce the above 1112SN/A// copyright notice, this list of conditions and the following disclaimer 1212SN/A// in the documentation and/or other materials provided with the 1312SN/A// distribution. 1412SN/A// * Neither the name of Google Inc. nor the names of its 1512SN/A// contributors may be used to endorse or promote products derived from 1612SN/A// this software without specific prior written permission. 1712SN/A// 1812SN/A// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 1912SN/A// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 2012SN/A// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 2112SN/A// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 2212SN/A// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 2312SN/A// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 2412SN/A// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 2512SN/A// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 2612SN/A// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 272665Ssaidi@eecs.umich.edu// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 282665Ssaidi@eecs.umich.edu// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 292665Ssaidi@eecs.umich.edu 3012SN/A// Utility functions and classes used by the Google C++ testing framework. 3112SN/A// 325616Snate@binkert.org// Author: wan@google.com (Zhanyong Wan) 3312SN/A// 3412SN/A// This file contains purely Google Test's internal implementation. Please 3556SN/A// DO NOT #INCLUDE IT IN A USER PROGRAM. 364484Sbinkertn@umich.edu 378229Snate@binkert.org#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ 382439SN/A#define GTEST_SRC_GTEST_INTERNAL_INL_H_ 397676Snate@binkert.org 408232Snate@binkert.org// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is 412423SN/A// part of Google Test's implementation; otherwise it's undefined. 428229Snate@binkert.org#if !GTEST_IMPLEMENTATION_ 432423SN/A// If this file is included from the user's code, just say no. 4412SN/A# error "gtest-internal-inl.h is part of Google Test's internal implementation." 4512SN/A# error "It must not be included except by Google Test itself." 4612SN/A#endif // GTEST_IMPLEMENTATION_ 4712SN/A 4812SN/A#ifndef _WIN32_WCE 49443SN/A# include <errno.h> 50443SN/A#endif // !_WIN32_WCE 512207SN/A#include <stddef.h> 522207SN/A#include <stdlib.h> // For strtoll/_strtoul64/malloc/free. 53443SN/A#include <string.h> // For memmove. 54468SN/A 551708SN/A#include <algorithm> 561708SN/A#include <string> 57443SN/A#include <vector> 58468SN/A 59443SN/A#include "gtest/internal/gtest-port.h" 60468SN/A 61443SN/A#if GTEST_CAN_STREAM_RESULTS_ 62443SN/A# include <arpa/inet.h> // NOLINT 63468SN/A# include <netdb.h> // NOLINT 64468SN/A#endif 65443SN/A 66443SN/A#if GTEST_OS_WINDOWS 67443SN/A# include <windows.h> // NOLINT 682476SN/A#endif // GTEST_OS_WINDOWS 692207SN/A 702207SN/A#include "gtest/gtest.h" // NOLINT 712207SN/A#include "gtest/gtest-spi.h" 722207SN/A 732207SN/Anamespace testing { 744111Sgblack@eecs.umich.edu 754111Sgblack@eecs.umich.edu// Declares the flags. 762620SN/A// 774111Sgblack@eecs.umich.edu// We don't want the users to modify this flag in the code, but want 784111Sgblack@eecs.umich.edu// Google Test's own unit tests to be able to access it. Therefore we 794111Sgblack@eecs.umich.edu// declare it here as opposed to in gtest.h. 804111Sgblack@eecs.umich.eduGTEST_DECLARE_bool_(death_test_use_fork); 814111Sgblack@eecs.umich.edu 822207SN/Anamespace internal { 832207SN/A 845383Sgblack@eecs.umich.edu// The value of GetTestTypeId() as seen from within the Google Test 855383Sgblack@eecs.umich.edu// library. This is solely for testing GetTestTypeId(). 865383Sgblack@eecs.umich.eduGTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; 875383Sgblack@eecs.umich.edu 885383Sgblack@eecs.umich.edu// Names of the flags (needed for parsing Google Test flags). 895383Sgblack@eecs.umich.educonst char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; 905383Sgblack@eecs.umich.educonst char kBreakOnFailureFlag[] = "break_on_failure"; 914166Sgblack@eecs.umich.educonst char kCatchExceptionsFlag[] = "catch_exceptions"; 924166Sgblack@eecs.umich.educonst char kColorFlag[] = "color"; 935874Sgblack@eecs.umich.educonst char kFilterFlag[] = "filter"; 945874Sgblack@eecs.umich.educonst char kListTestsFlag[] = "list_tests"; 955874Sgblack@eecs.umich.educonst char kOutputFlag[] = "output"; 965874Sgblack@eecs.umich.educonst char kPrintTimeFlag[] = "print_time"; 972207SN/Aconst char kRandomSeedFlag[] = "random_seed"; 982207SN/Aconst char kRepeatFlag[] = "repeat"; 995335Shines@cs.fsu.educonst char kShuffleFlag[] = "shuffle"; 1007095Sgblack@eecs.umich.educonst char kStackTraceDepthFlag[] = "stack_trace_depth"; 1017095Sgblack@eecs.umich.educonst char kStreamResultToFlag[] = "stream_result_to"; 1027095Sgblack@eecs.umich.educonst char kThrowOnFailureFlag[] = "throw_on_failure"; 1037095Sgblack@eecs.umich.educonst char kFlagfileFlag[] = "flagfile"; 1047095Sgblack@eecs.umich.edu 1056691Stjones1@inf.ed.ac.uk// A valid random seed must be in [1, kMaxRandomSeed]. 1066691Stjones1@inf.ed.ac.ukconst int kMaxRandomSeed = 99999; 1076691Stjones1@inf.ed.ac.uk 1086691Stjones1@inf.ed.ac.uk// g_help_flag is true iff the --help flag or an equivalent form is 1096691Stjones1@inf.ed.ac.uk// specified on the command line. 1106691Stjones1@inf.ed.ac.ukGTEST_API_ extern bool g_help_flag; 1116691Stjones1@inf.ed.ac.uk 1126691Stjones1@inf.ed.ac.uk// Returns the current time in milliseconds. 1136691Stjones1@inf.ed.ac.ukGTEST_API_ TimeInMillis GetTimeInMillis(); 1146691Stjones1@inf.ed.ac.uk 1156691Stjones1@inf.ed.ac.uk// Returns true iff Google Test should use colors in the output. 1166691Stjones1@inf.ed.ac.ukGTEST_API_ bool ShouldUseColor(bool stdout_is_tty); 1176691Stjones1@inf.ed.ac.uk 1182207SN/A// Formats the given time in milliseconds as seconds. 1192600SN/AGTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); 1202207SN/A 1212207SN/A// Converts the given time in milliseconds to a date string in the ISO 8601 1222207SN/A// format, without the timezone information. N.B.: due to the use the 1232207SN/A// non-reentrant localtime() function, this function is not thread safe. Do 1242207SN/A// not use it in any code that can be called from multiple threads. 1252207SN/AGTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); 1262238SN/A 1272207SN/A// Parses a string for an Int32 flag, in the form of "--flag=value". 1282207SN/A// 1292207SN/A// On success, stores the value of the flag in *value, and returns 1302207SN/A// true. On failure, returns false without changing *value. 1312207SN/AGTEST_API_ bool ParseInt32Flag( 1322238SN/A const char* str, const char* flag, Int32* value); 1332207SN/A 1342207SN/A// Returns a random seed in range [1, kMaxRandomSeed] based on the 1352238SN/A// given --gtest_random_seed flag value. 1366392Ssaidi@eecs.umich.eduinline int GetRandomSeedFromFlag(Int32 random_seed_flag) { 1376392Ssaidi@eecs.umich.edu const unsigned int raw_seed = (random_seed_flag == 0) ? 1386392Ssaidi@eecs.umich.edu static_cast<unsigned int>(GetTimeInMillis()) : 1392207SN/A static_cast<unsigned int>(random_seed_flag); 1402207SN/A 1412207SN/A // Normalizes the actual seed to range [1, kMaxRandomSeed] such that 1422207SN/A // it's easy to type. 1432238SN/A const int normalized_seed = 1442238SN/A static_cast<int>((raw_seed - 1U) % 1452600SN/A static_cast<unsigned int>(kMaxRandomSeed)) + 1; 1462238SN/A return normalized_seed; 1472238SN/A} 1482238SN/A 1492238SN/A// Returns the first valid random seed after 'seed'. The behavior is 1502238SN/A// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is 1512238SN/A// considered to be 1. 1522238SN/Ainline int GetNextRandomSeed(int seed) { 1532238SN/A GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) 1542238SN/A << "Invalid random seed " << seed << " - must be in [1, " 1552238SN/A << kMaxRandomSeed << "]."; 1562600SN/A const int next_seed = seed + 1; 1572238SN/A return (next_seed > kMaxRandomSeed) ? 1 : next_seed; 1582238SN/A} 1592238SN/A 1602238SN/A// This class saves the values of all Google Test flags in its c'tor, and 1612238SN/A// restores them in its d'tor. 1622238SN/Aclass GTestFlagSaver { 1632238SN/A public: 1642238SN/A // The c'tor. 1652238SN/A GTestFlagSaver() { 1662238SN/A also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); 1672238SN/A break_on_failure_ = GTEST_FLAG(break_on_failure); 1682238SN/A catch_exceptions_ = GTEST_FLAG(catch_exceptions); 1692238SN/A color_ = GTEST_FLAG(color); 1702238SN/A death_test_style_ = GTEST_FLAG(death_test_style); 1712238SN/A death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); 1722238SN/A filter_ = GTEST_FLAG(filter); 1732238SN/A internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); 1742238SN/A list_tests_ = GTEST_FLAG(list_tests); 1752238SN/A output_ = GTEST_FLAG(output); 1762238SN/A print_time_ = GTEST_FLAG(print_time); 1772238SN/A random_seed_ = GTEST_FLAG(random_seed); 1782238SN/A repeat_ = GTEST_FLAG(repeat); 1792600SN/A shuffle_ = GTEST_FLAG(shuffle); 1802600SN/A stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); 1812600SN/A stream_result_to_ = GTEST_FLAG(stream_result_to); 1822600SN/A throw_on_failure_ = GTEST_FLAG(throw_on_failure); 1832600SN/A } 1842238SN/A 1852238SN/A // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. 1862238SN/A ~GTestFlagSaver() { 1872472SN/A GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; 1882976Sgblack@eecs.umich.edu GTEST_FLAG(break_on_failure) = break_on_failure_; 1892976Sgblack@eecs.umich.edu GTEST_FLAG(catch_exceptions) = catch_exceptions_; 1902976Sgblack@eecs.umich.edu GTEST_FLAG(color) = color_; 1912976Sgblack@eecs.umich.edu GTEST_FLAG(death_test_style) = death_test_style_; 1922976Sgblack@eecs.umich.edu GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; 1932976Sgblack@eecs.umich.edu GTEST_FLAG(filter) = filter_; 1942976Sgblack@eecs.umich.edu GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; 1952976Sgblack@eecs.umich.edu GTEST_FLAG(list_tests) = list_tests_; 1962976Sgblack@eecs.umich.edu GTEST_FLAG(output) = output_; 1972976Sgblack@eecs.umich.edu GTEST_FLAG(print_time) = print_time_; 1982976Sgblack@eecs.umich.edu GTEST_FLAG(random_seed) = random_seed_; 1992976Sgblack@eecs.umich.edu GTEST_FLAG(repeat) = repeat_; 2002976Sgblack@eecs.umich.edu GTEST_FLAG(shuffle) = shuffle_; 2012976Sgblack@eecs.umich.edu GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; 2022976Sgblack@eecs.umich.edu GTEST_FLAG(stream_result_to) = stream_result_to_; 2032976Sgblack@eecs.umich.edu GTEST_FLAG(throw_on_failure) = throw_on_failure_; 2042976Sgblack@eecs.umich.edu } 2052976Sgblack@eecs.umich.edu 2062976Sgblack@eecs.umich.edu private: 2072976Sgblack@eecs.umich.edu // Fields for saving the original values of flags. 2082976Sgblack@eecs.umich.edu bool also_run_disabled_tests_; 2095143Sgblack@eecs.umich.edu bool break_on_failure_; 2102976Sgblack@eecs.umich.edu bool catch_exceptions_; 2112976Sgblack@eecs.umich.edu std::string color_; 2122976Sgblack@eecs.umich.edu std::string death_test_style_; 2132976Sgblack@eecs.umich.edu bool death_test_use_fork_; 2142976Sgblack@eecs.umich.edu std::string filter_; 2152976Sgblack@eecs.umich.edu std::string internal_run_death_test_; 2162976Sgblack@eecs.umich.edu bool list_tests_; 2172976Sgblack@eecs.umich.edu std::string output_; 2182238SN/A bool print_time_; 2192976Sgblack@eecs.umich.edu internal::Int32 random_seed_; 22012SN/A internal::Int32 repeat_; 22112SN/A bool shuffle_; 22212SN/A internal::Int32 stack_trace_depth_; 22312SN/A std::string stream_result_to_; 22412SN/A bool throw_on_failure_; 225360SN/A} GTEST_ATTRIBUTE_UNUSED_; 226360SN/A 227360SN/A// Converts a Unicode code point to a narrow string in UTF-8 encoding. 228443SN/A// code_point parameter is of type UInt32 because wchar_t may not be 22912SN/A// wide enough to contain a code point. 230443SN/A// If the code_point is not a valid Unicode code point 231443SN/A// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted 23212SN/A// to "(Invalid Unicode 0xXXXXXXXX)". 233468SN/AGTEST_API_ std::string CodePointToUtf8(UInt32 code_point); 2341708SN/A 2351708SN/A// Converts a wide string to a narrow string in UTF-8 encoding. 23612SN/A// The wide string is assumed to have the following encoding: 237468SN/A// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) 238443SN/A// UTF-32 if sizeof(wchar_t) == 4 (on Linux) 239468SN/A// Parameter str points to a null-terminated wide string. 240443SN/A// Parameter num_chars may additionally limit the number 24112SN/A// of wchar_t characters processed. -1 is used when the entire string 242468SN/A// should be processed. 243468SN/A// If the string contains code points that are not valid Unicode code points 244443SN/A// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output 24512SN/A// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding 24612SN/A// and contains invalid UTF-16 surrogate pairs, values in those pairs 247468SN/A// will be encoded as individual Unicode characters from Basic Normal Plane. 24812SN/AGTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); 249468SN/A 250468SN/A// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file 2519186SAli.Saidi@ARM.com// if the variable is present. If a file already exists at this location, this 252468SN/A// function will write over it. If the variable is present, but the file cannot 2535090Sgblack@eecs.umich.edu// be created, prints an error and exits. 2545090Sgblack@eecs.umich.eduvoid WriteToShardStatusFileIfNeeded(); 2555090Sgblack@eecs.umich.edu 2565090Sgblack@eecs.umich.edu// Checks whether sharding is enabled by examining the relevant 2575090Sgblack@eecs.umich.edu// environment variable values. If the variables are present, 2585090Sgblack@eecs.umich.edu// but inconsistent (e.g., shard_index >= total_shards), prints 2595090Sgblack@eecs.umich.edu// an error and exits. If in_subprocess_for_death_test, sharding is 2605090Sgblack@eecs.umich.edu// disabled because it must only be applied to the original test 2615090Sgblack@eecs.umich.edu// process. Otherwise, we could filter out death tests we intended to execute. 2625090Sgblack@eecs.umich.eduGTEST_API_ bool ShouldShard(const char* total_shards_str, 2635090Sgblack@eecs.umich.edu const char* shard_index_str, 2645090Sgblack@eecs.umich.edu bool in_subprocess_for_death_test); 2655090Sgblack@eecs.umich.edu 2665090Sgblack@eecs.umich.edu// Parses the environment variable var as an Int32. If it is unset, 2675090Sgblack@eecs.umich.edu// returns default_val. If it is not an Int32, prints an error and 2685090Sgblack@eecs.umich.edu// and aborts. 2695090Sgblack@eecs.umich.eduGTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); 2708350Sgblack@eecs.umich.edu 2718350Sgblack@eecs.umich.edu// Given the total number of shards, the shard index, and the test id, 2728350Sgblack@eecs.umich.edu// returns true iff the test should be run on this shard. The test id is 2738350Sgblack@eecs.umich.edu// some arbitrary but unique non-negative integer assigned to each test 2748350Sgblack@eecs.umich.edu// method. Assumes that 0 <= shard_index < total_shards. 2758350Sgblack@eecs.umich.eduGTEST_API_ bool ShouldRunTestOnShard( 2768350Sgblack@eecs.umich.edu int total_shards, int shard_index, int test_id); 2778350Sgblack@eecs.umich.edu 2788350Sgblack@eecs.umich.edu// STL container utilities. 2798350Sgblack@eecs.umich.edu 2808350Sgblack@eecs.umich.edu// Returns the number of elements in the given container that satisfy 2818350Sgblack@eecs.umich.edu// the given predicate. 2828350Sgblack@eecs.umich.edutemplate <class Container, typename Predicate> 2838350Sgblack@eecs.umich.eduinline int CountIf(const Container& c, Predicate predicate) { 2845090Sgblack@eecs.umich.edu // Implemented as an explicit loop since std::count_if() in libCstd on 2855090Sgblack@eecs.umich.edu // Solaris has a non-standard signature. 2865090Sgblack@eecs.umich.edu int count = 0; 2875090Sgblack@eecs.umich.edu for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { 2885090Sgblack@eecs.umich.edu if (predicate(*it)) 2895090Sgblack@eecs.umich.edu ++count; 2905090Sgblack@eecs.umich.edu } 2915090Sgblack@eecs.umich.edu return count; 292468SN/A} 293468SN/A 294468SN/A// Applies a function/functor to each element in the container. 2955090Sgblack@eecs.umich.edutemplate <class Container, typename Functor> 296468SN/Avoid ForEach(const Container& c, Functor functor) { 297468SN/A std::for_each(c.begin(), c.end(), functor); 298468SN/A} 299468SN/A 300468SN/A// Returns the i-th element of the vector, or default_value if i is not 301468SN/A// in range [0, v.size()). 3025090Sgblack@eecs.umich.edutemplate <typename E> 3035143Sgblack@eecs.umich.eduinline E GetElementOr(const std::vector<E>& v, int i, E default_value) { 3045143Sgblack@eecs.umich.edu return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i]; 3055090Sgblack@eecs.umich.edu} 3065143Sgblack@eecs.umich.edu 3075090Sgblack@eecs.umich.edu// Performs an in-place shuffle of a range of the vector's elements. 3085090Sgblack@eecs.umich.edu// 'begin' and 'end' are element indices as an STL-style range; 3095090Sgblack@eecs.umich.edu// i.e. [begin, end) are shuffled, where 'end' == size() means to 3105090Sgblack@eecs.umich.edu// shuffle to the end of the vector. 3115090Sgblack@eecs.umich.edutemplate <typename E> 3125152Sgblack@eecs.umich.eduvoid ShuffleRange(internal::Random* random, int begin, int end, 3135152Sgblack@eecs.umich.edu std::vector<E>* v) { 3145143Sgblack@eecs.umich.edu const int size = static_cast<int>(v->size()); 315468SN/A GTEST_CHECK_(0 <= begin && begin <= size) 3162420SN/A << "Invalid shuffle range start " << begin << ": must be in range [0, " 3175152Sgblack@eecs.umich.edu << size << "]."; 3185152Sgblack@eecs.umich.edu GTEST_CHECK_(begin <= end && end <= size) 3195143Sgblack@eecs.umich.edu << "Invalid shuffle range finish " << end << ": must be in range [" 320468SN/A << begin << ", " << size << "]."; 3212420SN/A 3222476SN/A // Fisher-Yates shuffle, from 3235759Shsul@eecs.umich.edu // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle 3245759Shsul@eecs.umich.edu for (int range_width = end - begin; range_width >= 2; range_width--) { 3255090Sgblack@eecs.umich.edu const int last_in_range = begin + range_width - 1; 3265143Sgblack@eecs.umich.edu const int selected = begin + random->Generate(range_width); 3275090Sgblack@eecs.umich.edu std::swap((*v)[selected], (*v)[last_in_range]); 3285090Sgblack@eecs.umich.edu } 3295090Sgblack@eecs.umich.edu} 330468SN/A 331468SN/A// Performs an in-place shuffle of the vector's elements. 332468SN/Atemplate <typename E> 333468SN/Ainline void Shuffle(internal::Random* random, std::vector<E>* v) { 334468SN/A ShuffleRange(random, 0, static_cast<int>(v->size()), v); 335468SN/A} 336468SN/A 337468SN/A// A function for deleting an object. Handy for being used as a 338468SN/A// functor. 339468SN/Atemplate <typename T> 340443SN/Astatic void Delete(T* x) { 341443SN/A delete x; 342468SN/A} 34312SN/A 34412SN/A// A predicate that checks the key of a TestProperty against a known key. 34512SN/A// 34612SN/A// TestPropertyKeyIs is copyable. 3477581SAli.Saidi@arm.comclass TestPropertyKeyIs { 34812SN/A public: 349443SN/A // Constructor. 350766SN/A // 351443SN/A // TestPropertyKeyIs has NO default constructor. 352443SN/A explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} 353443SN/A 354443SN/A // Returns true iff the test name of test property matches on key_. 355443SN/A bool operator()(const TestProperty& test_property) const { 356443SN/A return test_property.key() == key_; 357443SN/A } 358443SN/A 359443SN/A private: 360443SN/A std::string key_; 361468SN/A}; 3621708SN/A 3631708SN/A// Class UnitTestOptions. 364443SN/A// 365468SN/A// This class contains functions for processing options the user 366443SN/A// specifies when running the tests. It has only static members. 367443SN/A// 368443SN/A// In most cases, the user can specify an option using either an 369443SN/A// environment variable or a command line flag. E.g. you can set the 370468SN/A// test filter using either GTEST_FILTER or --gtest_filter. If both 371454SN/A// the variable and the flag are present, the latter overrides the 372443SN/A// former. 373468SN/Aclass GTEST_API_ UnitTestOptions { 374468SN/A public: 375443SN/A // Functions for processing the gtest_output flag. 376443SN/A 377468SN/A // Returns the output format, or "" for normal printed output. 378443SN/A static std::string GetOutputFormat(); 379443SN/A 380443SN/A // Returns the absolute path of the requested output file, or the 381443SN/A // default (test_detail.xml in the original working directory) if 382443SN/A // none was explicitly specified. 383468SN/A static std::string GetAbsolutePathToOutputFile(); 384468SN/A 385443SN/A // Functions for processing the gtest_filter flag. 386836SN/A 3877589SAli.Saidi@arm.com // Returns true iff the wildcard pattern matches the string. The 3887589SAli.Saidi@arm.com // first ':' or '\0' character in pattern marks the end of it. 3897589SAli.Saidi@arm.com // 3907589SAli.Saidi@arm.com // This recursive algorithm isn't very efficient, but is clear and 3917589SAli.Saidi@arm.com // works well enough for matching test names, which are short. 3927589SAli.Saidi@arm.com static bool PatternMatchesString(const char *pattern, const char *str); 393443SN/A 394443SN/A // Returns true iff the user-specified filter matches the test case 395443SN/A // name and the test name. 396454SN/A static bool FilterMatchesTest(const std::string &test_case_name, 397454SN/A const std::string &test_name); 398443SN/A 399443SN/A#if GTEST_OS_WINDOWS 400443SN/A // Function for supporting the gtest_catch_exception flag. 401443SN/A 402443SN/A // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the 40312SN/A // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. 40412SN/A // This function is useful as an __except condition. 40512SN/A static int GTestShouldProcessSEH(DWORD exception_code); 4063812Ssaidi@eecs.umich.edu#endif // GTEST_OS_WINDOWS 407468SN/A 4087581SAli.Saidi@arm.com // Returns true if "name" matches the ':' separated list of glob-style 409468SN/A // filters in "filter". 410468SN/A static bool MatchesFilter(const std::string& name, const char* filter); 411468SN/A}; 4123812Ssaidi@eecs.umich.edu 41312SN/A// Returns the current application's name, removing directory path if that 4147581SAli.Saidi@arm.com// is present. Used by UnitTestOptions::GetOutputFile. 41512SN/AGTEST_API_ FilePath GetCurrentExecutableName(); 4163917Ssaidi@eecs.umich.edu 4175090Sgblack@eecs.umich.edu// The role interface for getting the OS stack trace as a string. 4188852Sandreas.hansson@arm.comclass OsStackTraceGetterInterface { 4195090Sgblack@eecs.umich.edu public: 4208706Sandreas.hansson@arm.com OsStackTraceGetterInterface() {} 4215090Sgblack@eecs.umich.edu virtual ~OsStackTraceGetterInterface() {} 4225090Sgblack@eecs.umich.edu 4235090Sgblack@eecs.umich.edu // Returns the current OS stack trace as an std::string. Parameters: 4245090Sgblack@eecs.umich.edu // 4255090Sgblack@eecs.umich.edu // max_depth - the maximum number of stack frames to be included 4268706Sandreas.hansson@arm.com // in the trace. 4275090Sgblack@eecs.umich.edu // skip_count - the number of top frames to be skipped; doesn't count 4285090Sgblack@eecs.umich.edu // against max_depth. 4295090Sgblack@eecs.umich.edu virtual string CurrentStackTrace(int max_depth, int skip_count) = 0; 4305090Sgblack@eecs.umich.edu 4315090Sgblack@eecs.umich.edu // UponLeavingGTest() should be called immediately before Google Test calls 4325090Sgblack@eecs.umich.edu // user code. It saves some information about the current stack that 4335070Ssaidi@eecs.umich.edu // CurrentStackTrace() will use to find and hide Google Test stack frames. 4345070Ssaidi@eecs.umich.edu virtual void UponLeavingGTest() = 0; 4353917Ssaidi@eecs.umich.edu 4363917Ssaidi@eecs.umich.edu // This string is inserted in place of stack frames that are part of 4373917Ssaidi@eecs.umich.edu // Google Test's implementation. 4383917Ssaidi@eecs.umich.edu static const char* const kElidedFramesMarker; 4393917Ssaidi@eecs.umich.edu 4403917Ssaidi@eecs.umich.edu private: 4413917Ssaidi@eecs.umich.edu GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); 4423917Ssaidi@eecs.umich.edu}; 4435070Ssaidi@eecs.umich.edu 4445070Ssaidi@eecs.umich.edu// A working implementation of the OsStackTraceGetterInterface interface. 4453917Ssaidi@eecs.umich.educlass OsStackTraceGetter : public OsStackTraceGetterInterface { 4463917Ssaidi@eecs.umich.edu public: 4473917Ssaidi@eecs.umich.edu OsStackTraceGetter() {} 4483917Ssaidi@eecs.umich.edu 4493917Ssaidi@eecs.umich.edu virtual string CurrentStackTrace(int max_depth, int skip_count); 4503917Ssaidi@eecs.umich.edu virtual void UponLeavingGTest(); 4513917Ssaidi@eecs.umich.edu 4523917Ssaidi@eecs.umich.edu private: 4533917Ssaidi@eecs.umich.edu GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); 4543917Ssaidi@eecs.umich.edu}; 4553917Ssaidi@eecs.umich.edu 4563917Ssaidi@eecs.umich.edu// Information about a Google Test trace point. 4573917Ssaidi@eecs.umich.edustruct TraceInfo { 4583917Ssaidi@eecs.umich.edu const char* file; 4593917Ssaidi@eecs.umich.edu int line; 4603917Ssaidi@eecs.umich.edu std::string message; 4613917Ssaidi@eecs.umich.edu}; 4623917Ssaidi@eecs.umich.edu 4633917Ssaidi@eecs.umich.edu// This is the default global test part result reporter used in UnitTestImpl. 4645070Ssaidi@eecs.umich.edu// This class should only be used by UnitTestImpl. 4653917Ssaidi@eecs.umich.educlass DefaultGlobalTestPartResultReporter 4663917Ssaidi@eecs.umich.edu : public TestPartResultReporterInterface { 4673917Ssaidi@eecs.umich.edu public: 4683917Ssaidi@eecs.umich.edu explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); 4695070Ssaidi@eecs.umich.edu // Implements the TestPartResultReporterInterface. Reports the test part 4705070Ssaidi@eecs.umich.edu // result in the current test. 4715070Ssaidi@eecs.umich.edu virtual void ReportTestPartResult(const TestPartResult& result); 4725070Ssaidi@eecs.umich.edu 4735070Ssaidi@eecs.umich.edu private: 4745070Ssaidi@eecs.umich.edu UnitTestImpl* const unit_test_; 4755070Ssaidi@eecs.umich.edu 4763917Ssaidi@eecs.umich.edu GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); 4775070Ssaidi@eecs.umich.edu}; 478 479// This is the default per thread test part result reporter used in 480// UnitTestImpl. This class should only be used by UnitTestImpl. 481class DefaultPerThreadTestPartResultReporter 482 : public TestPartResultReporterInterface { 483 public: 484 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); 485 // Implements the TestPartResultReporterInterface. The implementation just 486 // delegates to the current global test part result reporter of *unit_test_. 487 virtual void ReportTestPartResult(const TestPartResult& result); 488 489 private: 490 UnitTestImpl* const unit_test_; 491 492 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); 493}; 494 495// The private implementation of the UnitTest class. We don't protect 496// the methods under a mutex, as this class is not accessible by a 497// user and the UnitTest class that delegates work to this class does 498// proper locking. 499class GTEST_API_ UnitTestImpl { 500 public: 501 explicit UnitTestImpl(UnitTest* parent); 502 virtual ~UnitTestImpl(); 503 504 // There are two different ways to register your own TestPartResultReporter. 505 // You can register your own repoter to listen either only for test results 506 // from the current thread or for results from all threads. 507 // By default, each per-thread test result repoter just passes a new 508 // TestPartResult to the global test result reporter, which registers the 509 // test part result for the currently running test. 510 511 // Returns the global test part result reporter. 512 TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); 513 514 // Sets the global test part result reporter. 515 void SetGlobalTestPartResultReporter( 516 TestPartResultReporterInterface* reporter); 517 518 // Returns the test part result reporter for the current thread. 519 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); 520 521 // Sets the test part result reporter for the current thread. 522 void SetTestPartResultReporterForCurrentThread( 523 TestPartResultReporterInterface* reporter); 524 525 // Gets the number of successful test cases. 526 int successful_test_case_count() const; 527 528 // Gets the number of failed test cases. 529 int failed_test_case_count() const; 530 531 // Gets the number of all test cases. 532 int total_test_case_count() const; 533 534 // Gets the number of all test cases that contain at least one test 535 // that should run. 536 int test_case_to_run_count() const; 537 538 // Gets the number of successful tests. 539 int successful_test_count() const; 540 541 // Gets the number of failed tests. 542 int failed_test_count() const; 543 544 // Gets the number of disabled tests that will be reported in the XML report. 545 int reportable_disabled_test_count() const; 546 547 // Gets the number of disabled tests. 548 int disabled_test_count() const; 549 550 // Gets the number of tests to be printed in the XML report. 551 int reportable_test_count() const; 552 553 // Gets the number of all tests. 554 int total_test_count() const; 555 556 // Gets the number of tests that should run. 557 int test_to_run_count() const; 558 559 // Gets the time of the test program start, in ms from the start of the 560 // UNIX epoch. 561 TimeInMillis start_timestamp() const { return start_timestamp_; } 562 563 // Gets the elapsed time, in milliseconds. 564 TimeInMillis elapsed_time() const { return elapsed_time_; } 565 566 // Returns true iff the unit test passed (i.e. all test cases passed). 567 bool Passed() const { return !Failed(); } 568 569 // Returns true iff the unit test failed (i.e. some test case failed 570 // or something outside of all tests failed). 571 bool Failed() const { 572 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); 573 } 574 575 // Gets the i-th test case among all the test cases. i can range from 0 to 576 // total_test_case_count() - 1. If i is not in that range, returns NULL. 577 const TestCase* GetTestCase(int i) const { 578 const int index = GetElementOr(test_case_indices_, i, -1); 579 return index < 0 ? NULL : test_cases_[i]; 580 } 581 582 // Gets the i-th test case among all the test cases. i can range from 0 to 583 // total_test_case_count() - 1. If i is not in that range, returns NULL. 584 TestCase* GetMutableTestCase(int i) { 585 const int index = GetElementOr(test_case_indices_, i, -1); 586 return index < 0 ? NULL : test_cases_[index]; 587 } 588 589 // Provides access to the event listener list. 590 TestEventListeners* listeners() { return &listeners_; } 591 592 // Returns the TestResult for the test that's currently running, or 593 // the TestResult for the ad hoc test if no test is running. 594 TestResult* current_test_result(); 595 596 // Returns the TestResult for the ad hoc test. 597 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } 598 599 // Sets the OS stack trace getter. 600 // 601 // Does nothing if the input and the current OS stack trace getter 602 // are the same; otherwise, deletes the old getter and makes the 603 // input the current getter. 604 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); 605 606 // Returns the current OS stack trace getter if it is not NULL; 607 // otherwise, creates an OsStackTraceGetter, makes it the current 608 // getter, and returns it. 609 OsStackTraceGetterInterface* os_stack_trace_getter(); 610 611 // Returns the current OS stack trace as an std::string. 612 // 613 // The maximum number of stack frames to be included is specified by 614 // the gtest_stack_trace_depth flag. The skip_count parameter 615 // specifies the number of top frames to be skipped, which doesn't 616 // count against the number of frames to be included. 617 // 618 // For example, if Foo() calls Bar(), which in turn calls 619 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the 620 // trace but Bar() and CurrentOsStackTraceExceptTop() won't. 621 std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; 622 623 // Finds and returns a TestCase with the given name. If one doesn't 624 // exist, creates one and returns it. 625 // 626 // Arguments: 627 // 628 // test_case_name: name of the test case 629 // type_param: the name of the test's type parameter, or NULL if 630 // this is not a typed or a type-parameterized test. 631 // set_up_tc: pointer to the function that sets up the test case 632 // tear_down_tc: pointer to the function that tears down the test case 633 TestCase* GetTestCase(const char* test_case_name, 634 const char* type_param, 635 Test::SetUpTestCaseFunc set_up_tc, 636 Test::TearDownTestCaseFunc tear_down_tc); 637 638 // Adds a TestInfo to the unit test. 639 // 640 // Arguments: 641 // 642 // set_up_tc: pointer to the function that sets up the test case 643 // tear_down_tc: pointer to the function that tears down the test case 644 // test_info: the TestInfo object 645 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, 646 Test::TearDownTestCaseFunc tear_down_tc, 647 TestInfo* test_info) { 648 // In order to support thread-safe death tests, we need to 649 // remember the original working directory when the test program 650 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as 651 // the user may have changed the current directory before calling 652 // RUN_ALL_TESTS(). Therefore we capture the current directory in 653 // AddTestInfo(), which is called to register a TEST or TEST_F 654 // before main() is reached. 655 if (original_working_dir_.IsEmpty()) { 656 original_working_dir_.Set(FilePath::GetCurrentDir()); 657 GTEST_CHECK_(!original_working_dir_.IsEmpty()) 658 << "Failed to get the current working directory."; 659 } 660 661 GetTestCase(test_info->test_case_name(), 662 test_info->type_param(), 663 set_up_tc, 664 tear_down_tc)->AddTestInfo(test_info); 665 } 666 667#if GTEST_HAS_PARAM_TEST 668 // Returns ParameterizedTestCaseRegistry object used to keep track of 669 // value-parameterized tests and instantiate and register them. 670 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { 671 return parameterized_test_registry_; 672 } 673#endif // GTEST_HAS_PARAM_TEST 674 675 // Sets the TestCase object for the test that's currently running. 676 void set_current_test_case(TestCase* a_current_test_case) { 677 current_test_case_ = a_current_test_case; 678 } 679 680 // Sets the TestInfo object for the test that's currently running. If 681 // current_test_info is NULL, the assertion results will be stored in 682 // ad_hoc_test_result_. 683 void set_current_test_info(TestInfo* a_current_test_info) { 684 current_test_info_ = a_current_test_info; 685 } 686 687 // Registers all parameterized tests defined using TEST_P and 688 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter 689 // combination. This method can be called more then once; it has guards 690 // protecting from registering the tests more then once. If 691 // value-parameterized tests are disabled, RegisterParameterizedTests is 692 // present but does nothing. 693 void RegisterParameterizedTests(); 694 695 // Runs all tests in this UnitTest object, prints the result, and 696 // returns true if all tests are successful. If any exception is 697 // thrown during a test, this test is considered to be failed, but 698 // the rest of the tests will still be run. 699 bool RunAllTests(); 700 701 // Clears the results of all tests, except the ad hoc tests. 702 void ClearNonAdHocTestResult() { 703 ForEach(test_cases_, TestCase::ClearTestCaseResult); 704 } 705 706 // Clears the results of ad-hoc test assertions. 707 void ClearAdHocTestResult() { 708 ad_hoc_test_result_.Clear(); 709 } 710 711 // Adds a TestProperty to the current TestResult object when invoked in a 712 // context of a test or a test case, or to the global property set. If the 713 // result already contains a property with the same key, the value will be 714 // updated. 715 void RecordProperty(const TestProperty& test_property); 716 717 enum ReactionToSharding { 718 HONOR_SHARDING_PROTOCOL, 719 IGNORE_SHARDING_PROTOCOL 720 }; 721 722 // Matches the full name of each test against the user-specified 723 // filter to decide whether the test should run, then records the 724 // result in each TestCase and TestInfo object. 725 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests 726 // based on sharding variables in the environment. 727 // Returns the number of tests that should run. 728 int FilterTests(ReactionToSharding shard_tests); 729 730 // Prints the names of the tests matching the user-specified filter flag. 731 void ListTestsMatchingFilter(); 732 733 const TestCase* current_test_case() const { return current_test_case_; } 734 TestInfo* current_test_info() { return current_test_info_; } 735 const TestInfo* current_test_info() const { return current_test_info_; } 736 737 // Returns the vector of environments that need to be set-up/torn-down 738 // before/after the tests are run. 739 std::vector<Environment*>& environments() { return environments_; } 740 741 // Getters for the per-thread Google Test trace stack. 742 std::vector<TraceInfo>& gtest_trace_stack() { 743 return *(gtest_trace_stack_.pointer()); 744 } 745 const std::vector<TraceInfo>& gtest_trace_stack() const { 746 return gtest_trace_stack_.get(); 747 } 748 749#if GTEST_HAS_DEATH_TEST 750 void InitDeathTestSubprocessControlInfo() { 751 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); 752 } 753 // Returns a pointer to the parsed --gtest_internal_run_death_test 754 // flag, or NULL if that flag was not specified. 755 // This information is useful only in a death test child process. 756 // Must not be called before a call to InitGoogleTest. 757 const InternalRunDeathTestFlag* internal_run_death_test_flag() const { 758 return internal_run_death_test_flag_.get(); 759 } 760 761 // Returns a pointer to the current death test factory. 762 internal::DeathTestFactory* death_test_factory() { 763 return death_test_factory_.get(); 764 } 765 766 void SuppressTestEventsIfInSubprocess(); 767 768 friend class ReplaceDeathTestFactory; 769#endif // GTEST_HAS_DEATH_TEST 770 771 // Initializes the event listener performing XML output as specified by 772 // UnitTestOptions. Must not be called before InitGoogleTest. 773 void ConfigureXmlOutput(); 774 775#if GTEST_CAN_STREAM_RESULTS_ 776 // Initializes the event listener for streaming test results to a socket. 777 // Must not be called before InitGoogleTest. 778 void ConfigureStreamingOutput(); 779#endif 780 781 // Performs initialization dependent upon flag values obtained in 782 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to 783 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest 784 // this function is also called from RunAllTests. Since this function can be 785 // called more than once, it has to be idempotent. 786 void PostFlagParsingInit(); 787 788 // Gets the random seed used at the start of the current test iteration. 789 int random_seed() const { return random_seed_; } 790 791 // Gets the random number generator. 792 internal::Random* random() { return &random_; } 793 794 // Shuffles all test cases, and the tests within each test case, 795 // making sure that death tests are still run first. 796 void ShuffleTests(); 797 798 // Restores the test cases and tests to their order before the first shuffle. 799 void UnshuffleTests(); 800 801 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment 802 // UnitTest::Run() starts. 803 bool catch_exceptions() const { return catch_exceptions_; } 804 805 private: 806 friend class ::testing::UnitTest; 807 808 // Used by UnitTest::Run() to capture the state of 809 // GTEST_FLAG(catch_exceptions) at the moment it starts. 810 void set_catch_exceptions(bool value) { catch_exceptions_ = value; } 811 812 // The UnitTest object that owns this implementation object. 813 UnitTest* const parent_; 814 815 // The working directory when the first TEST() or TEST_F() was 816 // executed. 817 internal::FilePath original_working_dir_; 818 819 // The default test part result reporters. 820 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; 821 DefaultPerThreadTestPartResultReporter 822 default_per_thread_test_part_result_reporter_; 823 824 // Points to (but doesn't own) the global test part result reporter. 825 TestPartResultReporterInterface* global_test_part_result_repoter_; 826 827 // Protects read and write access to global_test_part_result_reporter_. 828 internal::Mutex global_test_part_result_reporter_mutex_; 829 830 // Points to (but doesn't own) the per-thread test part result reporter. 831 internal::ThreadLocal<TestPartResultReporterInterface*> 832 per_thread_test_part_result_reporter_; 833 834 // The vector of environments that need to be set-up/torn-down 835 // before/after the tests are run. 836 std::vector<Environment*> environments_; 837 838 // The vector of TestCases in their original order. It owns the 839 // elements in the vector. 840 std::vector<TestCase*> test_cases_; 841 842 // Provides a level of indirection for the test case list to allow 843 // easy shuffling and restoring the test case order. The i-th 844 // element of this vector is the index of the i-th test case in the 845 // shuffled order. 846 std::vector<int> test_case_indices_; 847 848#if GTEST_HAS_PARAM_TEST 849 // ParameterizedTestRegistry object used to register value-parameterized 850 // tests. 851 internal::ParameterizedTestCaseRegistry parameterized_test_registry_; 852 853 // Indicates whether RegisterParameterizedTests() has been called already. 854 bool parameterized_tests_registered_; 855#endif // GTEST_HAS_PARAM_TEST 856 857 // Index of the last death test case registered. Initially -1. 858 int last_death_test_case_; 859 860 // This points to the TestCase for the currently running test. It 861 // changes as Google Test goes through one test case after another. 862 // When no test is running, this is set to NULL and Google Test 863 // stores assertion results in ad_hoc_test_result_. Initially NULL. 864 TestCase* current_test_case_; 865 866 // This points to the TestInfo for the currently running test. It 867 // changes as Google Test goes through one test after another. When 868 // no test is running, this is set to NULL and Google Test stores 869 // assertion results in ad_hoc_test_result_. Initially NULL. 870 TestInfo* current_test_info_; 871 872 // Normally, a user only writes assertions inside a TEST or TEST_F, 873 // or inside a function called by a TEST or TEST_F. Since Google 874 // Test keeps track of which test is current running, it can 875 // associate such an assertion with the test it belongs to. 876 // 877 // If an assertion is encountered when no TEST or TEST_F is running, 878 // Google Test attributes the assertion result to an imaginary "ad hoc" 879 // test, and records the result in ad_hoc_test_result_. 880 TestResult ad_hoc_test_result_; 881 882 // The list of event listeners that can be used to track events inside 883 // Google Test. 884 TestEventListeners listeners_; 885 886 // The OS stack trace getter. Will be deleted when the UnitTest 887 // object is destructed. By default, an OsStackTraceGetter is used, 888 // but the user can set this field to use a custom getter if that is 889 // desired. 890 OsStackTraceGetterInterface* os_stack_trace_getter_; 891 892 // True iff PostFlagParsingInit() has been called. 893 bool post_flag_parse_init_performed_; 894 895 // The random number seed used at the beginning of the test run. 896 int random_seed_; 897 898 // Our random number generator. 899 internal::Random random_; 900 901 // The time of the test program start, in ms from the start of the 902 // UNIX epoch. 903 TimeInMillis start_timestamp_; 904 905 // How long the test took to run, in milliseconds. 906 TimeInMillis elapsed_time_; 907 908#if GTEST_HAS_DEATH_TEST 909 // The decomposed components of the gtest_internal_run_death_test flag, 910 // parsed when RUN_ALL_TESTS is called. 911 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_; 912 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_; 913#endif // GTEST_HAS_DEATH_TEST 914 915 // A per-thread stack of traces created by the SCOPED_TRACE() macro. 916 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_; 917 918 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() 919 // starts. 920 bool catch_exceptions_; 921 922 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); 923}; // class UnitTestImpl 924 925// Convenience function for accessing the global UnitTest 926// implementation object. 927inline UnitTestImpl* GetUnitTestImpl() { 928 return UnitTest::GetInstance()->impl(); 929} 930 931#if GTEST_USES_SIMPLE_RE 932 933// Internal helper functions for implementing the simple regular 934// expression matcher. 935GTEST_API_ bool IsInSet(char ch, const char* str); 936GTEST_API_ bool IsAsciiDigit(char ch); 937GTEST_API_ bool IsAsciiPunct(char ch); 938GTEST_API_ bool IsRepeat(char ch); 939GTEST_API_ bool IsAsciiWhiteSpace(char ch); 940GTEST_API_ bool IsAsciiWordChar(char ch); 941GTEST_API_ bool IsValidEscape(char ch); 942GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); 943GTEST_API_ bool ValidateRegex(const char* regex); 944GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); 945GTEST_API_ bool MatchRepetitionAndRegexAtHead( 946 bool escaped, char ch, char repeat, const char* regex, const char* str); 947GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); 948 949#endif // GTEST_USES_SIMPLE_RE 950 951// Parses the command line for Google Test flags, without initializing 952// other parts of Google Test. 953GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); 954GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); 955 956#if GTEST_HAS_DEATH_TEST 957 958// Returns the message describing the last system error, regardless of the 959// platform. 960GTEST_API_ std::string GetLastErrnoDescription(); 961 962// Attempts to parse a string into a positive integer pointed to by the 963// number parameter. Returns true if that is possible. 964// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use 965// it here. 966template <typename Integer> 967bool ParseNaturalNumber(const ::std::string& str, Integer* number) { 968 // Fail fast if the given string does not begin with a digit; 969 // this bypasses strtoXXX's "optional leading whitespace and plus 970 // or minus sign" semantics, which are undesirable here. 971 if (str.empty() || !IsDigit(str[0])) { 972 return false; 973 } 974 errno = 0; 975 976 char* end; 977 // BiggestConvertible is the largest integer type that system-provided 978 // string-to-number conversion routines can return. 979 980# if GTEST_OS_WINDOWS && !defined(__GNUC__) 981 982 // MSVC and C++ Builder define __int64 instead of the standard long long. 983 typedef unsigned __int64 BiggestConvertible; 984 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); 985 986# else 987 988 typedef unsigned long long BiggestConvertible; // NOLINT 989 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); 990 991# endif // GTEST_OS_WINDOWS && !defined(__GNUC__) 992 993 const bool parse_success = *end == '\0' && errno == 0; 994 995 // TODO(vladl@google.com): Convert this to compile time assertion when it is 996 // available. 997 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); 998 999 const Integer result = static_cast<Integer>(parsed); 1000 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) { 1001 *number = result; 1002 return true; 1003 } 1004 return false; 1005} 1006#endif // GTEST_HAS_DEATH_TEST 1007 1008// TestResult contains some private methods that should be hidden from 1009// Google Test user but are required for testing. This class allow our tests 1010// to access them. 1011// 1012// This class is supplied only for the purpose of testing Google Test's own 1013// constructs. Do not use it in user tests, either directly or indirectly. 1014class TestResultAccessor { 1015 public: 1016 static void RecordProperty(TestResult* test_result, 1017 const std::string& xml_element, 1018 const TestProperty& property) { 1019 test_result->RecordProperty(xml_element, property); 1020 } 1021 1022 static void ClearTestPartResults(TestResult* test_result) { 1023 test_result->ClearTestPartResults(); 1024 } 1025 1026 static const std::vector<testing::TestPartResult>& test_part_results( 1027 const TestResult& test_result) { 1028 return test_result.test_part_results(); 1029 } 1030}; 1031 1032#if GTEST_CAN_STREAM_RESULTS_ 1033 1034// Streams test results to the given port on the given host machine. 1035class GTEST_API_ StreamingListener : public EmptyTestEventListener { 1036 public: 1037 // Abstract base class for writing strings to a socket. 1038 class AbstractSocketWriter { 1039 public: 1040 virtual ~AbstractSocketWriter() {} 1041 1042 // Sends a string to the socket. 1043 virtual void Send(const string& message) = 0; 1044 1045 // Closes the socket. 1046 virtual void CloseConnection() {} 1047 1048 // Sends a string and a newline to the socket. 1049 void SendLn(const string& message) { 1050 Send(message + "\n"); 1051 } 1052 }; 1053 1054 // Concrete class for actually writing strings to a socket. 1055 class SocketWriter : public AbstractSocketWriter { 1056 public: 1057 SocketWriter(const string& host, const string& port) 1058 : sockfd_(-1), host_name_(host), port_num_(port) { 1059 MakeConnection(); 1060 } 1061 1062 virtual ~SocketWriter() { 1063 if (sockfd_ != -1) 1064 CloseConnection(); 1065 } 1066 1067 // Sends a string to the socket. 1068 virtual void Send(const string& message) { 1069 GTEST_CHECK_(sockfd_ != -1) 1070 << "Send() can be called only when there is a connection."; 1071 1072 const int len = static_cast<int>(message.length()); 1073 if (write(sockfd_, message.c_str(), len) != len) { 1074 GTEST_LOG_(WARNING) 1075 << "stream_result_to: failed to stream to " 1076 << host_name_ << ":" << port_num_; 1077 } 1078 } 1079 1080 private: 1081 // Creates a client socket and connects to the server. 1082 void MakeConnection(); 1083 1084 // Closes the socket. 1085 void CloseConnection() { 1086 GTEST_CHECK_(sockfd_ != -1) 1087 << "CloseConnection() can be called only when there is a connection."; 1088 1089 close(sockfd_); 1090 sockfd_ = -1; 1091 } 1092 1093 int sockfd_; // socket file descriptor 1094 const string host_name_; 1095 const string port_num_; 1096 1097 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); 1098 }; // class SocketWriter 1099 1100 // Escapes '=', '&', '%', and '\n' characters in str as "%xx". 1101 static string UrlEncode(const char* str); 1102 1103 StreamingListener(const string& host, const string& port) 1104 : socket_writer_(new SocketWriter(host, port)) { Start(); } 1105 1106 explicit StreamingListener(AbstractSocketWriter* socket_writer) 1107 : socket_writer_(socket_writer) { Start(); } 1108 1109 void OnTestProgramStart(const UnitTest& /* unit_test */) { 1110 SendLn("event=TestProgramStart"); 1111 } 1112 1113 void OnTestProgramEnd(const UnitTest& unit_test) { 1114 // Note that Google Test current only report elapsed time for each 1115 // test iteration, not for the entire test program. 1116 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); 1117 1118 // Notify the streaming server to stop. 1119 socket_writer_->CloseConnection(); 1120 } 1121 1122 void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { 1123 SendLn("event=TestIterationStart&iteration=" + 1124 StreamableToString(iteration)); 1125 } 1126 1127 void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { 1128 SendLn("event=TestIterationEnd&passed=" + 1129 FormatBool(unit_test.Passed()) + "&elapsed_time=" + 1130 StreamableToString(unit_test.elapsed_time()) + "ms"); 1131 } 1132 1133 void OnTestCaseStart(const TestCase& test_case) { 1134 SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); 1135 } 1136 1137 void OnTestCaseEnd(const TestCase& test_case) { 1138 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) 1139 + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) 1140 + "ms"); 1141 } 1142 1143 void OnTestStart(const TestInfo& test_info) { 1144 SendLn(std::string("event=TestStart&name=") + test_info.name()); 1145 } 1146 1147 void OnTestEnd(const TestInfo& test_info) { 1148 SendLn("event=TestEnd&passed=" + 1149 FormatBool((test_info.result())->Passed()) + 1150 "&elapsed_time=" + 1151 StreamableToString((test_info.result())->elapsed_time()) + "ms"); 1152 } 1153 1154 void OnTestPartResult(const TestPartResult& test_part_result) { 1155 const char* file_name = test_part_result.file_name(); 1156 if (file_name == NULL) 1157 file_name = ""; 1158 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + 1159 "&line=" + StreamableToString(test_part_result.line_number()) + 1160 "&message=" + UrlEncode(test_part_result.message())); 1161 } 1162 1163 private: 1164 // Sends the given message and a newline to the socket. 1165 void SendLn(const string& message) { socket_writer_->SendLn(message); } 1166 1167 // Called at the start of streaming to notify the receiver what 1168 // protocol we are using. 1169 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } 1170 1171 string FormatBool(bool value) { return value ? "1" : "0"; } 1172 1173 const scoped_ptr<AbstractSocketWriter> socket_writer_; 1174 1175 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); 1176}; // class StreamingListener 1177 1178#endif // GTEST_CAN_STREAM_RESULTS_ 1179 1180} // namespace internal 1181} // namespace testing 1182 1183#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ 1184