blob: e7490573ac5fbf630111d2ac9d63ad1906f6e2a9 [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080029
Austin Schuh70cc9552019-01-21 19:46:48 -080030//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080031// The Google C++ Testing and Mocking Framework (Google Test)
Austin Schuh70cc9552019-01-21 19:46:48 -080032//
33// This header file defines the public API for Google Test. It should be
34// included by any test program that uses Google Test.
35//
36// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
37// leave some internal implementation details in this header file.
38// They are clearly marked by comments like this:
39//
40// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
41//
42// Such code is NOT meant to be used by a user directly, and is subject
43// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
44// program!
45//
46// Acknowledgment: Google Test borrowed the idea of automatic test
47// registration from Barthelemy Dagenais' (barthelemy@prologique.com)
48// easyUnit framework.
49
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080050// GOOGLETEST_CM0001 DO NOT DELETE
51
Austin Schuh3de38b02024-06-25 18:25:10 -070052#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_
53#define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
Austin Schuh70cc9552019-01-21 19:46:48 -080054
Austin Schuh3de38b02024-06-25 18:25:10 -070055#include <cstddef>
Austin Schuh70cc9552019-01-21 19:46:48 -080056#include <limits>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080057#include <memory>
Austin Schuh70cc9552019-01-21 19:46:48 -080058#include <ostream>
Austin Schuh3de38b02024-06-25 18:25:10 -070059#include <type_traits>
Austin Schuh70cc9552019-01-21 19:46:48 -080060#include <vector>
61
62// Copyright 2005, Google Inc.
63// All rights reserved.
64//
65// Redistribution and use in source and binary forms, with or without
66// modification, are permitted provided that the following conditions are
67// met:
68//
69// * Redistributions of source code must retain the above copyright
70// notice, this list of conditions and the following disclaimer.
71// * Redistributions in binary form must reproduce the above
72// copyright notice, this list of conditions and the following disclaimer
73// in the documentation and/or other materials provided with the
74// distribution.
75// * Neither the name of Google Inc. nor the names of its
76// contributors may be used to endorse or promote products derived from
77// this software without specific prior written permission.
78//
79// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
80// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
81// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
82// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
83// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
84// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
85// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
86// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
87// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
88// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
89// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
90//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080091// The Google C++ Testing and Mocking Framework (Google Test)
Austin Schuh70cc9552019-01-21 19:46:48 -080092//
93// This header file declares functions and macros used internally by
94// Google Test. They are subject to change without notice.
95
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080096// GOOGLETEST_CM0001 DO NOT DELETE
97
Austin Schuh3de38b02024-06-25 18:25:10 -070098#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
99#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
Austin Schuh70cc9552019-01-21 19:46:48 -0800100
101// Copyright 2005, Google Inc.
102// All rights reserved.
103//
104// Redistribution and use in source and binary forms, with or without
105// modification, are permitted provided that the following conditions are
106// met:
107//
108// * Redistributions of source code must retain the above copyright
109// notice, this list of conditions and the following disclaimer.
110// * Redistributions in binary form must reproduce the above
111// copyright notice, this list of conditions and the following disclaimer
112// in the documentation and/or other materials provided with the
113// distribution.
114// * Neither the name of Google Inc. nor the names of its
115// contributors may be used to endorse or promote products derived from
116// this software without specific prior written permission.
117//
118// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
119// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
120// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
121// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
122// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
123// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
124// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
125// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
126// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
127// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
128// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
129//
Austin Schuh70cc9552019-01-21 19:46:48 -0800130// Low-level types and utilities for porting Google Test to various
131// platforms. All macros ending with _ and symbols defined in an
132// internal namespace are subject to change without notice. Code
133// outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't
134// end with _ are part of Google Test's public API and can be used by
135// code outside Google Test.
136//
137// This file is fundamental to Google Test. All other Google Test source
138// files are expected to #include this. Therefore, it cannot #include
139// any other Google Test header.
140
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800141// GOOGLETEST_CM0001 DO NOT DELETE
142
Austin Schuh3de38b02024-06-25 18:25:10 -0700143#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
144#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
Austin Schuh70cc9552019-01-21 19:46:48 -0800145
146// Environment-describing macros
147// -----------------------------
148//
149// Google Test can be used in many different environments. Macros in
150// this section tell Google Test what kind of environment it is being
151// used in, such that Google Test can provide environment-specific
152// features and implementations.
153//
154// Google Test tries to automatically detect the properties of its
155// environment, so users usually don't need to worry about these
156// macros. However, the automatic detection is not perfect.
157// Sometimes it's necessary for a user to define some of the following
158// macros in the build script to override Google Test's decisions.
159//
160// If the user doesn't define a macro in the list, Google Test will
161// provide a default definition. After this header is #included, all
162// macros in this list will be defined to either 1 or 0.
163//
164// Notes to maintainers:
165// - Each macro here is a user-tweakable knob; do not grow the list
166// lightly.
167// - Use #if to key off these macros. Don't use #ifdef or "#if
168// defined(...)", which will not work as these macros are ALWAYS
169// defined.
170//
171// GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2)
172// is/isn't available.
173// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions
174// are enabled.
Austin Schuh70cc9552019-01-21 19:46:48 -0800175// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular
176// expressions are/aren't available.
177// GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h>
178// is/isn't available.
179// GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't
180// enabled.
181// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that
182// std::wstring does/doesn't work (Google Test can
183// be used where std::wstring is unavailable).
Austin Schuh70cc9552019-01-21 19:46:48 -0800184// GTEST_HAS_SEH - Define it to 1/0 to indicate whether the
185// compiler supports Microsoft's "Structured
186// Exception Handling".
187// GTEST_HAS_STREAM_REDIRECTION
188// - Define it to 1/0 to indicate whether the
189// platform supports I/O stream redirection using
190// dup() and dup2().
Austin Schuh70cc9552019-01-21 19:46:48 -0800191// GTEST_LINKED_AS_SHARED_LIBRARY
192// - Define to 1 when compiling tests that use
193// Google Test as a shared library (known as
194// DLL on Windows).
195// GTEST_CREATE_SHARED_LIBRARY
196// - Define to 1 when compiling Google Test itself
197// as a shared library.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800198// GTEST_DEFAULT_DEATH_TEST_STYLE
199// - The default value of --gtest_death_test_style.
200// The legacy default has been "fast" in the open
201// source version since 2008. The recommended value
202// is "threadsafe", and can be set in
203// custom/gtest-port.h.
Austin Schuh70cc9552019-01-21 19:46:48 -0800204
205// Platform-indicating macros
206// --------------------------
207//
208// Macros indicating the platform on which Google Test is being used
209// (a macro is defined to 1 if compiled on the given platform;
210// otherwise UNDEFINED -- it's never defined to 0.). Google Test
211// defines these macros automatically. Code outside Google Test MUST
212// NOT define them.
213//
214// GTEST_OS_AIX - IBM AIX
215// GTEST_OS_CYGWIN - Cygwin
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800216// GTEST_OS_DRAGONFLY - DragonFlyBSD
Austin Schuh70cc9552019-01-21 19:46:48 -0800217// GTEST_OS_FREEBSD - FreeBSD
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800218// GTEST_OS_FUCHSIA - Fuchsia
219// GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD
Austin Schuh3de38b02024-06-25 18:25:10 -0700220// GTEST_OS_HAIKU - Haiku
Austin Schuh70cc9552019-01-21 19:46:48 -0800221// GTEST_OS_HPUX - HP-UX
222// GTEST_OS_LINUX - Linux
223// GTEST_OS_LINUX_ANDROID - Google Android
224// GTEST_OS_MAC - Mac OS X
225// GTEST_OS_IOS - iOS
226// GTEST_OS_NACL - Google Native Client (NaCl)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800227// GTEST_OS_NETBSD - NetBSD
Austin Schuh70cc9552019-01-21 19:46:48 -0800228// GTEST_OS_OPENBSD - OpenBSD
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800229// GTEST_OS_OS2 - OS/2
Austin Schuh70cc9552019-01-21 19:46:48 -0800230// GTEST_OS_QNX - QNX
231// GTEST_OS_SOLARIS - Sun Solaris
Austin Schuh70cc9552019-01-21 19:46:48 -0800232// GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile)
233// GTEST_OS_WINDOWS_DESKTOP - Windows Desktop
234// GTEST_OS_WINDOWS_MINGW - MinGW
235// GTEST_OS_WINDOWS_MOBILE - Windows Mobile
236// GTEST_OS_WINDOWS_PHONE - Windows Phone
237// GTEST_OS_WINDOWS_RT - Windows Store App/WinRT
238// GTEST_OS_ZOS - z/OS
239//
Austin Schuh3de38b02024-06-25 18:25:10 -0700240// Among the platforms, Cygwin, Linux, Mac OS X, and Windows have the
Austin Schuh70cc9552019-01-21 19:46:48 -0800241// most stable support. Since core members of the Google Test project
242// don't have access to other platforms, support for them may be less
243// stable. If you notice any problems on your platform, please notify
244// googletestframework@googlegroups.com (patches for fixing them are
245// even more welcome!).
246//
247// It is possible that none of the GTEST_OS_* macros are defined.
248
249// Feature-indicating macros
250// -------------------------
251//
252// Macros indicating which Google Test features are available (a macro
253// is defined to 1 if the corresponding feature is supported;
254// otherwise UNDEFINED -- it's never defined to 0.). Google Test
255// defines these macros automatically. Code outside Google Test MUST
256// NOT define them.
257//
258// These macros are public so that portable tests can be written.
259// Such tests typically surround code using a feature with an #if
260// which controls that code. For example:
261//
262// #if GTEST_HAS_DEATH_TEST
263// EXPECT_DEATH(DoSomethingDeadly());
264// #endif
265//
Austin Schuh70cc9552019-01-21 19:46:48 -0800266// GTEST_HAS_DEATH_TEST - death tests
Austin Schuh70cc9552019-01-21 19:46:48 -0800267// GTEST_HAS_TYPED_TEST - typed tests
268// GTEST_HAS_TYPED_TEST_P - type-parameterized tests
269// GTEST_IS_THREADSAFE - Google Test is thread-safe.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800270// GOOGLETEST_CM0007 DO NOT DELETE
Austin Schuh70cc9552019-01-21 19:46:48 -0800271// GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with
272// GTEST_HAS_POSIX_RE (see above) which users can
273// define themselves.
274// GTEST_USES_SIMPLE_RE - our own simple regex is used;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800275// the above RE\b(s) are mutually exclusive.
Austin Schuh70cc9552019-01-21 19:46:48 -0800276
277// Misc public macros
278// ------------------
279//
280// GTEST_FLAG(flag_name) - references the variable corresponding to
281// the given Google Test flag.
282
283// Internal utilities
284// ------------------
285//
286// The following macros and utilities are for Google Test's INTERNAL
287// use only. Code outside Google Test MUST NOT USE THEM DIRECTLY.
288//
289// Macros for basic C++ coding:
290// GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
291// GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a
292// variable don't have to be used.
Austin Schuh3de38b02024-06-25 18:25:10 -0700293// GTEST_DISALLOW_ASSIGN_ - disables copy operator=.
Austin Schuh70cc9552019-01-21 19:46:48 -0800294// GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
Austin Schuh3de38b02024-06-25 18:25:10 -0700295// GTEST_DISALLOW_MOVE_ASSIGN_ - disables move operator=.
296// GTEST_DISALLOW_MOVE_AND_ASSIGN_ - disables move ctor and operator=.
Austin Schuh70cc9552019-01-21 19:46:48 -0800297// GTEST_MUST_USE_RESULT_ - declares that a function's result must be used.
298// GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
299// suppressed (constant conditional).
300// GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
301// is suppressed.
Austin Schuh3de38b02024-06-25 18:25:10 -0700302// GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
303// UniversalPrinter<absl::any> specializations.
304// GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
305// or
306// UniversalPrinter<absl::optional>
307// specializations.
308// GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
309// Matcher<absl::string_view>
310// specializations.
311// GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
312// UniversalPrinter<absl::variant>
313// specializations.
Austin Schuh70cc9552019-01-21 19:46:48 -0800314//
Austin Schuh70cc9552019-01-21 19:46:48 -0800315// Synchronization:
316// Mutex, MutexLock, ThreadLocal, GetThreadCount()
317// - synchronization primitives.
318//
Austin Schuh70cc9552019-01-21 19:46:48 -0800319// Regular expressions:
320// RE - a simple regular expression class using the POSIX
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800321// Extended Regular Expression syntax on UNIX-like platforms
322// GOOGLETEST_CM0008 DO NOT DELETE
323// or a reduced regular exception syntax on other
324// platforms, including Windows.
Austin Schuh70cc9552019-01-21 19:46:48 -0800325// Logging:
326// GTEST_LOG_() - logs messages at the specified severity level.
327// LogToStderr() - directs all log messages to stderr.
328// FlushInfoLog() - flushes informational log messages.
329//
330// Stdout and stderr capturing:
331// CaptureStdout() - starts capturing stdout.
332// GetCapturedStdout() - stops capturing stdout and returns the captured
333// string.
334// CaptureStderr() - starts capturing stderr.
335// GetCapturedStderr() - stops capturing stderr and returns the captured
336// string.
337//
338// Integer types:
339// TypeWithSize - maps an integer to a int type.
Austin Schuh3de38b02024-06-25 18:25:10 -0700340// TimeInMillis - integers of known sizes.
Austin Schuh70cc9552019-01-21 19:46:48 -0800341// BiggestInt - the biggest signed integer type.
342//
343// Command-line utilities:
344// GTEST_DECLARE_*() - declares a flag.
345// GTEST_DEFINE_*() - defines a flag.
346// GetInjectableArgvs() - returns the command line as a vector of strings.
347//
348// Environment variable utilities:
349// GetEnv() - gets the value of an environment variable.
350// BoolFromGTestEnv() - parses a bool environment variable.
Austin Schuh3de38b02024-06-25 18:25:10 -0700351// Int32FromGTestEnv() - parses an int32_t environment variable.
Austin Schuh70cc9552019-01-21 19:46:48 -0800352// StringFromGTestEnv() - parses a string environment variable.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800353//
354// Deprecation warnings:
355// GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as
356// deprecated; calling a marked function
357// should generate a compiler warning
Austin Schuh70cc9552019-01-21 19:46:48 -0800358
359#include <ctype.h> // for isspace, etc
360#include <stddef.h> // for ptrdiff_t
Austin Schuh70cc9552019-01-21 19:46:48 -0800361#include <stdio.h>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800362#include <stdlib.h>
Austin Schuh70cc9552019-01-21 19:46:48 -0800363#include <string.h>
Austin Schuh3de38b02024-06-25 18:25:10 -0700364
365#include <cerrno>
366#include <cstdint>
367#include <limits>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800368#include <type_traits>
369
Austin Schuh70cc9552019-01-21 19:46:48 -0800370#ifndef _WIN32_WCE
371# include <sys/types.h>
372# include <sys/stat.h>
373#endif // !_WIN32_WCE
374
375#if defined __APPLE__
376# include <AvailabilityMacros.h>
377# include <TargetConditionals.h>
378#endif
379
Austin Schuh3de38b02024-06-25 18:25:10 -0700380#include <iostream> // NOLINT
381#include <locale>
382#include <memory>
383#include <string> // NOLINT
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800384#include <tuple>
Austin Schuh70cc9552019-01-21 19:46:48 -0800385#include <vector> // NOLINT
386
387// Copyright 2015, Google Inc.
388// All rights reserved.
389//
390// Redistribution and use in source and binary forms, with or without
391// modification, are permitted provided that the following conditions are
392// met:
393//
394// * Redistributions of source code must retain the above copyright
395// notice, this list of conditions and the following disclaimer.
396// * Redistributions in binary form must reproduce the above
397// copyright notice, this list of conditions and the following disclaimer
398// in the documentation and/or other materials provided with the
399// distribution.
400// * Neither the name of Google Inc. nor the names of its
401// contributors may be used to endorse or promote products derived from
402// this software without specific prior written permission.
403//
404// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
405// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
406// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
407// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
408// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
409// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
410// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
411// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
412// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
413// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
414// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
415//
Austin Schuh3de38b02024-06-25 18:25:10 -0700416// Injection point for custom user configurations. See README for details
417//
418// ** Custom implementation starts here **
419
420#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
421#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
422
423#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
424// Copyright 2015, Google Inc.
425// All rights reserved.
426//
427// Redistribution and use in source and binary forms, with or without
428// modification, are permitted provided that the following conditions are
429// met:
430//
431// * Redistributions of source code must retain the above copyright
432// notice, this list of conditions and the following disclaimer.
433// * Redistributions in binary form must reproduce the above
434// copyright notice, this list of conditions and the following disclaimer
435// in the documentation and/or other materials provided with the
436// distribution.
437// * Neither the name of Google Inc. nor the names of its
438// contributors may be used to endorse or promote products derived from
439// this software without specific prior written permission.
440//
441// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
442// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
443// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
444// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
445// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
446// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
447// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
448// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
449// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
450// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
451// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
452//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800453// The Google C++ Testing and Mocking Framework (Google Test)
Austin Schuh70cc9552019-01-21 19:46:48 -0800454//
455// This header file defines the GTEST_OS_* macro.
456// It is separate from gtest-port.h so that custom/gtest-port.h can include it.
457
Austin Schuh3de38b02024-06-25 18:25:10 -0700458#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
459#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
Austin Schuh70cc9552019-01-21 19:46:48 -0800460
461// Determines the platform on which Google Test is compiled.
462#ifdef __CYGWIN__
463# define GTEST_OS_CYGWIN 1
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800464# elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
465# define GTEST_OS_WINDOWS_MINGW 1
466# define GTEST_OS_WINDOWS 1
Austin Schuh70cc9552019-01-21 19:46:48 -0800467#elif defined _WIN32
468# define GTEST_OS_WINDOWS 1
469# ifdef _WIN32_WCE
470# define GTEST_OS_WINDOWS_MOBILE 1
Austin Schuh70cc9552019-01-21 19:46:48 -0800471# elif defined(WINAPI_FAMILY)
472# include <winapifamily.h>
473# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
474# define GTEST_OS_WINDOWS_DESKTOP 1
475# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
476# define GTEST_OS_WINDOWS_PHONE 1
477# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
478# define GTEST_OS_WINDOWS_RT 1
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800479# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
480# define GTEST_OS_WINDOWS_PHONE 1
481# define GTEST_OS_WINDOWS_TV_TITLE 1
Austin Schuh70cc9552019-01-21 19:46:48 -0800482# else
483 // WINAPI_FAMILY defined but no known partition matched.
484 // Default to desktop.
485# define GTEST_OS_WINDOWS_DESKTOP 1
486# endif
487# else
488# define GTEST_OS_WINDOWS_DESKTOP 1
489# endif // _WIN32_WCE
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800490#elif defined __OS2__
491# define GTEST_OS_OS2 1
Austin Schuh70cc9552019-01-21 19:46:48 -0800492#elif defined __APPLE__
493# define GTEST_OS_MAC 1
Austin Schuh3de38b02024-06-25 18:25:10 -0700494# include <TargetConditionals.h>
Austin Schuh70cc9552019-01-21 19:46:48 -0800495# if TARGET_OS_IPHONE
496# define GTEST_OS_IOS 1
497# endif
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800498#elif defined __DragonFly__
499# define GTEST_OS_DRAGONFLY 1
Austin Schuh70cc9552019-01-21 19:46:48 -0800500#elif defined __FreeBSD__
501# define GTEST_OS_FREEBSD 1
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800502#elif defined __Fuchsia__
503# define GTEST_OS_FUCHSIA 1
504#elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
505# define GTEST_OS_GNU_KFREEBSD 1
Austin Schuh70cc9552019-01-21 19:46:48 -0800506#elif defined __linux__
507# define GTEST_OS_LINUX 1
508# if defined __ANDROID__
509# define GTEST_OS_LINUX_ANDROID 1
510# endif
511#elif defined __MVS__
512# define GTEST_OS_ZOS 1
513#elif defined(__sun) && defined(__SVR4)
514# define GTEST_OS_SOLARIS 1
515#elif defined(_AIX)
516# define GTEST_OS_AIX 1
517#elif defined(__hpux)
518# define GTEST_OS_HPUX 1
519#elif defined __native_client__
520# define GTEST_OS_NACL 1
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800521#elif defined __NetBSD__
522# define GTEST_OS_NETBSD 1
Austin Schuh70cc9552019-01-21 19:46:48 -0800523#elif defined __OpenBSD__
524# define GTEST_OS_OPENBSD 1
525#elif defined __QNX__
526# define GTEST_OS_QNX 1
Austin Schuh3de38b02024-06-25 18:25:10 -0700527#elif defined(__HAIKU__)
528#define GTEST_OS_HAIKU 1
529#elif defined ESP8266
530#define GTEST_OS_ESP8266 1
531#elif defined ESP32
532#define GTEST_OS_ESP32 1
533#elif defined(__XTENSA__)
534#define GTEST_OS_XTENSA 1
Austin Schuh70cc9552019-01-21 19:46:48 -0800535#endif // __CYGWIN__
536
Austin Schuh3de38b02024-06-25 18:25:10 -0700537#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
Austin Schuh70cc9552019-01-21 19:46:48 -0800538
539#if !defined(GTEST_DEV_EMAIL_)
540# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
541# define GTEST_FLAG_PREFIX_ "gtest_"
542# define GTEST_FLAG_PREFIX_DASH_ "gtest-"
543# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
544# define GTEST_NAME_ "Google Test"
545# define GTEST_PROJECT_URL_ "https://github.com/google/googletest/"
546#endif // !defined(GTEST_DEV_EMAIL_)
547
548#if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
549# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
550#endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
551
552// Determines the version of gcc that is used to compile this.
553#ifdef __GNUC__
554// 40302 means version 4.3.2.
555# define GTEST_GCC_VER_ \
556 (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
557#endif // __GNUC__
558
559// Macros for disabling Microsoft Visual C++ warnings.
560//
561// GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
562// /* code that triggers warnings C4800 and C4385 */
563// GTEST_DISABLE_MSC_WARNINGS_POP_()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800564#if defined(_MSC_VER)
Austin Schuh70cc9552019-01-21 19:46:48 -0800565# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
566 __pragma(warning(push)) \
567 __pragma(warning(disable: warnings))
568# define GTEST_DISABLE_MSC_WARNINGS_POP_() \
569 __pragma(warning(pop))
570#else
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800571// Not all compilers are MSVC
Austin Schuh70cc9552019-01-21 19:46:48 -0800572# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
573# define GTEST_DISABLE_MSC_WARNINGS_POP_()
574#endif
575
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800576// Clang on Windows does not understand MSVC's pragma warning.
577// We need clang-specific way to disable function deprecation warning.
578#ifdef __clang__
579# define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
580 _Pragma("clang diagnostic push") \
581 _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \
582 _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"")
583#define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
584 _Pragma("clang diagnostic pop")
585#else
586# define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
587 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
588# define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
589 GTEST_DISABLE_MSC_WARNINGS_POP_()
Austin Schuh70cc9552019-01-21 19:46:48 -0800590#endif
591
592// Brings in definitions for functions used in the testing::internal::posix
593// namespace (read, write, close, chdir, isatty, stat). We do not currently
594// use them on Windows Mobile.
595#if GTEST_OS_WINDOWS
596# if !GTEST_OS_WINDOWS_MOBILE
597# include <direct.h>
598# include <io.h>
599# endif
600// In order to avoid having to include <windows.h>, use forward declaration
601#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
602// MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two
603// separate (equivalent) structs, instead of using typedef
604typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
605#else
606// Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.
607// This assumption is verified by
608// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
609typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
610#endif
Austin Schuh3de38b02024-06-25 18:25:10 -0700611#elif GTEST_OS_XTENSA
612#include <unistd.h>
613// Xtensa toolchains define strcasecmp in the string.h header instead of
614// strings.h. string.h is already included.
Austin Schuh70cc9552019-01-21 19:46:48 -0800615#else
616// This assumes that non-Windows OSes provide unistd.h. For OSes where this
617// is not the case, we need to include headers that provide the functions
618// mentioned above.
619# include <unistd.h>
620# include <strings.h>
621#endif // GTEST_OS_WINDOWS
622
623#if GTEST_OS_LINUX_ANDROID
624// Used to define __ANDROID_API__ matching the target NDK API level.
625# include <android/api-level.h> // NOLINT
626#endif
627
Austin Schuh3de38b02024-06-25 18:25:10 -0700628// Defines this to true if and only if Google Test can use POSIX regular
629// expressions.
Austin Schuh70cc9552019-01-21 19:46:48 -0800630#ifndef GTEST_HAS_POSIX_RE
631# if GTEST_OS_LINUX_ANDROID
632// On Android, <regex.h> is only available starting with Gingerbread.
633# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
634# else
Austin Schuh3de38b02024-06-25 18:25:10 -0700635#define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA)
Austin Schuh70cc9552019-01-21 19:46:48 -0800636# endif
637#endif
638
639#if GTEST_USES_PCRE
640// The appropriate headers have already been included.
641
642#elif GTEST_HAS_POSIX_RE
643
644// On some platforms, <regex.h> needs someone to define size_t, and
645// won't compile otherwise. We can #include it here as we already
646// included <stdlib.h>, which is guaranteed to define size_t through
647// <stddef.h>.
648# include <regex.h> // NOLINT
649
650# define GTEST_USES_POSIX_RE 1
651
652#elif GTEST_OS_WINDOWS
653
654// <regex.h> is not available on Windows. Use our own simple regex
655// implementation instead.
656# define GTEST_USES_SIMPLE_RE 1
657
658#else
659
660// <regex.h> may not be available on this platform. Use our own
661// simple regex implementation instead.
662# define GTEST_USES_SIMPLE_RE 1
663
664#endif // GTEST_USES_PCRE
665
666#ifndef GTEST_HAS_EXCEPTIONS
667// The user didn't tell us whether exceptions are enabled, so we need
668// to figure it out.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800669# if defined(_MSC_VER) && defined(_CPPUNWIND)
Austin Schuh3de38b02024-06-25 18:25:10 -0700670// MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800671# define GTEST_HAS_EXCEPTIONS 1
672# elif defined(__BORLANDC__)
673// C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS
Austin Schuh70cc9552019-01-21 19:46:48 -0800674// macro to enable exceptions, so we'll do the same.
675// Assumes that exceptions are enabled by default.
676# ifndef _HAS_EXCEPTIONS
677# define _HAS_EXCEPTIONS 1
678# endif // _HAS_EXCEPTIONS
679# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
680# elif defined(__clang__)
Austin Schuh3de38b02024-06-25 18:25:10 -0700681// clang defines __EXCEPTIONS if and only if exceptions are enabled before clang
682// 220714, but if and only if cleanups are enabled after that. In Obj-C++ files,
683// there can be cleanups for ObjC exceptions which also need cleanups, even if
684// C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which
685// checks for C++ exceptions starting at clang r206352, but which checked for
686// cleanups prior to that. To reliably check for C++ exception availability with
687// clang, check for
Austin Schuh70cc9552019-01-21 19:46:48 -0800688// __EXCEPTIONS && __has_feature(cxx_exceptions).
689# define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
690# elif defined(__GNUC__) && __EXCEPTIONS
Austin Schuh3de38b02024-06-25 18:25:10 -0700691// gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
Austin Schuh70cc9552019-01-21 19:46:48 -0800692# define GTEST_HAS_EXCEPTIONS 1
693# elif defined(__SUNPRO_CC)
694// Sun Pro CC supports exceptions. However, there is no compile-time way of
695// detecting whether they are enabled or not. Therefore, we assume that
696// they are enabled unless the user tells us otherwise.
697# define GTEST_HAS_EXCEPTIONS 1
698# elif defined(__IBMCPP__) && __EXCEPTIONS
Austin Schuh3de38b02024-06-25 18:25:10 -0700699// xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
Austin Schuh70cc9552019-01-21 19:46:48 -0800700# define GTEST_HAS_EXCEPTIONS 1
701# elif defined(__HP_aCC)
702// Exception handling is in effect by default in HP aCC compiler. It has to
703// be turned of by +noeh compiler option if desired.
704# define GTEST_HAS_EXCEPTIONS 1
705# else
706// For other compilers, we assume exceptions are disabled to be
707// conservative.
708# define GTEST_HAS_EXCEPTIONS 0
709# endif // defined(_MSC_VER) || defined(__BORLANDC__)
710#endif // GTEST_HAS_EXCEPTIONS
711
Austin Schuh70cc9552019-01-21 19:46:48 -0800712#ifndef GTEST_HAS_STD_WSTRING
713// The user didn't tell us whether ::std::wstring is available, so we need
714// to figure it out.
Austin Schuh70cc9552019-01-21 19:46:48 -0800715// Cygwin 1.7 and below doesn't support ::std::wstring.
716// Solaris' libc++ doesn't support it either. Android has
717// no support for it at least as recent as Froyo (2.2).
Austin Schuh3de38b02024-06-25 18:25:10 -0700718#define GTEST_HAS_STD_WSTRING \
719 (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
720 GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || GTEST_OS_XTENSA))
Austin Schuh70cc9552019-01-21 19:46:48 -0800721
722#endif // GTEST_HAS_STD_WSTRING
723
Austin Schuh70cc9552019-01-21 19:46:48 -0800724// Determines whether RTTI is available.
725#ifndef GTEST_HAS_RTTI
726// The user didn't tell us whether RTTI is enabled, so we need to
727// figure it out.
728
729# ifdef _MSC_VER
730
Austin Schuh3de38b02024-06-25 18:25:10 -0700731#ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled.
Austin Schuh70cc9552019-01-21 19:46:48 -0800732# define GTEST_HAS_RTTI 1
733# else
734# define GTEST_HAS_RTTI 0
735# endif
736
Austin Schuh3de38b02024-06-25 18:25:10 -0700737// Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is
738// enabled.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800739# elif defined(__GNUC__)
Austin Schuh70cc9552019-01-21 19:46:48 -0800740
741# ifdef __GXX_RTTI
742// When building against STLport with the Android NDK and with
743// -frtti -fno-exceptions, the build fails at link time with undefined
744// references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
745// so disable RTTI when detected.
746# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
747 !defined(__EXCEPTIONS)
748# define GTEST_HAS_RTTI 0
749# else
750# define GTEST_HAS_RTTI 1
751# endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
752# else
753# define GTEST_HAS_RTTI 0
754# endif // __GXX_RTTI
755
756// Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
757// using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
758// first version with C++ support.
759# elif defined(__clang__)
760
761# define GTEST_HAS_RTTI __has_feature(cxx_rtti)
762
763// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
764// both the typeid and dynamic_cast features are present.
765# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
766
767# ifdef __RTTI_ALL__
768# define GTEST_HAS_RTTI 1
769# else
770# define GTEST_HAS_RTTI 0
771# endif
772
773# else
774
775// For all other compilers, we assume RTTI is enabled.
776# define GTEST_HAS_RTTI 1
777
778# endif // _MSC_VER
779
780#endif // GTEST_HAS_RTTI
781
782// It's this header's responsibility to #include <typeinfo> when RTTI
783// is enabled.
784#if GTEST_HAS_RTTI
785# include <typeinfo>
786#endif
787
788// Determines whether Google Test can use the pthreads library.
789#ifndef GTEST_HAS_PTHREAD
790// The user didn't tell us explicitly, so we make reasonable assumptions about
791// which platforms have pthreads support.
792//
793// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
794// to your compiler flags.
Austin Schuh3de38b02024-06-25 18:25:10 -0700795#define GTEST_HAS_PTHREAD \
796 (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800797 GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
Austin Schuh3de38b02024-06-25 18:25:10 -0700798 GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \
799 GTEST_OS_HAIKU)
Austin Schuh70cc9552019-01-21 19:46:48 -0800800#endif // GTEST_HAS_PTHREAD
801
802#if GTEST_HAS_PTHREAD
803// gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
804// true.
805# include <pthread.h> // NOLINT
806
807// For timespec and nanosleep, used below.
808# include <time.h> // NOLINT
809#endif
810
Austin Schuh70cc9552019-01-21 19:46:48 -0800811// Determines whether clone(2) is supported.
812// Usually it will only be available on Linux, excluding
813// Linux on the Itanium architecture.
814// Also see http://linux.die.net/man/2/clone.
815#ifndef GTEST_HAS_CLONE
816// The user didn't tell us, so we need to figure it out.
817
818# if GTEST_OS_LINUX && !defined(__ia64__)
819# if GTEST_OS_LINUX_ANDROID
820// On Android, clone() became available at different API levels for each 32-bit
821// architecture.
822# if defined(__LP64__) || \
823 (defined(__arm__) && __ANDROID_API__ >= 9) || \
824 (defined(__mips__) && __ANDROID_API__ >= 12) || \
825 (defined(__i386__) && __ANDROID_API__ >= 17)
826# define GTEST_HAS_CLONE 1
827# else
828# define GTEST_HAS_CLONE 0
829# endif
830# else
831# define GTEST_HAS_CLONE 1
832# endif
833# else
834# define GTEST_HAS_CLONE 0
835# endif // GTEST_OS_LINUX && !defined(__ia64__)
836
837#endif // GTEST_HAS_CLONE
838
839// Determines whether to support stream redirection. This is used to test
840// output correctness and to implement death tests.
841#ifndef GTEST_HAS_STREAM_REDIRECTION
842// By default, we assume that stream redirection is supported on all
843// platforms except known mobile ones.
Austin Schuh3de38b02024-06-25 18:25:10 -0700844#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
845 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
Austin Schuh70cc9552019-01-21 19:46:48 -0800846# define GTEST_HAS_STREAM_REDIRECTION 0
847# else
848# define GTEST_HAS_STREAM_REDIRECTION 1
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800849# endif // !GTEST_OS_WINDOWS_MOBILE
Austin Schuh70cc9552019-01-21 19:46:48 -0800850#endif // GTEST_HAS_STREAM_REDIRECTION
851
852// Determines whether to support death tests.
Austin Schuh70cc9552019-01-21 19:46:48 -0800853// pops up a dialog window that cannot be suppressed programmatically.
Austin Schuh3de38b02024-06-25 18:25:10 -0700854#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
855 (GTEST_OS_MAC && !GTEST_OS_IOS) || \
856 (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \
857 GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \
858 GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
859 GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU)
Austin Schuh70cc9552019-01-21 19:46:48 -0800860# define GTEST_HAS_DEATH_TEST 1
861#endif
862
Austin Schuh70cc9552019-01-21 19:46:48 -0800863// Determines whether to support type-driven tests.
864
865// Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
866// Sun Pro CC, IBM Visual Age, and HP aCC support.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800867#if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \
Austin Schuh70cc9552019-01-21 19:46:48 -0800868 defined(__IBMCPP__) || defined(__HP_aCC)
869# define GTEST_HAS_TYPED_TEST 1
870# define GTEST_HAS_TYPED_TEST_P 1
871#endif
872
Austin Schuh70cc9552019-01-21 19:46:48 -0800873// Determines whether the system compiler uses UTF-16 for encoding wide strings.
874#define GTEST_WIDE_STRING_USES_UTF16_ \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800875 (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2)
Austin Schuh70cc9552019-01-21 19:46:48 -0800876
877// Determines whether test results can be streamed to a socket.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800878#if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \
879 GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD
Austin Schuh70cc9552019-01-21 19:46:48 -0800880# define GTEST_CAN_STREAM_RESULTS_ 1
881#endif
882
883// Defines some utility macros.
884
885// The GNU compiler emits a warning if nested "if" statements are followed by
886// an "else" statement and braces are not used to explicitly disambiguate the
887// "else" binding. This leads to problems with code like:
888//
889// if (gate)
890// ASSERT_*(condition) << "Some message";
891//
892// The "switch (0) case 0:" idiom is used to suppress this.
893#ifdef __INTEL_COMPILER
894# define GTEST_AMBIGUOUS_ELSE_BLOCKER_
895#else
896# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT
897#endif
898
899// Use this annotation at the end of a struct/class definition to
900// prevent the compiler from optimizing away instances that are never
901// used. This is useful when all interesting logic happens inside the
902// c'tor and / or d'tor. Example:
903//
904// struct Foo {
905// Foo() { ... }
906// } GTEST_ATTRIBUTE_UNUSED_;
907//
908// Also use it after a variable or parameter declaration to tell the
909// compiler the variable/parameter does not have to be used.
910#if defined(__GNUC__) && !defined(COMPILER_ICC)
911# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
912#elif defined(__clang__)
913# if __has_attribute(unused)
914# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
915# endif
916#endif
917#ifndef GTEST_ATTRIBUTE_UNUSED_
918# define GTEST_ATTRIBUTE_UNUSED_
919#endif
920
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800921// Use this annotation before a function that takes a printf format string.
922#if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC)
923# if defined(__MINGW_PRINTF_FORMAT)
924// MinGW has two different printf implementations. Ensure the format macro
925// matches the selected implementation. See
926// https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.
927# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
928 __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \
929 first_to_check)))
930# else
931# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
932 __attribute__((__format__(__printf__, string_index, first_to_check)))
933# endif
934#else
935# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
936#endif
937
938
Austin Schuh3de38b02024-06-25 18:25:10 -0700939// A macro to disallow copy operator=
Austin Schuh70cc9552019-01-21 19:46:48 -0800940// This should be used in the private: declarations for a class.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800941#define GTEST_DISALLOW_ASSIGN_(type) \
Austin Schuh3de38b02024-06-25 18:25:10 -0700942 type& operator=(type const &) = delete
Austin Schuh70cc9552019-01-21 19:46:48 -0800943
944// A macro to disallow copy constructor and operator=
945// This should be used in the private: declarations for a class.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800946#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \
Austin Schuh3de38b02024-06-25 18:25:10 -0700947 type(type const&) = delete; \
948 type& operator=(type const&) = delete
949
950// A macro to disallow move operator=
951// This should be used in the private: declarations for a class.
952#define GTEST_DISALLOW_MOVE_ASSIGN_(type) \
953 type& operator=(type &&) noexcept = delete
954
955// A macro to disallow move constructor and operator=
956// This should be used in the private: declarations for a class.
957#define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \
958 type(type&&) noexcept = delete; \
959 type& operator=(type&&) noexcept = delete
Austin Schuh70cc9552019-01-21 19:46:48 -0800960
961// Tell the compiler to warn about unused return values for functions declared
962// with this macro. The macro should be used on function declarations
963// following the argument list:
964//
965// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800966#if defined(__GNUC__) && !defined(COMPILER_ICC)
Austin Schuh70cc9552019-01-21 19:46:48 -0800967# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
968#else
969# define GTEST_MUST_USE_RESULT_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800970#endif // __GNUC__ && !COMPILER_ICC
Austin Schuh70cc9552019-01-21 19:46:48 -0800971
972// MS C++ compiler emits warning when a conditional expression is compile time
973// constant. In some contexts this warning is false positive and needs to be
974// suppressed. Use the following two macros in such cases:
975//
976// GTEST_INTENTIONAL_CONST_COND_PUSH_()
977// while (true) {
978// GTEST_INTENTIONAL_CONST_COND_POP_()
979// }
980# define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
981 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
982# define GTEST_INTENTIONAL_CONST_COND_POP_() \
983 GTEST_DISABLE_MSC_WARNINGS_POP_()
984
985// Determine whether the compiler supports Microsoft's Structured Exception
986// Handling. This is supported by several Windows compilers but generally
987// does not exist on any other system.
988#ifndef GTEST_HAS_SEH
989// The user didn't tell us, so we need to figure it out.
990
991# if defined(_MSC_VER) || defined(__BORLANDC__)
992// These two compilers are known to support SEH.
993# define GTEST_HAS_SEH 1
994# else
995// Assume no SEH.
996# define GTEST_HAS_SEH 0
997# endif
998
Austin Schuh70cc9552019-01-21 19:46:48 -0800999#endif // GTEST_HAS_SEH
1000
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001001#ifndef GTEST_IS_THREADSAFE
1002
1003#define GTEST_IS_THREADSAFE \
1004 (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \
1005 (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \
1006 GTEST_HAS_PTHREAD)
1007
1008#endif // GTEST_IS_THREADSAFE
1009
1010// GTEST_API_ qualifies all symbols that must be exported. The definitions below
1011// are guarded by #ifndef to give embedders a chance to define GTEST_API_ in
1012// gtest/internal/custom/gtest-port.h
1013#ifndef GTEST_API_
1014
Austin Schuh70cc9552019-01-21 19:46:48 -08001015#ifdef _MSC_VER
1016# if GTEST_LINKED_AS_SHARED_LIBRARY
1017# define GTEST_API_ __declspec(dllimport)
1018# elif GTEST_CREATE_SHARED_LIBRARY
1019# define GTEST_API_ __declspec(dllexport)
1020# endif
1021#elif __GNUC__ >= 4 || defined(__clang__)
1022# define GTEST_API_ __attribute__((visibility ("default")))
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001023#endif // _MSC_VER
1024
1025#endif // GTEST_API_
Austin Schuh70cc9552019-01-21 19:46:48 -08001026
1027#ifndef GTEST_API_
1028# define GTEST_API_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001029#endif // GTEST_API_
1030
1031#ifndef GTEST_DEFAULT_DEATH_TEST_STYLE
1032# define GTEST_DEFAULT_DEATH_TEST_STYLE "fast"
1033#endif // GTEST_DEFAULT_DEATH_TEST_STYLE
Austin Schuh70cc9552019-01-21 19:46:48 -08001034
1035#ifdef __GNUC__
1036// Ask the compiler to never inline a given function.
1037# define GTEST_NO_INLINE_ __attribute__((noinline))
1038#else
1039# define GTEST_NO_INLINE_
1040#endif
1041
1042// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001043#if !defined(GTEST_HAS_CXXABI_H_)
1044# if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
1045# define GTEST_HAS_CXXABI_H_ 1
1046# else
1047# define GTEST_HAS_CXXABI_H_ 0
1048# endif
Austin Schuh70cc9552019-01-21 19:46:48 -08001049#endif
1050
1051// A function level attribute to disable checking for use of uninitialized
1052// memory when built with MemorySanitizer.
1053#if defined(__clang__)
1054# if __has_feature(memory_sanitizer)
1055# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
1056 __attribute__((no_sanitize_memory))
1057# else
1058# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
1059# endif // __has_feature(memory_sanitizer)
1060#else
1061# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
1062#endif // __clang__
1063
1064// A function level attribute to disable AddressSanitizer instrumentation.
1065#if defined(__clang__)
1066# if __has_feature(address_sanitizer)
1067# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
1068 __attribute__((no_sanitize_address))
1069# else
1070# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1071# endif // __has_feature(address_sanitizer)
1072#else
1073# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1074#endif // __clang__
1075
Austin Schuh3de38b02024-06-25 18:25:10 -07001076// A function level attribute to disable HWAddressSanitizer instrumentation.
1077#if defined(__clang__)
1078# if __has_feature(hwaddress_sanitizer)
1079# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
1080 __attribute__((no_sanitize("hwaddress")))
1081# else
1082# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1083# endif // __has_feature(hwaddress_sanitizer)
1084#else
1085# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1086#endif // __clang__
1087
Austin Schuh70cc9552019-01-21 19:46:48 -08001088// A function level attribute to disable ThreadSanitizer instrumentation.
1089#if defined(__clang__)
1090# if __has_feature(thread_sanitizer)
1091# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
1092 __attribute__((no_sanitize_thread))
1093# else
1094# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
1095# endif // __has_feature(thread_sanitizer)
1096#else
1097# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
1098#endif // __clang__
1099
1100namespace testing {
1101
1102class Message;
1103
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001104// Legacy imports for backwards compatibility.
1105// New code should use std:: names directly.
1106using std::get;
1107using std::make_tuple;
1108using std::tuple;
1109using std::tuple_element;
1110using std::tuple_size;
Austin Schuh70cc9552019-01-21 19:46:48 -08001111
1112namespace internal {
1113
1114// A secret type that Google Test users don't know about. It has no
1115// definition on purpose. Therefore it's impossible to create a
1116// Secret object, which is what we want.
1117class Secret;
1118
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001119// The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile
1120// time expression is true (in new code, use static_assert instead). For
1121// example, you could use it to verify the size of a static array:
Austin Schuh70cc9552019-01-21 19:46:48 -08001122//
1123// GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
1124// names_incorrect_size);
1125//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001126// The second argument to the macro must be a valid C++ identifier. If the
1127// expression is false, compiler will issue an error containing this identifier.
1128#define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
Austin Schuh70cc9552019-01-21 19:46:48 -08001129
Austin Schuh70cc9552019-01-21 19:46:48 -08001130// A helper for suppressing warnings on constant condition. It just
1131// returns 'condition'.
1132GTEST_API_ bool IsTrue(bool condition);
1133
Austin Schuh70cc9552019-01-21 19:46:48 -08001134// Defines RE.
1135
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001136#if GTEST_USES_PCRE
1137// if used, PCRE is injected by custom/gtest-port.h
1138#elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
1139
Austin Schuh70cc9552019-01-21 19:46:48 -08001140// A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
1141// Regular Expression syntax.
1142class GTEST_API_ RE {
1143 public:
1144 // A copy constructor is required by the Standard to initialize object
1145 // references from r-values.
1146 RE(const RE& other) { Init(other.pattern()); }
1147
1148 // Constructs an RE from a string.
1149 RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT
1150
Austin Schuh70cc9552019-01-21 19:46:48 -08001151 RE(const char* regex) { Init(regex); } // NOLINT
1152 ~RE();
1153
1154 // Returns the string representation of the regex.
1155 const char* pattern() const { return pattern_; }
1156
Austin Schuh3de38b02024-06-25 18:25:10 -07001157 // FullMatch(str, re) returns true if and only if regular expression re
1158 // matches the entire str.
1159 // PartialMatch(str, re) returns true if and only if regular expression re
Austin Schuh70cc9552019-01-21 19:46:48 -08001160 // matches a substring of str (including str itself).
Austin Schuh70cc9552019-01-21 19:46:48 -08001161 static bool FullMatch(const ::std::string& str, const RE& re) {
1162 return FullMatch(str.c_str(), re);
1163 }
1164 static bool PartialMatch(const ::std::string& str, const RE& re) {
1165 return PartialMatch(str.c_str(), re);
1166 }
1167
Austin Schuh70cc9552019-01-21 19:46:48 -08001168 static bool FullMatch(const char* str, const RE& re);
1169 static bool PartialMatch(const char* str, const RE& re);
1170
1171 private:
1172 void Init(const char* regex);
Austin Schuh70cc9552019-01-21 19:46:48 -08001173 const char* pattern_;
1174 bool is_valid_;
1175
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001176# if GTEST_USES_POSIX_RE
Austin Schuh70cc9552019-01-21 19:46:48 -08001177
1178 regex_t full_regex_; // For FullMatch().
1179 regex_t partial_regex_; // For PartialMatch().
1180
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001181# else // GTEST_USES_SIMPLE_RE
Austin Schuh70cc9552019-01-21 19:46:48 -08001182
1183 const char* full_pattern_; // For FullMatch();
1184
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001185# endif
Austin Schuh70cc9552019-01-21 19:46:48 -08001186};
1187
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001188#endif // GTEST_USES_PCRE
1189
Austin Schuh70cc9552019-01-21 19:46:48 -08001190// Formats a source file path and a line number as they would appear
1191// in an error message from the compiler used to compile this code.
1192GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
1193
1194// Formats a file location for compiler-independent XML output.
1195// Although this function is not platform dependent, we put it next to
1196// FormatFileLocation in order to contrast the two functions.
1197GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
1198 int line);
1199
1200// Defines logging utilities:
1201// GTEST_LOG_(severity) - logs messages at the specified severity level. The
1202// message itself is streamed into the macro.
1203// LogToStderr() - directs all log messages to stderr.
1204// FlushInfoLog() - flushes informational log messages.
1205
1206enum GTestLogSeverity {
1207 GTEST_INFO,
1208 GTEST_WARNING,
1209 GTEST_ERROR,
1210 GTEST_FATAL
1211};
1212
1213// Formats log entry severity, provides a stream object for streaming the
1214// log message, and terminates the message with a newline when going out of
1215// scope.
1216class GTEST_API_ GTestLog {
1217 public:
1218 GTestLog(GTestLogSeverity severity, const char* file, int line);
1219
1220 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
1221 ~GTestLog();
1222
1223 ::std::ostream& GetStream() { return ::std::cerr; }
1224
1225 private:
1226 const GTestLogSeverity severity_;
1227
1228 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
1229};
1230
1231#if !defined(GTEST_LOG_)
1232
1233# define GTEST_LOG_(severity) \
1234 ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
1235 __FILE__, __LINE__).GetStream()
1236
1237inline void LogToStderr() {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001238inline void FlushInfoLog() { fflush(nullptr); }
Austin Schuh70cc9552019-01-21 19:46:48 -08001239
1240#endif // !defined(GTEST_LOG_)
1241
1242#if !defined(GTEST_CHECK_)
1243// INTERNAL IMPLEMENTATION - DO NOT USE.
1244//
1245// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
1246// is not satisfied.
1247// Synopsys:
1248// GTEST_CHECK_(boolean_condition);
1249// or
1250// GTEST_CHECK_(boolean_condition) << "Additional message";
1251//
1252// This checks the condition and if the condition is not satisfied
1253// it prints message about the condition violation, including the
1254// condition itself, plus additional message streamed into it, if any,
1255// and then it aborts the program. It aborts the program irrespective of
1256// whether it is built in the debug mode or not.
1257# define GTEST_CHECK_(condition) \
1258 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1259 if (::testing::internal::IsTrue(condition)) \
1260 ; \
1261 else \
1262 GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
1263#endif // !defined(GTEST_CHECK_)
1264
1265// An all-mode assert to verify that the given POSIX-style function
1266// call returns 0 (indicating success). Known limitation: this
1267// doesn't expand to a balanced 'if' statement, so enclose the macro
1268// in {} if you need to use it as the only statement in an 'if'
1269// branch.
1270#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
1271 if (const int gtest_error = (posix_call)) \
1272 GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
1273 << gtest_error
1274
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001275// Transforms "T" into "const T&" according to standard reference collapsing
1276// rules (this is only needed as a backport for C++98 compilers that do not
1277// support reference collapsing). Specifically, it transforms:
1278//
1279// char ==> const char&
1280// const char ==> const char&
1281// char& ==> char&
1282// const char& ==> const char&
1283//
1284// Note that the non-const reference will not have "const" added. This is
1285// standard, and necessary so that "T" can always bind to "const T&".
1286template <typename T>
1287struct ConstRef { typedef const T& type; };
1288template <typename T>
1289struct ConstRef<T&> { typedef T& type; };
1290
1291// The argument T must depend on some template parameters.
1292#define GTEST_REFERENCE_TO_CONST_(T) \
1293 typename ::testing::internal::ConstRef<T>::type
Austin Schuh70cc9552019-01-21 19:46:48 -08001294
1295// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1296//
1297// Use ImplicitCast_ as a safe version of static_cast for upcasting in
1298// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
1299// const Foo*). When you use ImplicitCast_, the compiler checks that
1300// the cast is safe. Such explicit ImplicitCast_s are necessary in
1301// surprisingly many situations where C++ demands an exact type match
1302// instead of an argument type convertable to a target type.
1303//
1304// The syntax for using ImplicitCast_ is the same as for static_cast:
1305//
1306// ImplicitCast_<ToType>(expr)
1307//
1308// ImplicitCast_ would have been part of the C++ standard library,
1309// but the proposal was submitted too late. It will probably make
1310// its way into the language in the future.
1311//
1312// This relatively ugly name is intentional. It prevents clashes with
1313// similar functions users may have (e.g., implicit_cast). The internal
1314// namespace alone is not enough because the function can be found by ADL.
1315template<typename To>
1316inline To ImplicitCast_(To x) { return x; }
1317
1318// When you upcast (that is, cast a pointer from type Foo to type
1319// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
1320// always succeed. When you downcast (that is, cast a pointer from
1321// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
1322// how do you know the pointer is really of type SubclassOfFoo? It
1323// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
1324// when you downcast, you should use this macro. In debug mode, we
1325// use dynamic_cast<> to double-check the downcast is legal (we die
1326// if it's not). In normal mode, we do the efficient static_cast<>
1327// instead. Thus, it's important to test in debug mode to make sure
1328// the cast is legal!
1329// This is the only place in the code we should use dynamic_cast<>.
1330// In particular, you SHOULDN'T be using dynamic_cast<> in order to
1331// do RTTI (eg code like this:
1332// if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
1333// if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
1334// You should design the code some other way not to need this.
1335//
1336// This relatively ugly name is intentional. It prevents clashes with
1337// similar functions users may have (e.g., down_cast). The internal
1338// namespace alone is not enough because the function can be found by ADL.
1339template<typename To, typename From> // use like this: DownCast_<T*>(foo);
1340inline To DownCast_(From* f) { // so we only accept pointers
1341 // Ensures that To is a sub-type of From *. This test is here only
1342 // for compile-time type checking, and has no overhead in an
1343 // optimized build at run-time, as it will be optimized away
1344 // completely.
1345 GTEST_INTENTIONAL_CONST_COND_PUSH_()
1346 if (false) {
1347 GTEST_INTENTIONAL_CONST_COND_POP_()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001348 const To to = nullptr;
1349 ::testing::internal::ImplicitCast_<From*>(to);
Austin Schuh70cc9552019-01-21 19:46:48 -08001350 }
1351
1352#if GTEST_HAS_RTTI
1353 // RTTI: debug mode only!
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001354 GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -08001355#endif
1356 return static_cast<To>(f);
1357}
1358
1359// Downcasts the pointer of type Base to Derived.
1360// Derived must be a subclass of Base. The parameter MUST
1361// point to a class of type Derived, not any subclass of it.
1362// When RTTI is available, the function performs a runtime
1363// check to enforce this.
1364template <class Derived, class Base>
1365Derived* CheckedDowncastToActualType(Base* base) {
1366#if GTEST_HAS_RTTI
1367 GTEST_CHECK_(typeid(*base) == typeid(Derived));
1368#endif
1369
1370#if GTEST_HAS_DOWNCAST_
1371 return ::down_cast<Derived*>(base);
1372#elif GTEST_HAS_RTTI
1373 return dynamic_cast<Derived*>(base); // NOLINT
1374#else
1375 return static_cast<Derived*>(base); // Poor man's downcast.
1376#endif
1377}
1378
1379#if GTEST_HAS_STREAM_REDIRECTION
1380
1381// Defines the stderr capturer:
1382// CaptureStdout - starts capturing stdout.
1383// GetCapturedStdout - stops capturing stdout and returns the captured string.
1384// CaptureStderr - starts capturing stderr.
1385// GetCapturedStderr - stops capturing stderr and returns the captured string.
1386//
1387GTEST_API_ void CaptureStdout();
1388GTEST_API_ std::string GetCapturedStdout();
1389GTEST_API_ void CaptureStderr();
1390GTEST_API_ std::string GetCapturedStderr();
1391
1392#endif // GTEST_HAS_STREAM_REDIRECTION
Austin Schuh70cc9552019-01-21 19:46:48 -08001393// Returns the size (in bytes) of a file.
1394GTEST_API_ size_t GetFileSize(FILE* file);
1395
1396// Reads the entire content of a file as a string.
1397GTEST_API_ std::string ReadEntireFile(FILE* file);
1398
1399// All command line arguments.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001400GTEST_API_ std::vector<std::string> GetArgvs();
Austin Schuh70cc9552019-01-21 19:46:48 -08001401
1402#if GTEST_HAS_DEATH_TEST
1403
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001404std::vector<std::string> GetInjectableArgvs();
1405// Deprecated: pass the args vector by value instead.
1406void SetInjectableArgvs(const std::vector<std::string>* new_argvs);
1407void SetInjectableArgvs(const std::vector<std::string>& new_argvs);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001408void ClearInjectableArgvs();
Austin Schuh70cc9552019-01-21 19:46:48 -08001409
1410#endif // GTEST_HAS_DEATH_TEST
1411
1412// Defines synchronization primitives.
1413#if GTEST_IS_THREADSAFE
1414# if GTEST_HAS_PTHREAD
1415// Sleeps for (roughly) n milliseconds. This function is only for testing
1416// Google Test's own constructs. Don't use it in user tests, either
1417// directly or indirectly.
1418inline void SleepMilliseconds(int n) {
1419 const timespec time = {
1420 0, // 0 seconds.
1421 n * 1000L * 1000L, // And n ms.
1422 };
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001423 nanosleep(&time, nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -08001424}
1425# endif // GTEST_HAS_PTHREAD
1426
1427# if GTEST_HAS_NOTIFICATION_
1428// Notification has already been imported into the namespace.
1429// Nothing to do here.
1430
1431# elif GTEST_HAS_PTHREAD
1432// Allows a controller thread to pause execution of newly created
1433// threads until notified. Instances of this class must be created
1434// and destroyed in the controller thread.
1435//
1436// This class is only for testing Google Test's own constructs. Do not
1437// use it in user tests, either directly or indirectly.
1438class Notification {
1439 public:
1440 Notification() : notified_(false) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001441 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
Austin Schuh70cc9552019-01-21 19:46:48 -08001442 }
1443 ~Notification() {
1444 pthread_mutex_destroy(&mutex_);
1445 }
1446
1447 // Notifies all threads created with this notification to start. Must
1448 // be called from the controller thread.
1449 void Notify() {
1450 pthread_mutex_lock(&mutex_);
1451 notified_ = true;
1452 pthread_mutex_unlock(&mutex_);
1453 }
1454
1455 // Blocks until the controller thread notifies. Must be called from a test
1456 // thread.
1457 void WaitForNotification() {
1458 for (;;) {
1459 pthread_mutex_lock(&mutex_);
1460 const bool notified = notified_;
1461 pthread_mutex_unlock(&mutex_);
1462 if (notified)
1463 break;
1464 SleepMilliseconds(10);
1465 }
1466 }
1467
1468 private:
1469 pthread_mutex_t mutex_;
1470 bool notified_;
1471
1472 GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1473};
1474
1475# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1476
1477GTEST_API_ void SleepMilliseconds(int n);
1478
1479// Provides leak-safe Windows kernel handle ownership.
1480// Used in death tests and in threading support.
1481class GTEST_API_ AutoHandle {
1482 public:
1483 // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
1484 // avoid including <windows.h> in this header file. Including <windows.h> is
1485 // undesirable because it defines a lot of symbols and macros that tend to
1486 // conflict with client code. This assumption is verified by
1487 // WindowsTypesTest.HANDLEIsVoidStar.
1488 typedef void* Handle;
1489 AutoHandle();
1490 explicit AutoHandle(Handle handle);
1491
1492 ~AutoHandle();
1493
1494 Handle Get() const;
1495 void Reset();
1496 void Reset(Handle handle);
1497
1498 private:
Austin Schuh3de38b02024-06-25 18:25:10 -07001499 // Returns true if and only if the handle is a valid handle object that can be
1500 // closed.
Austin Schuh70cc9552019-01-21 19:46:48 -08001501 bool IsCloseable() const;
1502
1503 Handle handle_;
1504
1505 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1506};
1507
1508// Allows a controller thread to pause execution of newly created
1509// threads until notified. Instances of this class must be created
1510// and destroyed in the controller thread.
1511//
1512// This class is only for testing Google Test's own constructs. Do not
1513// use it in user tests, either directly or indirectly.
1514class GTEST_API_ Notification {
1515 public:
1516 Notification();
1517 void Notify();
1518 void WaitForNotification();
1519
1520 private:
1521 AutoHandle event_;
1522
1523 GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1524};
1525# endif // GTEST_HAS_NOTIFICATION_
1526
1527// On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
1528// defined, but we don't want to use MinGW's pthreads implementation, which
1529// has conformance problems with some versions of the POSIX standard.
1530# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
1531
1532// As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
1533// Consequently, it cannot select a correct instantiation of ThreadWithParam
1534// in order to call its Run(). Introducing ThreadWithParamBase as a
1535// non-templated base class for ThreadWithParam allows us to bypass this
1536// problem.
1537class ThreadWithParamBase {
1538 public:
1539 virtual ~ThreadWithParamBase() {}
1540 virtual void Run() = 0;
1541};
1542
1543// pthread_create() accepts a pointer to a function type with the C linkage.
1544// According to the Standard (7.5/1), function types with different linkages
1545// are different even if they are otherwise identical. Some compilers (for
1546// example, SunStudio) treat them as different types. Since class methods
1547// cannot be defined with C-linkage we need to define a free C-function to
1548// pass into pthread_create().
1549extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
1550 static_cast<ThreadWithParamBase*>(thread)->Run();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001551 return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08001552}
1553
1554// Helper class for testing Google Test's multi-threading constructs.
1555// To use it, write:
1556//
1557// void ThreadFunc(int param) { /* Do things with param */ }
1558// Notification thread_can_start;
1559// ...
1560// // The thread_can_start parameter is optional; you can supply NULL.
1561// ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
1562// thread_can_start.Notify();
1563//
1564// These classes are only for testing Google Test's own constructs. Do
1565// not use them in user tests, either directly or indirectly.
1566template <typename T>
1567class ThreadWithParam : public ThreadWithParamBase {
1568 public:
1569 typedef void UserThreadFunc(T);
1570
1571 ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1572 : func_(func),
1573 param_(param),
1574 thread_can_start_(thread_can_start),
1575 finished_(false) {
1576 ThreadWithParamBase* const base = this;
1577 // The thread can be created only after all fields except thread_
1578 // have been initialized.
1579 GTEST_CHECK_POSIX_SUCCESS_(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001580 pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base));
Austin Schuh70cc9552019-01-21 19:46:48 -08001581 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001582 ~ThreadWithParam() override { Join(); }
Austin Schuh70cc9552019-01-21 19:46:48 -08001583
1584 void Join() {
1585 if (!finished_) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001586 GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr));
Austin Schuh70cc9552019-01-21 19:46:48 -08001587 finished_ = true;
1588 }
1589 }
1590
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001591 void Run() override {
1592 if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification();
Austin Schuh70cc9552019-01-21 19:46:48 -08001593 func_(param_);
1594 }
1595
1596 private:
1597 UserThreadFunc* const func_; // User-supplied thread function.
1598 const T param_; // User-supplied parameter to the thread function.
1599 // When non-NULL, used to block execution until the controller thread
1600 // notifies.
1601 Notification* const thread_can_start_;
Austin Schuh3de38b02024-06-25 18:25:10 -07001602 bool finished_; // true if and only if we know that the thread function has
1603 // finished.
Austin Schuh70cc9552019-01-21 19:46:48 -08001604 pthread_t thread_; // The native thread object.
1605
1606 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1607};
1608# endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
1609 // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1610
1611# if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1612// Mutex and ThreadLocal have already been imported into the namespace.
1613// Nothing to do here.
1614
1615# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1616
1617// Mutex implements mutex on Windows platforms. It is used in conjunction
1618// with class MutexLock:
1619//
1620// Mutex mutex;
1621// ...
1622// MutexLock lock(&mutex); // Acquires the mutex and releases it at the
1623// // end of the current scope.
1624//
1625// A static Mutex *must* be defined or declared using one of the following
1626// macros:
1627// GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
1628// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
1629//
1630// (A non-static Mutex is defined/declared in the usual way).
1631class GTEST_API_ Mutex {
1632 public:
1633 enum MutexType { kStatic = 0, kDynamic = 1 };
1634 // We rely on kStaticMutex being 0 as it is to what the linker initializes
1635 // type_ in static mutexes. critical_section_ will be initialized lazily
1636 // in ThreadSafeLazyInit().
1637 enum StaticConstructorSelector { kStaticMutex = 0 };
1638
1639 // This constructor intentionally does nothing. It relies on type_ being
1640 // statically initialized to 0 (effectively setting it to kStatic) and on
1641 // ThreadSafeLazyInit() to lazily initialize the rest of the members.
1642 explicit Mutex(StaticConstructorSelector /*dummy*/) {}
1643
1644 Mutex();
1645 ~Mutex();
1646
1647 void Lock();
1648
1649 void Unlock();
1650
1651 // Does nothing if the current thread holds the mutex. Otherwise, crashes
1652 // with high probability.
1653 void AssertHeld();
1654
1655 private:
1656 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
1657 void ThreadSafeLazyInit();
1658
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001659 // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503,
Austin Schuh70cc9552019-01-21 19:46:48 -08001660 // we assume that 0 is an invalid value for thread IDs.
1661 unsigned int owner_thread_id_;
1662
1663 // For static mutexes, we rely on these members being initialized to zeros
1664 // by the linker.
1665 MutexType type_;
1666 long critical_section_init_phase_; // NOLINT
1667 GTEST_CRITICAL_SECTION* critical_section_;
1668
1669 GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1670};
1671
1672# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1673 extern ::testing::internal::Mutex mutex
1674
1675# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1676 ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
1677
1678// We cannot name this class MutexLock because the ctor declaration would
1679// conflict with a macro named MutexLock, which is defined on some
1680// platforms. That macro is used as a defensive measure to prevent against
1681// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1682// "MutexLock l(&mu)". Hence the typedef trick below.
1683class GTestMutexLock {
1684 public:
1685 explicit GTestMutexLock(Mutex* mutex)
1686 : mutex_(mutex) { mutex_->Lock(); }
1687
1688 ~GTestMutexLock() { mutex_->Unlock(); }
1689
1690 private:
1691 Mutex* const mutex_;
1692
1693 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1694};
1695
1696typedef GTestMutexLock MutexLock;
1697
1698// Base class for ValueHolder<T>. Allows a caller to hold and delete a value
1699// without knowing its type.
1700class ThreadLocalValueHolderBase {
1701 public:
1702 virtual ~ThreadLocalValueHolderBase() {}
1703};
1704
1705// Provides a way for a thread to send notifications to a ThreadLocal
1706// regardless of its parameter type.
1707class ThreadLocalBase {
1708 public:
1709 // Creates a new ValueHolder<T> object holding a default value passed to
1710 // this ThreadLocal<T>'s constructor and returns it. It is the caller's
1711 // responsibility not to call this when the ThreadLocal<T> instance already
1712 // has a value on the current thread.
1713 virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
1714
1715 protected:
1716 ThreadLocalBase() {}
1717 virtual ~ThreadLocalBase() {}
1718
1719 private:
1720 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
1721};
1722
1723// Maps a thread to a set of ThreadLocals that have values instantiated on that
1724// thread and notifies them when the thread exits. A ThreadLocal instance is
1725// expected to persist until all threads it has values on have terminated.
1726class GTEST_API_ ThreadLocalRegistry {
1727 public:
1728 // Registers thread_local_instance as having value on the current thread.
1729 // Returns a value that can be used to identify the thread from other threads.
1730 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
1731 const ThreadLocalBase* thread_local_instance);
1732
1733 // Invoked when a ThreadLocal instance is destroyed.
1734 static void OnThreadLocalDestroyed(
1735 const ThreadLocalBase* thread_local_instance);
1736};
1737
1738class GTEST_API_ ThreadWithParamBase {
1739 public:
1740 void Join();
1741
1742 protected:
1743 class Runnable {
1744 public:
1745 virtual ~Runnable() {}
1746 virtual void Run() = 0;
1747 };
1748
1749 ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
1750 virtual ~ThreadWithParamBase();
1751
1752 private:
1753 AutoHandle thread_;
1754};
1755
1756// Helper class for testing Google Test's multi-threading constructs.
1757template <typename T>
1758class ThreadWithParam : public ThreadWithParamBase {
1759 public:
1760 typedef void UserThreadFunc(T);
1761
1762 ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1763 : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
1764 }
1765 virtual ~ThreadWithParam() {}
1766
1767 private:
1768 class RunnableImpl : public Runnable {
1769 public:
1770 RunnableImpl(UserThreadFunc* func, T param)
1771 : func_(func),
1772 param_(param) {
1773 }
1774 virtual ~RunnableImpl() {}
1775 virtual void Run() {
1776 func_(param_);
1777 }
1778
1779 private:
1780 UserThreadFunc* const func_;
1781 const T param_;
1782
1783 GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
1784 };
1785
1786 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1787};
1788
1789// Implements thread-local storage on Windows systems.
1790//
1791// // Thread 1
1792// ThreadLocal<int> tl(100); // 100 is the default value for each thread.
1793//
1794// // Thread 2
1795// tl.set(150); // Changes the value for thread 2 only.
1796// EXPECT_EQ(150, tl.get());
1797//
1798// // Thread 1
1799// EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value.
1800// tl.set(200);
1801// EXPECT_EQ(200, tl.get());
1802//
1803// The template type argument T must have a public copy constructor.
1804// In addition, the default ThreadLocal constructor requires T to have
1805// a public default constructor.
1806//
1807// The users of a TheadLocal instance have to make sure that all but one
1808// threads (including the main one) using that instance have exited before
1809// destroying it. Otherwise, the per-thread objects managed for them by the
1810// ThreadLocal instance are not guaranteed to be destroyed on all platforms.
1811//
1812// Google Test only uses global ThreadLocal objects. That means they
1813// will die after main() has returned. Therefore, no per-thread
1814// object managed by Google Test will be leaked as long as all threads
1815// using Google Test have exited when main() returns.
1816template <typename T>
1817class ThreadLocal : public ThreadLocalBase {
1818 public:
1819 ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
1820 explicit ThreadLocal(const T& value)
1821 : default_factory_(new InstanceValueHolderFactory(value)) {}
1822
1823 ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
1824
1825 T* pointer() { return GetOrCreateValue(); }
1826 const T* pointer() const { return GetOrCreateValue(); }
1827 const T& get() const { return *pointer(); }
1828 void set(const T& value) { *pointer() = value; }
1829
1830 private:
1831 // Holds a value of T. Can be deleted via its base class without the caller
1832 // knowing the type of T.
1833 class ValueHolder : public ThreadLocalValueHolderBase {
1834 public:
1835 ValueHolder() : value_() {}
1836 explicit ValueHolder(const T& value) : value_(value) {}
1837
1838 T* pointer() { return &value_; }
1839
1840 private:
1841 T value_;
1842 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
1843 };
1844
1845
1846 T* GetOrCreateValue() const {
1847 return static_cast<ValueHolder*>(
1848 ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
1849 }
1850
1851 virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
1852 return default_factory_->MakeNewHolder();
1853 }
1854
1855 class ValueHolderFactory {
1856 public:
1857 ValueHolderFactory() {}
1858 virtual ~ValueHolderFactory() {}
1859 virtual ValueHolder* MakeNewHolder() const = 0;
1860
1861 private:
1862 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
1863 };
1864
1865 class DefaultValueHolderFactory : public ValueHolderFactory {
1866 public:
1867 DefaultValueHolderFactory() {}
Austin Schuh3de38b02024-06-25 18:25:10 -07001868 ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
Austin Schuh70cc9552019-01-21 19:46:48 -08001869
1870 private:
1871 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
1872 };
1873
1874 class InstanceValueHolderFactory : public ValueHolderFactory {
1875 public:
1876 explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
Austin Schuh3de38b02024-06-25 18:25:10 -07001877 ValueHolder* MakeNewHolder() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08001878 return new ValueHolder(value_);
1879 }
1880
1881 private:
1882 const T value_; // The value for each thread.
1883
1884 GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
1885 };
1886
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001887 std::unique_ptr<ValueHolderFactory> default_factory_;
Austin Schuh70cc9552019-01-21 19:46:48 -08001888
1889 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
1890};
1891
1892# elif GTEST_HAS_PTHREAD
1893
1894// MutexBase and Mutex implement mutex on pthreads-based platforms.
1895class MutexBase {
1896 public:
1897 // Acquires this mutex.
1898 void Lock() {
1899 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
1900 owner_ = pthread_self();
1901 has_owner_ = true;
1902 }
1903
1904 // Releases this mutex.
1905 void Unlock() {
1906 // Since the lock is being released the owner_ field should no longer be
1907 // considered valid. We don't protect writing to has_owner_ here, as it's
1908 // the caller's responsibility to ensure that the current thread holds the
1909 // mutex when this is called.
1910 has_owner_ = false;
1911 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
1912 }
1913
1914 // Does nothing if the current thread holds the mutex. Otherwise, crashes
1915 // with high probability.
1916 void AssertHeld() const {
1917 GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
1918 << "The current thread is not holding the mutex @" << this;
1919 }
1920
1921 // A static mutex may be used before main() is entered. It may even
1922 // be used before the dynamic initialization stage. Therefore we
1923 // must be able to initialize a static mutex object at link time.
1924 // This means MutexBase has to be a POD and its member variables
1925 // have to be public.
1926 public:
1927 pthread_mutex_t mutex_; // The underlying pthread mutex.
1928 // has_owner_ indicates whether the owner_ field below contains a valid thread
1929 // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
1930 // accesses to the owner_ field should be protected by a check of this field.
1931 // An alternative might be to memset() owner_ to all zeros, but there's no
1932 // guarantee that a zero'd pthread_t is necessarily invalid or even different
1933 // from pthread_self().
1934 bool has_owner_;
1935 pthread_t owner_; // The thread holding the mutex.
1936};
1937
1938// Forward-declares a static mutex.
1939# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1940 extern ::testing::internal::MutexBase mutex
1941
1942// Defines and statically (i.e. at link time) initializes a static mutex.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001943// The initialization list here does not explicitly initialize each field,
1944// instead relying on default initialization for the unspecified fields. In
1945// particular, the owner_ field (a pthread_t) is not explicitly initialized.
1946// This allows initialization to work whether pthread_t is a scalar or struct.
1947// The flag -Wmissing-field-initializers must not be specified for this to work.
1948#define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1949 ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0}
Austin Schuh70cc9552019-01-21 19:46:48 -08001950
1951// The Mutex class can only be used for mutexes created at runtime. It
1952// shares its API with MutexBase otherwise.
1953class Mutex : public MutexBase {
1954 public:
1955 Mutex() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08001956 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
Austin Schuh70cc9552019-01-21 19:46:48 -08001957 has_owner_ = false;
1958 }
1959 ~Mutex() {
1960 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
1961 }
1962
1963 private:
1964 GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1965};
1966
1967// We cannot name this class MutexLock because the ctor declaration would
1968// conflict with a macro named MutexLock, which is defined on some
1969// platforms. That macro is used as a defensive measure to prevent against
1970// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1971// "MutexLock l(&mu)". Hence the typedef trick below.
1972class GTestMutexLock {
1973 public:
1974 explicit GTestMutexLock(MutexBase* mutex)
1975 : mutex_(mutex) { mutex_->Lock(); }
1976
1977 ~GTestMutexLock() { mutex_->Unlock(); }
1978
1979 private:
1980 MutexBase* const mutex_;
1981
1982 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1983};
1984
1985typedef GTestMutexLock MutexLock;
1986
1987// Helpers for ThreadLocal.
1988
1989// pthread_key_create() requires DeleteThreadLocalValue() to have
1990// C-linkage. Therefore it cannot be templatized to access
1991// ThreadLocal<T>. Hence the need for class
1992// ThreadLocalValueHolderBase.
1993class ThreadLocalValueHolderBase {
1994 public:
1995 virtual ~ThreadLocalValueHolderBase() {}
1996};
1997
1998// Called by pthread to delete thread-local data stored by
1999// pthread_setspecific().
2000extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
2001 delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
2002}
2003
2004// Implements thread-local storage on pthreads-based systems.
2005template <typename T>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002006class GTEST_API_ ThreadLocal {
Austin Schuh70cc9552019-01-21 19:46:48 -08002007 public:
2008 ThreadLocal()
2009 : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
2010 explicit ThreadLocal(const T& value)
2011 : key_(CreateKey()),
2012 default_factory_(new InstanceValueHolderFactory(value)) {}
2013
2014 ~ThreadLocal() {
2015 // Destroys the managed object for the current thread, if any.
2016 DeleteThreadLocalValue(pthread_getspecific(key_));
2017
2018 // Releases resources associated with the key. This will *not*
2019 // delete managed objects for other threads.
2020 GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
2021 }
2022
2023 T* pointer() { return GetOrCreateValue(); }
2024 const T* pointer() const { return GetOrCreateValue(); }
2025 const T& get() const { return *pointer(); }
2026 void set(const T& value) { *pointer() = value; }
2027
2028 private:
2029 // Holds a value of type T.
2030 class ValueHolder : public ThreadLocalValueHolderBase {
2031 public:
2032 ValueHolder() : value_() {}
2033 explicit ValueHolder(const T& value) : value_(value) {}
2034
2035 T* pointer() { return &value_; }
2036
2037 private:
2038 T value_;
2039 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
2040 };
2041
2042 static pthread_key_t CreateKey() {
2043 pthread_key_t key;
2044 // When a thread exits, DeleteThreadLocalValue() will be called on
2045 // the object managed for that thread.
2046 GTEST_CHECK_POSIX_SUCCESS_(
2047 pthread_key_create(&key, &DeleteThreadLocalValue));
2048 return key;
2049 }
2050
2051 T* GetOrCreateValue() const {
2052 ThreadLocalValueHolderBase* const holder =
2053 static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002054 if (holder != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08002055 return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
2056 }
2057
2058 ValueHolder* const new_holder = default_factory_->MakeNewHolder();
2059 ThreadLocalValueHolderBase* const holder_base = new_holder;
2060 GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
2061 return new_holder->pointer();
2062 }
2063
2064 class ValueHolderFactory {
2065 public:
2066 ValueHolderFactory() {}
2067 virtual ~ValueHolderFactory() {}
2068 virtual ValueHolder* MakeNewHolder() const = 0;
2069
2070 private:
2071 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
2072 };
2073
2074 class DefaultValueHolderFactory : public ValueHolderFactory {
2075 public:
2076 DefaultValueHolderFactory() {}
Austin Schuh3de38b02024-06-25 18:25:10 -07002077 ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
Austin Schuh70cc9552019-01-21 19:46:48 -08002078
2079 private:
2080 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
2081 };
2082
2083 class InstanceValueHolderFactory : public ValueHolderFactory {
2084 public:
2085 explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
Austin Schuh3de38b02024-06-25 18:25:10 -07002086 ValueHolder* MakeNewHolder() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08002087 return new ValueHolder(value_);
2088 }
2089
2090 private:
2091 const T value_; // The value for each thread.
2092
2093 GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
2094 };
2095
2096 // A key pthreads uses for looking up per-thread values.
2097 const pthread_key_t key_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002098 std::unique_ptr<ValueHolderFactory> default_factory_;
Austin Schuh70cc9552019-01-21 19:46:48 -08002099
2100 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
2101};
2102
2103# endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
2104
2105#else // GTEST_IS_THREADSAFE
2106
2107// A dummy implementation of synchronization primitives (mutex, lock,
2108// and thread-local variable). Necessary for compiling Google Test where
2109// mutex is not supported - using Google Test in multiple threads is not
2110// supported on such platforms.
2111
2112class Mutex {
2113 public:
2114 Mutex() {}
2115 void Lock() {}
2116 void Unlock() {}
2117 void AssertHeld() const {}
2118};
2119
2120# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
2121 extern ::testing::internal::Mutex mutex
2122
2123# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
2124
2125// We cannot name this class MutexLock because the ctor declaration would
2126// conflict with a macro named MutexLock, which is defined on some
2127// platforms. That macro is used as a defensive measure to prevent against
2128// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
2129// "MutexLock l(&mu)". Hence the typedef trick below.
2130class GTestMutexLock {
2131 public:
2132 explicit GTestMutexLock(Mutex*) {} // NOLINT
2133};
2134
2135typedef GTestMutexLock MutexLock;
2136
2137template <typename T>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002138class GTEST_API_ ThreadLocal {
Austin Schuh70cc9552019-01-21 19:46:48 -08002139 public:
2140 ThreadLocal() : value_() {}
2141 explicit ThreadLocal(const T& value) : value_(value) {}
2142 T* pointer() { return &value_; }
2143 const T* pointer() const { return &value_; }
2144 const T& get() const { return value_; }
2145 void set(const T& value) { value_ = value; }
2146 private:
2147 T value_;
2148};
2149
2150#endif // GTEST_IS_THREADSAFE
2151
2152// Returns the number of threads running in the process, or 0 to indicate that
2153// we cannot detect it.
2154GTEST_API_ size_t GetThreadCount();
2155
Austin Schuh70cc9552019-01-21 19:46:48 -08002156#if GTEST_OS_WINDOWS
2157# define GTEST_PATH_SEP_ "\\"
2158# define GTEST_HAS_ALT_PATH_SEP_ 1
Austin Schuh70cc9552019-01-21 19:46:48 -08002159#else
2160# define GTEST_PATH_SEP_ "/"
2161# define GTEST_HAS_ALT_PATH_SEP_ 0
Austin Schuh70cc9552019-01-21 19:46:48 -08002162#endif // GTEST_OS_WINDOWS
2163
2164// Utilities for char.
2165
2166// isspace(int ch) and friends accept an unsigned char or EOF. char
2167// may be signed, depending on the compiler (or compiler flags).
2168// Therefore we need to cast a char to unsigned char before calling
2169// isspace(), etc.
2170
2171inline bool IsAlpha(char ch) {
2172 return isalpha(static_cast<unsigned char>(ch)) != 0;
2173}
2174inline bool IsAlNum(char ch) {
2175 return isalnum(static_cast<unsigned char>(ch)) != 0;
2176}
2177inline bool IsDigit(char ch) {
2178 return isdigit(static_cast<unsigned char>(ch)) != 0;
2179}
2180inline bool IsLower(char ch) {
2181 return islower(static_cast<unsigned char>(ch)) != 0;
2182}
2183inline bool IsSpace(char ch) {
2184 return isspace(static_cast<unsigned char>(ch)) != 0;
2185}
2186inline bool IsUpper(char ch) {
2187 return isupper(static_cast<unsigned char>(ch)) != 0;
2188}
2189inline bool IsXDigit(char ch) {
2190 return isxdigit(static_cast<unsigned char>(ch)) != 0;
2191}
Austin Schuh3de38b02024-06-25 18:25:10 -07002192#ifdef __cpp_char8_t
2193inline bool IsXDigit(char8_t ch) {
2194 return isxdigit(static_cast<unsigned char>(ch)) != 0;
2195}
2196#endif
2197inline bool IsXDigit(char16_t ch) {
2198 const unsigned char low_byte = static_cast<unsigned char>(ch);
2199 return ch == low_byte && isxdigit(low_byte) != 0;
2200}
2201inline bool IsXDigit(char32_t ch) {
2202 const unsigned char low_byte = static_cast<unsigned char>(ch);
2203 return ch == low_byte && isxdigit(low_byte) != 0;
2204}
Austin Schuh70cc9552019-01-21 19:46:48 -08002205inline bool IsXDigit(wchar_t ch) {
2206 const unsigned char low_byte = static_cast<unsigned char>(ch);
2207 return ch == low_byte && isxdigit(low_byte) != 0;
2208}
2209
2210inline char ToLower(char ch) {
2211 return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
2212}
2213inline char ToUpper(char ch) {
2214 return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
2215}
2216
2217inline std::string StripTrailingSpaces(std::string str) {
2218 std::string::iterator it = str.end();
2219 while (it != str.begin() && IsSpace(*--it))
2220 it = str.erase(it);
2221 return str;
2222}
2223
2224// The testing::internal::posix namespace holds wrappers for common
2225// POSIX functions. These wrappers hide the differences between
2226// Windows/MSVC and POSIX systems. Since some compilers define these
2227// standard functions as macros, the wrapper cannot have the same name
2228// as the wrapped function.
2229
2230namespace posix {
2231
2232// Functions with a different name on Windows.
2233
2234#if GTEST_OS_WINDOWS
2235
2236typedef struct _stat StatStruct;
2237
2238# ifdef __BORLANDC__
Austin Schuh3de38b02024-06-25 18:25:10 -07002239inline int DoIsATTY(int fd) { return isatty(fd); }
Austin Schuh70cc9552019-01-21 19:46:48 -08002240inline int StrCaseCmp(const char* s1, const char* s2) {
2241 return stricmp(s1, s2);
2242}
2243inline char* StrDup(const char* src) { return strdup(src); }
2244# else // !__BORLANDC__
2245# if GTEST_OS_WINDOWS_MOBILE
Austin Schuh3de38b02024-06-25 18:25:10 -07002246inline int DoIsATTY(int /* fd */) { return 0; }
Austin Schuh70cc9552019-01-21 19:46:48 -08002247# else
Austin Schuh3de38b02024-06-25 18:25:10 -07002248inline int DoIsATTY(int fd) { return _isatty(fd); }
Austin Schuh70cc9552019-01-21 19:46:48 -08002249# endif // GTEST_OS_WINDOWS_MOBILE
2250inline int StrCaseCmp(const char* s1, const char* s2) {
2251 return _stricmp(s1, s2);
2252}
2253inline char* StrDup(const char* src) { return _strdup(src); }
2254# endif // __BORLANDC__
2255
2256# if GTEST_OS_WINDOWS_MOBILE
2257inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
2258// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
2259// time and thus not defined there.
2260# else
2261inline int FileNo(FILE* file) { return _fileno(file); }
2262inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
2263inline int RmDir(const char* dir) { return _rmdir(dir); }
2264inline bool IsDir(const StatStruct& st) {
2265 return (_S_IFDIR & st.st_mode) != 0;
2266}
2267# endif // GTEST_OS_WINDOWS_MOBILE
2268
Austin Schuh3de38b02024-06-25 18:25:10 -07002269#elif GTEST_OS_ESP8266
2270typedef struct stat StatStruct;
2271
2272inline int FileNo(FILE* file) { return fileno(file); }
2273inline int DoIsATTY(int fd) { return isatty(fd); }
2274inline int Stat(const char* path, StatStruct* buf) {
2275 // stat function not implemented on ESP8266
2276 return 0;
2277}
2278inline int StrCaseCmp(const char* s1, const char* s2) {
2279 return strcasecmp(s1, s2);
2280}
2281inline char* StrDup(const char* src) { return strdup(src); }
2282inline int RmDir(const char* dir) { return rmdir(dir); }
2283inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2284
Austin Schuh70cc9552019-01-21 19:46:48 -08002285#else
2286
2287typedef struct stat StatStruct;
2288
2289inline int FileNo(FILE* file) { return fileno(file); }
Austin Schuh3de38b02024-06-25 18:25:10 -07002290inline int DoIsATTY(int fd) { return isatty(fd); }
Austin Schuh70cc9552019-01-21 19:46:48 -08002291inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
2292inline int StrCaseCmp(const char* s1, const char* s2) {
2293 return strcasecmp(s1, s2);
2294}
2295inline char* StrDup(const char* src) { return strdup(src); }
2296inline int RmDir(const char* dir) { return rmdir(dir); }
2297inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2298
2299#endif // GTEST_OS_WINDOWS
2300
Austin Schuh3de38b02024-06-25 18:25:10 -07002301inline int IsATTY(int fd) {
2302 // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout
2303 // to a file on Linux), which is unexpected, so save the previous value, and
2304 // restore it after the call.
2305 int savedErrno = errno;
2306 int isAttyValue = DoIsATTY(fd);
2307 errno = savedErrno;
2308
2309 return isAttyValue;
2310}
2311
Austin Schuh70cc9552019-01-21 19:46:48 -08002312// Functions deprecated by MSVC 8.0.
2313
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002314GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
Austin Schuh70cc9552019-01-21 19:46:48 -08002315
Austin Schuh70cc9552019-01-21 19:46:48 -08002316// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
2317// StrError() aren't needed on Windows CE at this time and thus not
2318// defined there.
2319
Austin Schuh3de38b02024-06-25 18:25:10 -07002320#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
2321 !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !GTEST_OS_XTENSA
Austin Schuh70cc9552019-01-21 19:46:48 -08002322inline int ChDir(const char* dir) { return chdir(dir); }
2323#endif
2324inline FILE* FOpen(const char* path, const char* mode) {
Austin Schuh3de38b02024-06-25 18:25:10 -07002325#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2326 struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
2327 std::wstring_convert<wchar_codecvt> converter;
2328 std::wstring wide_path = converter.from_bytes(path);
2329 std::wstring wide_mode = converter.from_bytes(mode);
2330 return _wfopen(wide_path.c_str(), wide_mode.c_str());
2331#else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
Austin Schuh70cc9552019-01-21 19:46:48 -08002332 return fopen(path, mode);
Austin Schuh3de38b02024-06-25 18:25:10 -07002333#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
Austin Schuh70cc9552019-01-21 19:46:48 -08002334}
2335#if !GTEST_OS_WINDOWS_MOBILE
2336inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
2337 return freopen(path, mode, stream);
2338}
2339inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
2340#endif
2341inline int FClose(FILE* fp) { return fclose(fp); }
2342#if !GTEST_OS_WINDOWS_MOBILE
2343inline int Read(int fd, void* buf, unsigned int count) {
2344 return static_cast<int>(read(fd, buf, count));
2345}
2346inline int Write(int fd, const void* buf, unsigned int count) {
2347 return static_cast<int>(write(fd, buf, count));
2348}
2349inline int Close(int fd) { return close(fd); }
2350inline const char* StrError(int errnum) { return strerror(errnum); }
2351#endif
2352inline const char* GetEnv(const char* name) {
Austin Schuh3de38b02024-06-25 18:25:10 -07002353#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
2354 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
2355 // We are on an embedded platform, which has no environment variables.
Austin Schuh70cc9552019-01-21 19:46:48 -08002356 static_cast<void>(name); // To prevent 'unused argument' warning.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002357 return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08002358#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
2359 // Environment variables which we programmatically clear will be set to the
2360 // empty string rather than unset (NULL). Handle that case.
2361 const char* const env = getenv(name);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002362 return (env != nullptr && env[0] != '\0') ? env : nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08002363#else
2364 return getenv(name);
2365#endif
2366}
2367
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002368GTEST_DISABLE_MSC_DEPRECATED_POP_()
Austin Schuh70cc9552019-01-21 19:46:48 -08002369
2370#if GTEST_OS_WINDOWS_MOBILE
2371// Windows CE has no C library. The abort() function is used in
2372// several places in Google Test. This implementation provides a reasonable
2373// imitation of standard behaviour.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002374[[noreturn]] void Abort();
Austin Schuh70cc9552019-01-21 19:46:48 -08002375#else
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002376[[noreturn]] inline void Abort() { abort(); }
Austin Schuh70cc9552019-01-21 19:46:48 -08002377#endif // GTEST_OS_WINDOWS_MOBILE
2378
2379} // namespace posix
2380
2381// MSVC "deprecates" snprintf and issues warnings wherever it is used. In
2382// order to avoid these warnings, we need to use _snprintf or _snprintf_s on
2383// MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate
2384// function in order to achieve that. We use macro definition here because
2385// snprintf is a variadic function.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002386#if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE
Austin Schuh70cc9552019-01-21 19:46:48 -08002387// MSVC 2005 and above support variadic macros.
2388# define GTEST_SNPRINTF_(buffer, size, format, ...) \
2389 _snprintf_s(buffer, size, size, format, __VA_ARGS__)
2390#elif defined(_MSC_VER)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002391// Windows CE does not define _snprintf_s
Austin Schuh70cc9552019-01-21 19:46:48 -08002392# define GTEST_SNPRINTF_ _snprintf
2393#else
2394# define GTEST_SNPRINTF_ snprintf
2395#endif
2396
Austin Schuh3de38b02024-06-25 18:25:10 -07002397// The biggest signed integer type the compiler supports.
Austin Schuh70cc9552019-01-21 19:46:48 -08002398//
Austin Schuh3de38b02024-06-25 18:25:10 -07002399// long long is guaranteed to be at least 64-bits in C++11.
2400using BiggestInt = long long; // NOLINT
2401
2402// The maximum number a BiggestInt can represent.
2403constexpr BiggestInt kMaxBiggestInt = (std::numeric_limits<BiggestInt>::max)();
Austin Schuh70cc9552019-01-21 19:46:48 -08002404
2405// This template class serves as a compile-time function from size to
2406// type. It maps a size in bytes to a primitive type with that
2407// size. e.g.
2408//
2409// TypeWithSize<4>::UInt
2410//
2411// is typedef-ed to be unsigned int (unsigned integer made up of 4
2412// bytes).
2413//
2414// Such functionality should belong to STL, but I cannot find it
2415// there.
2416//
2417// Google Test uses this class in the implementation of floating-point
2418// comparison.
2419//
2420// For now it only handles UInt (unsigned int) as that's all Google Test
2421// needs. Other types can be easily added in the future if need
2422// arises.
2423template <size_t size>
2424class TypeWithSize {
2425 public:
2426 // This prevents the user from using TypeWithSize<N> with incorrect
2427 // values of N.
Austin Schuh3de38b02024-06-25 18:25:10 -07002428 using UInt = void;
Austin Schuh70cc9552019-01-21 19:46:48 -08002429};
2430
2431// The specialization for size 4.
2432template <>
2433class TypeWithSize<4> {
2434 public:
Austin Schuh3de38b02024-06-25 18:25:10 -07002435 using Int = std::int32_t;
2436 using UInt = std::uint32_t;
Austin Schuh70cc9552019-01-21 19:46:48 -08002437};
2438
2439// The specialization for size 8.
2440template <>
2441class TypeWithSize<8> {
2442 public:
Austin Schuh3de38b02024-06-25 18:25:10 -07002443 using Int = std::int64_t;
2444 using UInt = std::uint64_t;
Austin Schuh70cc9552019-01-21 19:46:48 -08002445};
2446
2447// Integer types of known sizes.
Austin Schuh3de38b02024-06-25 18:25:10 -07002448using TimeInMillis = int64_t; // Represents time in milliseconds.
Austin Schuh70cc9552019-01-21 19:46:48 -08002449
2450// Utilities for command line flags and environment variables.
2451
2452// Macro for referencing flags.
2453#if !defined(GTEST_FLAG)
2454# define GTEST_FLAG(name) FLAGS_gtest_##name
2455#endif // !defined(GTEST_FLAG)
2456
2457#if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2458# define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
2459#endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2460
2461#if !defined(GTEST_DECLARE_bool_)
2462# define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
2463
2464// Macros for declaring flags.
2465# define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
2466# define GTEST_DECLARE_int32_(name) \
Austin Schuh3de38b02024-06-25 18:25:10 -07002467 GTEST_API_ extern std::int32_t GTEST_FLAG(name)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002468# define GTEST_DECLARE_string_(name) \
Austin Schuh70cc9552019-01-21 19:46:48 -08002469 GTEST_API_ extern ::std::string GTEST_FLAG(name)
2470
2471// Macros for defining flags.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002472# define GTEST_DEFINE_bool_(name, default_val, doc) \
Austin Schuh70cc9552019-01-21 19:46:48 -08002473 GTEST_API_ bool GTEST_FLAG(name) = (default_val)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002474# define GTEST_DEFINE_int32_(name, default_val, doc) \
Austin Schuh3de38b02024-06-25 18:25:10 -07002475 GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002476# define GTEST_DEFINE_string_(name, default_val, doc) \
Austin Schuh70cc9552019-01-21 19:46:48 -08002477 GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
2478
2479#endif // !defined(GTEST_DECLARE_bool_)
2480
2481// Thread annotations
2482#if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2483# define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
2484# define GTEST_LOCK_EXCLUDED_(locks)
2485#endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2486
2487// Parses 'str' for a 32-bit signed integer. If successful, writes the result
2488// to *value and returns true; otherwise leaves *value unchanged and returns
2489// false.
Austin Schuh3de38b02024-06-25 18:25:10 -07002490GTEST_API_ bool ParseInt32(const Message& src_text, const char* str,
2491 int32_t* value);
Austin Schuh70cc9552019-01-21 19:46:48 -08002492
Austin Schuh3de38b02024-06-25 18:25:10 -07002493// Parses a bool/int32_t/string from the environment variable
Austin Schuh70cc9552019-01-21 19:46:48 -08002494// corresponding to the given Google Test flag.
2495bool BoolFromGTestEnv(const char* flag, bool default_val);
Austin Schuh3de38b02024-06-25 18:25:10 -07002496GTEST_API_ int32_t Int32FromGTestEnv(const char* flag, int32_t default_val);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002497std::string OutputFlagAlsoCheckEnvVar();
2498const char* StringFromGTestEnv(const char* flag, const char* default_val);
Austin Schuh70cc9552019-01-21 19:46:48 -08002499
2500} // namespace internal
2501} // namespace testing
2502
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002503#if !defined(GTEST_INTERNAL_DEPRECATED)
2504
2505// Internal Macro to mark an API deprecated, for googletest usage only
2506// Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or
2507// GTEST_INTERNAL_DEPRECATED(message) <return_type> myFunction(); Every usage of
2508// a deprecated entity will trigger a warning when compiled with
2509// `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler).
2510// For msvc /W3 option will need to be used
2511// Note that for 'other' compilers this macro evaluates to nothing to prevent
2512// compilations errors.
2513#if defined(_MSC_VER)
2514#define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message))
2515#elif defined(__GNUC__)
2516#define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message)))
2517#else
2518#define GTEST_INTERNAL_DEPRECATED(message)
2519#endif
2520
2521#endif // !defined(GTEST_INTERNAL_DEPRECATED)
2522
Austin Schuh3de38b02024-06-25 18:25:10 -07002523#if GTEST_HAS_ABSL
2524// Always use absl::any for UniversalPrinter<> specializations if googletest
2525// is built with absl support.
2526#define GTEST_INTERNAL_HAS_ANY 1
2527#include "absl/types/any.h"
2528namespace testing {
2529namespace internal {
2530using Any = ::absl::any;
2531} // namespace internal
2532} // namespace testing
2533#else
2534#ifdef __has_include
2535#if __has_include(<any>) && __cplusplus >= 201703L
2536// Otherwise for C++17 and higher use std::any for UniversalPrinter<>
2537// specializations.
2538#define GTEST_INTERNAL_HAS_ANY 1
2539#include <any>
2540namespace testing {
2541namespace internal {
2542using Any = ::std::any;
2543} // namespace internal
2544} // namespace testing
2545// The case where absl is configured NOT to alias std::any is not
2546// supported.
2547#endif // __has_include(<any>) && __cplusplus >= 201703L
2548#endif // __has_include
2549#endif // GTEST_HAS_ABSL
2550
2551#if GTEST_HAS_ABSL
2552// Always use absl::optional for UniversalPrinter<> specializations if
2553// googletest is built with absl support.
2554#define GTEST_INTERNAL_HAS_OPTIONAL 1
2555#include "absl/types/optional.h"
2556namespace testing {
2557namespace internal {
2558template <typename T>
2559using Optional = ::absl::optional<T>;
2560} // namespace internal
2561} // namespace testing
2562#else
2563#ifdef __has_include
2564#if __has_include(<optional>) && __cplusplus >= 201703L
2565// Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
2566// specializations.
2567#define GTEST_INTERNAL_HAS_OPTIONAL 1
2568#include <optional>
2569namespace testing {
2570namespace internal {
2571template <typename T>
2572using Optional = ::std::optional<T>;
2573} // namespace internal
2574} // namespace testing
2575// The case where absl is configured NOT to alias std::optional is not
2576// supported.
2577#endif // __has_include(<optional>) && __cplusplus >= 201703L
2578#endif // __has_include
2579#endif // GTEST_HAS_ABSL
2580
2581#if GTEST_HAS_ABSL
2582// Always use absl::string_view for Matcher<> specializations if googletest
2583// is built with absl support.
2584# define GTEST_INTERNAL_HAS_STRING_VIEW 1
2585#include "absl/strings/string_view.h"
2586namespace testing {
2587namespace internal {
2588using StringView = ::absl::string_view;
2589} // namespace internal
2590} // namespace testing
2591#else
2592# ifdef __has_include
2593# if __has_include(<string_view>) && __cplusplus >= 201703L
2594// Otherwise for C++17 and higher use std::string_view for Matcher<>
2595// specializations.
2596# define GTEST_INTERNAL_HAS_STRING_VIEW 1
2597#include <string_view>
2598namespace testing {
2599namespace internal {
2600using StringView = ::std::string_view;
2601} // namespace internal
2602} // namespace testing
2603// The case where absl is configured NOT to alias std::string_view is not
2604// supported.
2605# endif // __has_include(<string_view>) && __cplusplus >= 201703L
2606# endif // __has_include
2607#endif // GTEST_HAS_ABSL
2608
2609#if GTEST_HAS_ABSL
2610// Always use absl::variant for UniversalPrinter<> specializations if googletest
2611// is built with absl support.
2612#define GTEST_INTERNAL_HAS_VARIANT 1
2613#include "absl/types/variant.h"
2614namespace testing {
2615namespace internal {
2616template <typename... T>
2617using Variant = ::absl::variant<T...>;
2618} // namespace internal
2619} // namespace testing
2620#else
2621#ifdef __has_include
2622#if __has_include(<variant>) && __cplusplus >= 201703L
2623// Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
2624// specializations.
2625#define GTEST_INTERNAL_HAS_VARIANT 1
2626#include <variant>
2627namespace testing {
2628namespace internal {
2629template <typename... T>
2630using Variant = ::std::variant<T...>;
2631} // namespace internal
2632} // namespace testing
2633// The case where absl is configured NOT to alias std::variant is not supported.
2634#endif // __has_include(<variant>) && __cplusplus >= 201703L
2635#endif // __has_include
2636#endif // GTEST_HAS_ABSL
2637
2638#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08002639
2640#if GTEST_OS_LINUX
2641# include <stdlib.h>
2642# include <sys/types.h>
2643# include <sys/wait.h>
2644# include <unistd.h>
2645#endif // GTEST_OS_LINUX
2646
2647#if GTEST_HAS_EXCEPTIONS
2648# include <stdexcept>
2649#endif
2650
2651#include <ctype.h>
2652#include <float.h>
2653#include <string.h>
Austin Schuh3de38b02024-06-25 18:25:10 -07002654#include <cstdint>
Austin Schuh70cc9552019-01-21 19:46:48 -08002655#include <iomanip>
2656#include <limits>
2657#include <map>
2658#include <set>
2659#include <string>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002660#include <type_traits>
Austin Schuh70cc9552019-01-21 19:46:48 -08002661#include <vector>
2662
2663// Copyright 2005, Google Inc.
2664// All rights reserved.
2665//
2666// Redistribution and use in source and binary forms, with or without
2667// modification, are permitted provided that the following conditions are
2668// met:
2669//
2670// * Redistributions of source code must retain the above copyright
2671// notice, this list of conditions and the following disclaimer.
2672// * Redistributions in binary form must reproduce the above
2673// copyright notice, this list of conditions and the following disclaimer
2674// in the documentation and/or other materials provided with the
2675// distribution.
2676// * Neither the name of Google Inc. nor the names of its
2677// contributors may be used to endorse or promote products derived from
2678// this software without specific prior written permission.
2679//
2680// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2681// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2682// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2683// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2684// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2685// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2686// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2687// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2688// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2689// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2690// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002691
Austin Schuh70cc9552019-01-21 19:46:48 -08002692//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002693// The Google C++ Testing and Mocking Framework (Google Test)
Austin Schuh70cc9552019-01-21 19:46:48 -08002694//
2695// This header file defines the Message class.
2696//
2697// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
2698// leave some internal implementation details in this header file.
2699// They are clearly marked by comments like this:
2700//
2701// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2702//
2703// Such code is NOT meant to be used by a user directly, and is subject
2704// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
2705// program!
2706
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002707// GOOGLETEST_CM0001 DO NOT DELETE
2708
Austin Schuh3de38b02024-06-25 18:25:10 -07002709#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
2710#define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08002711
2712#include <limits>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002713#include <memory>
Austin Schuh3de38b02024-06-25 18:25:10 -07002714#include <sstream>
Austin Schuh70cc9552019-01-21 19:46:48 -08002715
2716
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002717GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
2718/* class A needs to have dll-interface to be used by clients of class B */)
2719
Austin Schuh70cc9552019-01-21 19:46:48 -08002720// Ensures that there is at least one operator<< in the global namespace.
2721// See Message& operator<<(...) below for why.
2722void operator<<(const testing::internal::Secret&, int);
2723
2724namespace testing {
2725
2726// The Message class works like an ostream repeater.
2727//
2728// Typical usage:
2729//
2730// 1. You stream a bunch of values to a Message object.
2731// It will remember the text in a stringstream.
2732// 2. Then you stream the Message object to an ostream.
2733// This causes the text in the Message to be streamed
2734// to the ostream.
2735//
2736// For example;
2737//
2738// testing::Message foo;
2739// foo << 1 << " != " << 2;
2740// std::cout << foo;
2741//
2742// will print "1 != 2".
2743//
2744// Message is not intended to be inherited from. In particular, its
2745// destructor is not virtual.
2746//
2747// Note that stringstream behaves differently in gcc and in MSVC. You
2748// can stream a NULL char pointer to it in the former, but not in the
2749// latter (it causes an access violation if you do). The Message
2750// class hides this difference by treating a NULL char pointer as
2751// "(null)".
2752class GTEST_API_ Message {
2753 private:
2754 // The type of basic IO manipulators (endl, ends, and flush) for
2755 // narrow streams.
2756 typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
2757
2758 public:
2759 // Constructs an empty Message.
2760 Message();
2761
2762 // Copy constructor.
2763 Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT
2764 *ss_ << msg.GetString();
2765 }
2766
2767 // Constructs a Message from a C-string.
2768 explicit Message(const char* str) : ss_(new ::std::stringstream) {
2769 *ss_ << str;
2770 }
2771
Austin Schuh70cc9552019-01-21 19:46:48 -08002772 // Streams a non-pointer value to this object.
2773 template <typename T>
2774 inline Message& operator <<(const T& val) {
2775 // Some libraries overload << for STL containers. These
2776 // overloads are defined in the global namespace instead of ::std.
2777 //
2778 // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
2779 // overloads are visible in either the std namespace or the global
2780 // namespace, but not other namespaces, including the testing
2781 // namespace which Google Test's Message class is in.
2782 //
2783 // To allow STL containers (and other types that has a << operator
2784 // defined in the global namespace) to be used in Google Test
2785 // assertions, testing::Message must access the custom << operator
2786 // from the global namespace. With this using declaration,
2787 // overloads of << defined in the global namespace and those
2788 // visible via Koenig lookup are both exposed in this function.
2789 using ::operator <<;
2790 *ss_ << val;
2791 return *this;
2792 }
2793
2794 // Streams a pointer value to this object.
2795 //
2796 // This function is an overload of the previous one. When you
2797 // stream a pointer to a Message, this definition will be used as it
2798 // is more specialized. (The C++ Standard, section
2799 // [temp.func.order].) If you stream a non-pointer, then the
2800 // previous definition will be used.
2801 //
2802 // The reason for this overload is that streaming a NULL pointer to
2803 // ostream is undefined behavior. Depending on the compiler, you
2804 // may get "0", "(nil)", "(null)", or an access violation. To
2805 // ensure consistent result across compilers, we always treat NULL
2806 // as "(null)".
2807 template <typename T>
2808 inline Message& operator <<(T* const& pointer) { // NOLINT
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002809 if (pointer == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08002810 *ss_ << "(null)";
2811 } else {
2812 *ss_ << pointer;
2813 }
2814 return *this;
2815 }
Austin Schuh70cc9552019-01-21 19:46:48 -08002816
2817 // Since the basic IO manipulators are overloaded for both narrow
2818 // and wide streams, we have to provide this specialized definition
2819 // of operator <<, even though its body is the same as the
2820 // templatized version above. Without this definition, streaming
2821 // endl or other basic IO manipulators to Message will confuse the
2822 // compiler.
2823 Message& operator <<(BasicNarrowIoManip val) {
2824 *ss_ << val;
2825 return *this;
2826 }
2827
2828 // Instead of 1/0, we want to see true/false for bool values.
2829 Message& operator <<(bool b) {
2830 return *this << (b ? "true" : "false");
2831 }
2832
2833 // These two overloads allow streaming a wide C string to a Message
2834 // using the UTF-8 encoding.
2835 Message& operator <<(const wchar_t* wide_c_str);
2836 Message& operator <<(wchar_t* wide_c_str);
2837
2838#if GTEST_HAS_STD_WSTRING
2839 // Converts the given wide string to a narrow string using the UTF-8
2840 // encoding, and streams the result to this Message object.
2841 Message& operator <<(const ::std::wstring& wstr);
2842#endif // GTEST_HAS_STD_WSTRING
2843
Austin Schuh70cc9552019-01-21 19:46:48 -08002844 // Gets the text streamed to this object so far as an std::string.
2845 // Each '\0' character in the buffer is replaced with "\\0".
2846 //
2847 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2848 std::string GetString() const;
2849
2850 private:
Austin Schuh70cc9552019-01-21 19:46:48 -08002851 // We'll hold the text streamed to this object here.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002852 const std::unique_ptr< ::std::stringstream> ss_;
Austin Schuh70cc9552019-01-21 19:46:48 -08002853
2854 // We declare (but don't implement) this to prevent the compiler
2855 // from implementing the assignment operator.
2856 void operator=(const Message&);
2857};
2858
2859// Streams a Message to an ostream.
2860inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
2861 return os << sb.GetString();
2862}
2863
2864namespace internal {
2865
2866// Converts a streamable value to an std::string. A NULL pointer is
2867// converted to "(null)". When the input value is a ::string,
2868// ::std::string, ::wstring, or ::std::wstring object, each NUL
2869// character in it is replaced with "\\0".
2870template <typename T>
2871std::string StreamableToString(const T& streamable) {
2872 return (Message() << streamable).GetString();
2873}
2874
2875} // namespace internal
2876} // namespace testing
2877
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002878GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
2879
Austin Schuh3de38b02024-06-25 18:25:10 -07002880#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002881// Copyright 2008, Google Inc.
2882// All rights reserved.
2883//
2884// Redistribution and use in source and binary forms, with or without
2885// modification, are permitted provided that the following conditions are
2886// met:
2887//
2888// * Redistributions of source code must retain the above copyright
2889// notice, this list of conditions and the following disclaimer.
2890// * Redistributions in binary form must reproduce the above
2891// copyright notice, this list of conditions and the following disclaimer
2892// in the documentation and/or other materials provided with the
2893// distribution.
2894// * Neither the name of Google Inc. nor the names of its
2895// contributors may be used to endorse or promote products derived from
2896// this software without specific prior written permission.
2897//
2898// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2899// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2900// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2901// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2902// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2903// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2904// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2905// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2906// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2907// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2908// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2909//
2910// Google Test filepath utilities
2911//
2912// This header file declares classes and functions used internally by
2913// Google Test. They are subject to change without notice.
2914//
2915// This file is #included in gtest/internal/gtest-internal.h.
2916// Do not include this header file separately!
2917
2918// GOOGLETEST_CM0001 DO NOT DELETE
2919
Austin Schuh3de38b02024-06-25 18:25:10 -07002920#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
2921#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002922
Austin Schuh70cc9552019-01-21 19:46:48 -08002923// Copyright 2005, Google Inc.
2924// All rights reserved.
2925//
2926// Redistribution and use in source and binary forms, with or without
2927// modification, are permitted provided that the following conditions are
2928// met:
2929//
2930// * Redistributions of source code must retain the above copyright
2931// notice, this list of conditions and the following disclaimer.
2932// * Redistributions in binary form must reproduce the above
2933// copyright notice, this list of conditions and the following disclaimer
2934// in the documentation and/or other materials provided with the
2935// distribution.
2936// * Neither the name of Google Inc. nor the names of its
2937// contributors may be used to endorse or promote products derived from
2938// this software without specific prior written permission.
2939//
2940// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2941// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2942// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2943// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2944// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2945// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2946// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2947// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2948// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2949// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2950// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2951//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002952// The Google C++ Testing and Mocking Framework (Google Test)
Austin Schuh70cc9552019-01-21 19:46:48 -08002953//
2954// This header file declares the String class and functions used internally by
2955// Google Test. They are subject to change without notice. They should not used
2956// by code external to Google Test.
2957//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002958// This header file is #included by gtest-internal.h.
Austin Schuh70cc9552019-01-21 19:46:48 -08002959// It should not be #included by other files.
2960
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08002961// GOOGLETEST_CM0001 DO NOT DELETE
2962
Austin Schuh3de38b02024-06-25 18:25:10 -07002963#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
2964#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08002965
2966#ifdef __BORLANDC__
2967// string.h is not guaranteed to provide strcpy on C++ Builder.
2968# include <mem.h>
2969#endif
2970
2971#include <string.h>
Austin Schuh3de38b02024-06-25 18:25:10 -07002972#include <cstdint>
Austin Schuh70cc9552019-01-21 19:46:48 -08002973#include <string>
2974
2975
2976namespace testing {
2977namespace internal {
2978
2979// String - an abstract class holding static string utilities.
2980class GTEST_API_ String {
2981 public:
2982 // Static utility methods
2983
2984 // Clones a 0-terminated C string, allocating memory using new. The
2985 // caller is responsible for deleting the return value using
2986 // delete[]. Returns the cloned string, or NULL if the input is
2987 // NULL.
2988 //
2989 // This is different from strdup() in string.h, which allocates
2990 // memory using malloc().
2991 static const char* CloneCString(const char* c_str);
2992
2993#if GTEST_OS_WINDOWS_MOBILE
2994 // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
2995 // able to pass strings to Win32 APIs on CE we need to convert them
2996 // to 'Unicode', UTF-16.
2997
2998 // Creates a UTF-16 wide string from the given ANSI string, allocating
2999 // memory using new. The caller is responsible for deleting the return
3000 // value using delete[]. Returns the wide string, or NULL if the
3001 // input is NULL.
3002 //
3003 // The wide string is created using the ANSI codepage (CP_ACP) to
3004 // match the behaviour of the ANSI versions of Win32 calls and the
3005 // C runtime.
3006 static LPCWSTR AnsiToUtf16(const char* c_str);
3007
3008 // Creates an ANSI string from the given wide string, allocating
3009 // memory using new. The caller is responsible for deleting the return
3010 // value using delete[]. Returns the ANSI string, or NULL if the
3011 // input is NULL.
3012 //
3013 // The returned string is created using the ANSI codepage (CP_ACP) to
3014 // match the behaviour of the ANSI versions of Win32 calls and the
3015 // C runtime.
3016 static const char* Utf16ToAnsi(LPCWSTR utf16_str);
3017#endif
3018
Austin Schuh3de38b02024-06-25 18:25:10 -07003019 // Compares two C strings. Returns true if and only if they have the same
3020 // content.
Austin Schuh70cc9552019-01-21 19:46:48 -08003021 //
3022 // Unlike strcmp(), this function can handle NULL argument(s). A
3023 // NULL C string is considered different to any non-NULL C string,
3024 // including the empty string.
3025 static bool CStringEquals(const char* lhs, const char* rhs);
3026
3027 // Converts a wide C string to a String using the UTF-8 encoding.
3028 // NULL will be converted to "(null)". If an error occurred during
3029 // the conversion, "(failed to convert from wide string)" is
3030 // returned.
3031 static std::string ShowWideCString(const wchar_t* wide_c_str);
3032
Austin Schuh3de38b02024-06-25 18:25:10 -07003033 // Compares two wide C strings. Returns true if and only if they have the
3034 // same content.
Austin Schuh70cc9552019-01-21 19:46:48 -08003035 //
3036 // Unlike wcscmp(), this function can handle NULL argument(s). A
3037 // NULL C string is considered different to any non-NULL C string,
3038 // including the empty string.
3039 static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
3040
Austin Schuh3de38b02024-06-25 18:25:10 -07003041 // Compares two C strings, ignoring case. Returns true if and only if
3042 // they have the same content.
Austin Schuh70cc9552019-01-21 19:46:48 -08003043 //
3044 // Unlike strcasecmp(), this function can handle NULL argument(s).
3045 // A NULL C string is considered different to any non-NULL C string,
3046 // including the empty string.
3047 static bool CaseInsensitiveCStringEquals(const char* lhs,
3048 const char* rhs);
3049
Austin Schuh3de38b02024-06-25 18:25:10 -07003050 // Compares two wide C strings, ignoring case. Returns true if and only if
3051 // they have the same content.
Austin Schuh70cc9552019-01-21 19:46:48 -08003052 //
3053 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3054 // A NULL C string is considered different to any non-NULL wide C string,
3055 // including the empty string.
3056 // NB: The implementations on different platforms slightly differ.
3057 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3058 // environment variable. On GNU platform this method uses wcscasecmp
3059 // which compares according to LC_CTYPE category of the current locale.
3060 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3061 // current locale.
3062 static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3063 const wchar_t* rhs);
3064
Austin Schuh3de38b02024-06-25 18:25:10 -07003065 // Returns true if and only if the given string ends with the given suffix,
3066 // ignoring case. Any string is considered to end with an empty suffix.
Austin Schuh70cc9552019-01-21 19:46:48 -08003067 static bool EndsWithCaseInsensitive(
3068 const std::string& str, const std::string& suffix);
3069
3070 // Formats an int value as "%02d".
3071 static std::string FormatIntWidth2(int value); // "%02d" for width == 2
3072
Austin Schuh3de38b02024-06-25 18:25:10 -07003073 // Formats an int value to given width with leading zeros.
3074 static std::string FormatIntWidthN(int value, int width);
3075
Austin Schuh70cc9552019-01-21 19:46:48 -08003076 // Formats an int value as "%X".
3077 static std::string FormatHexInt(int value);
3078
Austin Schuh3de38b02024-06-25 18:25:10 -07003079 // Formats an int value as "%X".
3080 static std::string FormatHexUInt32(uint32_t value);
3081
Austin Schuh70cc9552019-01-21 19:46:48 -08003082 // Formats a byte as "%02X".
3083 static std::string FormatByte(unsigned char value);
3084
3085 private:
3086 String(); // Not meant to be instantiated.
3087}; // class String
3088
3089// Gets the content of the stringstream's buffer as an std::string. Each '\0'
3090// character in the buffer is replaced with "\\0".
3091GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
3092
3093} // namespace internal
3094} // namespace testing
3095
Austin Schuh3de38b02024-06-25 18:25:10 -07003096#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08003097
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003098GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
3099/* class A needs to have dll-interface to be used by clients of class B */)
Austin Schuh70cc9552019-01-21 19:46:48 -08003100
3101namespace testing {
3102namespace internal {
3103
3104// FilePath - a class for file and directory pathname manipulation which
3105// handles platform-specific conventions (like the pathname separator).
3106// Used for helper functions for naming files in a directory for xml output.
3107// Except for Set methods, all methods are const or static, which provides an
3108// "immutable value object" -- useful for peace of mind.
3109// A FilePath with a value ending in a path separator ("like/this/") represents
3110// a directory, otherwise it is assumed to represent a file. In either case,
3111// it may or may not represent an actual file or directory in the file system.
3112// Names are NOT checked for syntax correctness -- no checking for illegal
3113// characters, malformed paths, etc.
3114
3115class GTEST_API_ FilePath {
3116 public:
3117 FilePath() : pathname_("") { }
3118 FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
3119
3120 explicit FilePath(const std::string& pathname) : pathname_(pathname) {
3121 Normalize();
3122 }
3123
3124 FilePath& operator=(const FilePath& rhs) {
3125 Set(rhs);
3126 return *this;
3127 }
3128
3129 void Set(const FilePath& rhs) {
3130 pathname_ = rhs.pathname_;
3131 }
3132
3133 const std::string& string() const { return pathname_; }
3134 const char* c_str() const { return pathname_.c_str(); }
3135
3136 // Returns the current working directory, or "" if unsuccessful.
3137 static FilePath GetCurrentDir();
3138
3139 // Given directory = "dir", base_name = "test", number = 0,
3140 // extension = "xml", returns "dir/test.xml". If number is greater
3141 // than zero (e.g., 12), returns "dir/test_12.xml".
3142 // On Windows platform, uses \ as the separator rather than /.
3143 static FilePath MakeFileName(const FilePath& directory,
3144 const FilePath& base_name,
3145 int number,
3146 const char* extension);
3147
3148 // Given directory = "dir", relative_path = "test.xml",
3149 // returns "dir/test.xml".
3150 // On Windows, uses \ as the separator rather than /.
3151 static FilePath ConcatPaths(const FilePath& directory,
3152 const FilePath& relative_path);
3153
3154 // Returns a pathname for a file that does not currently exist. The pathname
3155 // will be directory/base_name.extension or
3156 // directory/base_name_<number>.extension if directory/base_name.extension
3157 // already exists. The number will be incremented until a pathname is found
3158 // that does not already exist.
3159 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
3160 // There could be a race condition if two or more processes are calling this
3161 // function at the same time -- they could both pick the same filename.
3162 static FilePath GenerateUniqueFileName(const FilePath& directory,
3163 const FilePath& base_name,
3164 const char* extension);
3165
Austin Schuh3de38b02024-06-25 18:25:10 -07003166 // Returns true if and only if the path is "".
Austin Schuh70cc9552019-01-21 19:46:48 -08003167 bool IsEmpty() const { return pathname_.empty(); }
3168
3169 // If input name has a trailing separator character, removes it and returns
3170 // the name, otherwise return the name string unmodified.
3171 // On Windows platform, uses \ as the separator, other platforms use /.
3172 FilePath RemoveTrailingPathSeparator() const;
3173
3174 // Returns a copy of the FilePath with the directory part removed.
3175 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
3176 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
3177 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
3178 // returns an empty FilePath ("").
3179 // On Windows platform, '\' is the path separator, otherwise it is '/'.
3180 FilePath RemoveDirectoryName() const;
3181
3182 // RemoveFileName returns the directory path with the filename removed.
3183 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
3184 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
3185 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
3186 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
3187 // On Windows platform, '\' is the path separator, otherwise it is '/'.
3188 FilePath RemoveFileName() const;
3189
3190 // Returns a copy of the FilePath with the case-insensitive extension removed.
3191 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
3192 // FilePath("dir/file"). If a case-insensitive extension is not
3193 // found, returns a copy of the original FilePath.
3194 FilePath RemoveExtension(const char* extension) const;
3195
3196 // Creates directories so that path exists. Returns true if successful or if
3197 // the directories already exist; returns false if unable to create
3198 // directories for any reason. Will also return false if the FilePath does
3199 // not represent a directory (that is, it doesn't end with a path separator).
3200 bool CreateDirectoriesRecursively() const;
3201
3202 // Create the directory so that path exists. Returns true if successful or
3203 // if the directory already exists; returns false if unable to create the
3204 // directory for any reason, including if the parent directory does not
3205 // exist. Not named "CreateDirectory" because that's a macro on Windows.
3206 bool CreateFolder() const;
3207
3208 // Returns true if FilePath describes something in the file-system,
3209 // either a file, directory, or whatever, and that something exists.
3210 bool FileOrDirectoryExists() const;
3211
3212 // Returns true if pathname describes a directory in the file-system
3213 // that exists.
3214 bool DirectoryExists() const;
3215
3216 // Returns true if FilePath ends with a path separator, which indicates that
3217 // it is intended to represent a directory. Returns false otherwise.
3218 // This does NOT check that a directory (or file) actually exists.
3219 bool IsDirectory() const;
3220
3221 // Returns true if pathname describes a root directory. (Windows has one
3222 // root directory per disk drive.)
3223 bool IsRootDirectory() const;
3224
3225 // Returns true if pathname describes an absolute path.
3226 bool IsAbsolutePath() const;
3227
3228 private:
3229 // Replaces multiple consecutive separators with a single separator.
3230 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
3231 // redundancies that might be in a pathname involving "." or "..".
3232 //
3233 // A pathname with multiple consecutive separators may occur either through
3234 // user error or as a result of some scripts or APIs that generate a pathname
3235 // with a trailing separator. On other platforms the same API or script
3236 // may NOT generate a pathname with a trailing "/". Then elsewhere that
3237 // pathname may have another "/" and pathname components added to it,
3238 // without checking for the separator already being there.
3239 // The script language and operating system may allow paths like "foo//bar"
3240 // but some of the functions in FilePath will not handle that correctly. In
3241 // particular, RemoveTrailingPathSeparator() only removes one separator, and
3242 // it is called in CreateDirectoriesRecursively() assuming that it will change
3243 // a pathname from directory syntax (trailing separator) to filename syntax.
3244 //
3245 // On Windows this method also replaces the alternate path separator '/' with
3246 // the primary path separator '\\', so that for example "bar\\/\\foo" becomes
3247 // "bar\\foo".
3248
3249 void Normalize();
3250
Austin Schuh3de38b02024-06-25 18:25:10 -07003251 // Returns a pointer to the last occurrence of a valid path separator in
Austin Schuh70cc9552019-01-21 19:46:48 -08003252 // the FilePath. On Windows, for example, both '/' and '\' are valid path
3253 // separators. Returns NULL if no path separator was found.
3254 const char* FindLastPathSeparator() const;
3255
3256 std::string pathname_;
3257}; // class FilePath
3258
3259} // namespace internal
3260} // namespace testing
3261
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003262GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
3263
Austin Schuh3de38b02024-06-25 18:25:10 -07003264#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08003265// Copyright 2008 Google Inc.
3266// All Rights Reserved.
3267//
3268// Redistribution and use in source and binary forms, with or without
3269// modification, are permitted provided that the following conditions are
3270// met:
3271//
3272// * Redistributions of source code must retain the above copyright
3273// notice, this list of conditions and the following disclaimer.
3274// * Redistributions in binary form must reproduce the above
3275// copyright notice, this list of conditions and the following disclaimer
3276// in the documentation and/or other materials provided with the
3277// distribution.
3278// * Neither the name of Google Inc. nor the names of its
3279// contributors may be used to endorse or promote products derived from
3280// this software without specific prior written permission.
3281//
3282// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
3283// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
3284// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
3285// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3286// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3287// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3288// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3289// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3290// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3291// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3292// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh70cc9552019-01-21 19:46:48 -08003293
3294// Type utilities needed for implementing typed and type-parameterized
Austin Schuh3de38b02024-06-25 18:25:10 -07003295// tests.
Austin Schuh70cc9552019-01-21 19:46:48 -08003296
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003297// GOOGLETEST_CM0001 DO NOT DELETE
3298
Austin Schuh3de38b02024-06-25 18:25:10 -07003299#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
3300#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08003301
3302
3303// #ifdef __GNUC__ is too general here. It is possible to use gcc without using
3304// libstdc++ (which is where cxxabi.h comes from).
3305# if GTEST_HAS_CXXABI_H_
3306# include <cxxabi.h>
3307# elif defined(__HP_aCC)
3308# include <acxx_demangle.h>
3309# endif // GTEST_HASH_CXXABI_H_
3310
3311namespace testing {
3312namespace internal {
3313
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003314// Canonicalizes a given name with respect to the Standard C++ Library.
3315// This handles removing the inline namespace within `std` that is
3316// used by various standard libraries (e.g., `std::__1`). Names outside
3317// of namespace std are returned unmodified.
3318inline std::string CanonicalizeForStdLibVersioning(std::string s) {
3319 static const char prefix[] = "std::__";
3320 if (s.compare(0, strlen(prefix), prefix) == 0) {
3321 std::string::size_type end = s.find("::", strlen(prefix));
3322 if (end != s.npos) {
3323 // Erase everything between the initial `std` and the second `::`.
3324 s.erase(strlen("std"), end - strlen("std"));
3325 }
3326 }
3327 return s;
3328}
3329
Austin Schuh3de38b02024-06-25 18:25:10 -07003330#if GTEST_HAS_RTTI
3331// GetTypeName(const std::type_info&) returns a human-readable name of type T.
3332inline std::string GetTypeName(const std::type_info& type) {
3333 const char* const name = type.name();
3334#if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
Austin Schuh70cc9552019-01-21 19:46:48 -08003335 int status = 0;
3336 // gcc's implementation of typeid(T).name() mangles the type name,
3337 // so we have to demangle it.
Austin Schuh3de38b02024-06-25 18:25:10 -07003338#if GTEST_HAS_CXXABI_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08003339 using abi::__cxa_demangle;
Austin Schuh3de38b02024-06-25 18:25:10 -07003340#endif // GTEST_HAS_CXXABI_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003341 char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
Austin Schuh70cc9552019-01-21 19:46:48 -08003342 const std::string name_str(status == 0 ? readable_name : name);
3343 free(readable_name);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003344 return CanonicalizeForStdLibVersioning(name_str);
Austin Schuh3de38b02024-06-25 18:25:10 -07003345#else
Austin Schuh70cc9552019-01-21 19:46:48 -08003346 return name;
Austin Schuh3de38b02024-06-25 18:25:10 -07003347#endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
3348}
3349#endif // GTEST_HAS_RTTI
Austin Schuh70cc9552019-01-21 19:46:48 -08003350
Austin Schuh3de38b02024-06-25 18:25:10 -07003351// GetTypeName<T>() returns a human-readable name of type T if and only if
3352// RTTI is enabled, otherwise it returns a dummy type name.
3353// NB: This function is also used in Google Mock, so don't move it inside of
3354// the typed-test-only section below.
3355template <typename T>
3356std::string GetTypeName() {
3357#if GTEST_HAS_RTTI
3358 return GetTypeName(typeid(T));
3359#else
Austin Schuh70cc9552019-01-21 19:46:48 -08003360 return "<type>";
Austin Schuh3de38b02024-06-25 18:25:10 -07003361#endif // GTEST_HAS_RTTI
Austin Schuh70cc9552019-01-21 19:46:48 -08003362}
3363
Austin Schuh3de38b02024-06-25 18:25:10 -07003364// A unique type indicating an empty node
Austin Schuh70cc9552019-01-21 19:46:48 -08003365struct None {};
3366
Austin Schuh70cc9552019-01-21 19:46:48 -08003367# define GTEST_TEMPLATE_ template <typename T> class
3368
3369// The template "selector" struct TemplateSel<Tmpl> is used to
3370// represent Tmpl, which must be a class template with one type
3371// parameter, as a type. TemplateSel<Tmpl>::Bind<T>::type is defined
3372// as the type Tmpl<T>. This allows us to actually instantiate the
3373// template "selected" by TemplateSel<Tmpl>.
3374//
3375// This trick is necessary for simulating typedef for class templates,
3376// which C++ doesn't support directly.
3377template <GTEST_TEMPLATE_ Tmpl>
3378struct TemplateSel {
3379 template <typename T>
3380 struct Bind {
3381 typedef Tmpl<T> type;
3382 };
3383};
3384
3385# define GTEST_BIND_(TmplSel, T) \
3386 TmplSel::template Bind<T>::type
3387
Austin Schuh3de38b02024-06-25 18:25:10 -07003388template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>
Austin Schuh70cc9552019-01-21 19:46:48 -08003389struct Templates {
Austin Schuh3de38b02024-06-25 18:25:10 -07003390 using Head = TemplateSel<Head_>;
3391 using Tail = Templates<Tail_...>;
Austin Schuh70cc9552019-01-21 19:46:48 -08003392};
3393
Austin Schuh3de38b02024-06-25 18:25:10 -07003394template <GTEST_TEMPLATE_ Head_>
3395struct Templates<Head_> {
3396 using Head = TemplateSel<Head_>;
3397 using Tail = None;
Austin Schuh70cc9552019-01-21 19:46:48 -08003398};
3399
Austin Schuh3de38b02024-06-25 18:25:10 -07003400// Tuple-like type lists
3401template <typename Head_, typename... Tail_>
3402struct Types {
3403 using Head = Head_;
3404 using Tail = Types<Tail_...>;
3405};
Austin Schuh70cc9552019-01-21 19:46:48 -08003406
Austin Schuh3de38b02024-06-25 18:25:10 -07003407template <typename Head_>
3408struct Types<Head_> {
3409 using Head = Head_;
3410 using Tail = None;
3411};
3412
3413// Helper metafunctions to tell apart a single type from types
3414// generated by ::testing::Types
3415template <typename... Ts>
3416struct ProxyTypeList {
3417 using type = Types<Ts...>;
3418};
3419
3420template <typename>
3421struct is_proxy_type_list : std::false_type {};
3422
3423template <typename... Ts>
3424struct is_proxy_type_list<ProxyTypeList<Ts...>> : std::true_type {};
3425
3426// Generator which conditionally creates type lists.
3427// It recognizes if a requested type list should be created
3428// and prevents creating a new type list nested within another one.
Austin Schuh70cc9552019-01-21 19:46:48 -08003429template <typename T>
Austin Schuh3de38b02024-06-25 18:25:10 -07003430struct GenerateTypeList {
3431 private:
3432 using proxy = typename std::conditional<is_proxy_type_list<T>::value, T,
3433 ProxyTypeList<T>>::type;
Austin Schuh70cc9552019-01-21 19:46:48 -08003434
Austin Schuh3de38b02024-06-25 18:25:10 -07003435 public:
3436 using type = typename proxy::type;
Austin Schuh70cc9552019-01-21 19:46:48 -08003437};
3438
Austin Schuh70cc9552019-01-21 19:46:48 -08003439} // namespace internal
Austin Schuh3de38b02024-06-25 18:25:10 -07003440
3441template <typename... Ts>
3442using Types = internal::ProxyTypeList<Ts...>;
3443
Austin Schuh70cc9552019-01-21 19:46:48 -08003444} // namespace testing
3445
Austin Schuh3de38b02024-06-25 18:25:10 -07003446#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08003447
3448// Due to C++ preprocessor weirdness, we need double indirection to
3449// concatenate two tokens when one of them is __LINE__. Writing
3450//
3451// foo ## __LINE__
3452//
3453// will result in the token foo__LINE__, instead of foo followed by
3454// the current line number. For more details, see
3455// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
3456#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
3457#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
3458
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003459// Stringifies its argument.
Austin Schuh3de38b02024-06-25 18:25:10 -07003460// Work around a bug in visual studio which doesn't accept code like this:
3461//
3462// #define GTEST_STRINGIFY_(name) #name
3463// #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
3464// MACRO(, x, y)
3465//
3466// Complaining about the argument to GTEST_STRINGIFY_ being empty.
3467// This is allowed by the spec.
3468#define GTEST_STRINGIFY_HELPER_(name, ...) #name
3469#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003470
Austin Schuh3de38b02024-06-25 18:25:10 -07003471namespace proto2 {
3472class MessageLite;
3473}
Austin Schuh70cc9552019-01-21 19:46:48 -08003474
3475namespace testing {
3476
3477// Forward declarations.
3478
3479class AssertionResult; // Result of an assertion.
3480class Message; // Represents a failure message.
3481class Test; // Represents a test.
3482class TestInfo; // Information about a test.
3483class TestPartResult; // Result of a test part.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003484class UnitTest; // A collection of test suites.
Austin Schuh70cc9552019-01-21 19:46:48 -08003485
3486template <typename T>
3487::std::string PrintToString(const T& value);
3488
3489namespace internal {
3490
3491struct TraceInfo; // Information about a trace point.
Austin Schuh70cc9552019-01-21 19:46:48 -08003492class TestInfoImpl; // Opaque implementation of TestInfo
3493class UnitTestImpl; // Opaque implementation of UnitTest
3494
3495// The text used in failure messages to indicate the start of the
3496// stack trace.
3497GTEST_API_ extern const char kStackTraceMarker[];
3498
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003499// An IgnoredValue object can be implicitly constructed from ANY value.
3500class IgnoredValue {
3501 struct Sink {};
3502 public:
3503 // This constructor template allows any value to be implicitly
3504 // converted to IgnoredValue. The object has no data member and
3505 // doesn't try to remember anything about the argument. We
3506 // deliberately omit the 'explicit' keyword in order to allow the
3507 // conversion to be implicit.
3508 // Disable the conversion if T already has a magical conversion operator.
3509 // Otherwise we get ambiguity.
3510 template <typename T,
3511 typename std::enable_if<!std::is_convertible<T, Sink>::value,
3512 int>::type = 0>
3513 IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
3514};
3515
Austin Schuh70cc9552019-01-21 19:46:48 -08003516// Appends the user-supplied message to the Google-Test-generated message.
3517GTEST_API_ std::string AppendUserMessage(
3518 const std::string& gtest_msg, const Message& user_msg);
3519
3520#if GTEST_HAS_EXCEPTIONS
3521
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003522GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
3523/* an exported class was derived from a class that was not exported */)
3524
Austin Schuh70cc9552019-01-21 19:46:48 -08003525// This exception is thrown by (and only by) a failed Google Test
3526// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
3527// are enabled). We derive it from std::runtime_error, which is for
3528// errors presumably detectable only at run time. Since
3529// std::runtime_error inherits from std::exception, many testing
3530// frameworks know how to extract and print the message inside it.
3531class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
3532 public:
3533 explicit GoogleTestFailureException(const TestPartResult& failure);
3534};
3535
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003536GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
3537
Austin Schuh70cc9552019-01-21 19:46:48 -08003538#endif // GTEST_HAS_EXCEPTIONS
3539
Austin Schuh70cc9552019-01-21 19:46:48 -08003540namespace edit_distance {
3541// Returns the optimal edits to go from 'left' to 'right'.
3542// All edits cost the same, with replace having lower priority than
3543// add/remove.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003544// Simple implementation of the Wagner-Fischer algorithm.
Austin Schuh70cc9552019-01-21 19:46:48 -08003545// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
3546enum EditType { kMatch, kAdd, kRemove, kReplace };
3547GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
3548 const std::vector<size_t>& left, const std::vector<size_t>& right);
3549
3550// Same as above, but the input is represented as strings.
3551GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
3552 const std::vector<std::string>& left,
3553 const std::vector<std::string>& right);
3554
3555// Create a diff of the input strings in Unified diff format.
3556GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
3557 const std::vector<std::string>& right,
3558 size_t context = 2);
3559
3560} // namespace edit_distance
3561
3562// Calculate the diff between 'left' and 'right' and return it in unified diff
3563// format.
3564// If not null, stores in 'total_line_count' the total number of lines found
3565// in left + right.
3566GTEST_API_ std::string DiffStrings(const std::string& left,
3567 const std::string& right,
3568 size_t* total_line_count);
3569
3570// Constructs and returns the message for an equality assertion
3571// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
3572//
3573// The first four parameters are the expressions used in the assertion
3574// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
3575// where foo is 5 and bar is 6, we have:
3576//
3577// expected_expression: "foo"
3578// actual_expression: "bar"
3579// expected_value: "5"
3580// actual_value: "6"
3581//
Austin Schuh3de38b02024-06-25 18:25:10 -07003582// The ignoring_case parameter is true if and only if the assertion is a
Austin Schuh70cc9552019-01-21 19:46:48 -08003583// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
3584// be inserted into the message.
3585GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
3586 const char* actual_expression,
3587 const std::string& expected_value,
3588 const std::string& actual_value,
3589 bool ignoring_case);
3590
3591// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
3592GTEST_API_ std::string GetBoolAssertionFailureMessage(
3593 const AssertionResult& assertion_result,
3594 const char* expression_text,
3595 const char* actual_predicate_value,
3596 const char* expected_predicate_value);
3597
3598// This template class represents an IEEE floating-point number
3599// (either single-precision or double-precision, depending on the
3600// template parameters).
3601//
3602// The purpose of this class is to do more sophisticated number
3603// comparison. (Due to round-off error, etc, it's very unlikely that
3604// two floating-points will be equal exactly. Hence a naive
3605// comparison by the == operation often doesn't work.)
3606//
3607// Format of IEEE floating-point:
3608//
3609// The most-significant bit being the leftmost, an IEEE
3610// floating-point looks like
3611//
3612// sign_bit exponent_bits fraction_bits
3613//
3614// Here, sign_bit is a single bit that designates the sign of the
3615// number.
3616//
3617// For float, there are 8 exponent bits and 23 fraction bits.
3618//
3619// For double, there are 11 exponent bits and 52 fraction bits.
3620//
3621// More details can be found at
3622// http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
3623//
3624// Template parameter:
3625//
3626// RawType: the raw floating-point type (either float or double)
3627template <typename RawType>
3628class FloatingPoint {
3629 public:
3630 // Defines the unsigned integer type that has the same size as the
3631 // floating point number.
3632 typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
3633
3634 // Constants.
3635
3636 // # of bits in a number.
3637 static const size_t kBitCount = 8*sizeof(RawType);
3638
3639 // # of fraction bits in a number.
3640 static const size_t kFractionBitCount =
3641 std::numeric_limits<RawType>::digits - 1;
3642
3643 // # of exponent bits in a number.
3644 static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
3645
3646 // The mask for the sign bit.
3647 static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
3648
3649 // The mask for the fraction bits.
3650 static const Bits kFractionBitMask =
3651 ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
3652
3653 // The mask for the exponent bits.
3654 static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
3655
3656 // How many ULP's (Units in the Last Place) we want to tolerate when
3657 // comparing two numbers. The larger the value, the more error we
3658 // allow. A 0 value means that two numbers must be exactly the same
3659 // to be considered equal.
3660 //
3661 // The maximum error of a single floating-point operation is 0.5
3662 // units in the last place. On Intel CPU's, all floating-point
3663 // calculations are done with 80-bit precision, while double has 64
3664 // bits. Therefore, 4 should be enough for ordinary use.
3665 //
3666 // See the following article for more details on ULP:
3667 // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
Austin Schuh3de38b02024-06-25 18:25:10 -07003668 static const uint32_t kMaxUlps = 4;
Austin Schuh70cc9552019-01-21 19:46:48 -08003669
3670 // Constructs a FloatingPoint from a raw floating-point number.
3671 //
3672 // On an Intel CPU, passing a non-normalized NAN (Not a Number)
3673 // around may change its bits, although the new value is guaranteed
3674 // to be also a NAN. Therefore, don't expect this constructor to
3675 // preserve the bits in x when x is a NAN.
3676 explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
3677
3678 // Static methods
3679
3680 // Reinterprets a bit pattern as a floating-point number.
3681 //
3682 // This function is needed to test the AlmostEquals() method.
3683 static RawType ReinterpretBits(const Bits bits) {
3684 FloatingPoint fp(0);
3685 fp.u_.bits_ = bits;
3686 return fp.u_.value_;
3687 }
3688
3689 // Returns the floating-point number that represent positive infinity.
3690 static RawType Infinity() {
3691 return ReinterpretBits(kExponentBitMask);
3692 }
3693
3694 // Returns the maximum representable finite floating-point number.
3695 static RawType Max();
3696
3697 // Non-static methods
3698
3699 // Returns the bits that represents this number.
3700 const Bits &bits() const { return u_.bits_; }
3701
3702 // Returns the exponent bits of this number.
3703 Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
3704
3705 // Returns the fraction bits of this number.
3706 Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
3707
3708 // Returns the sign bit of this number.
3709 Bits sign_bit() const { return kSignBitMask & u_.bits_; }
3710
Austin Schuh3de38b02024-06-25 18:25:10 -07003711 // Returns true if and only if this is NAN (not a number).
Austin Schuh70cc9552019-01-21 19:46:48 -08003712 bool is_nan() const {
3713 // It's a NAN if the exponent bits are all ones and the fraction
3714 // bits are not entirely zeros.
3715 return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
3716 }
3717
Austin Schuh3de38b02024-06-25 18:25:10 -07003718 // Returns true if and only if this number is at most kMaxUlps ULP's away
3719 // from rhs. In particular, this function:
Austin Schuh70cc9552019-01-21 19:46:48 -08003720 //
3721 // - returns false if either number is (or both are) NAN.
3722 // - treats really large numbers as almost equal to infinity.
3723 // - thinks +0.0 and -0.0 are 0 DLP's apart.
3724 bool AlmostEquals(const FloatingPoint& rhs) const {
3725 // The IEEE standard says that any comparison operation involving
3726 // a NAN must return false.
3727 if (is_nan() || rhs.is_nan()) return false;
3728
3729 return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
3730 <= kMaxUlps;
3731 }
3732
3733 private:
3734 // The data type used to store the actual floating-point number.
3735 union FloatingPointUnion {
3736 RawType value_; // The raw floating-point number.
3737 Bits bits_; // The bits that represent the number.
3738 };
3739
3740 // Converts an integer from the sign-and-magnitude representation to
3741 // the biased representation. More precisely, let N be 2 to the
3742 // power of (kBitCount - 1), an integer x is represented by the
3743 // unsigned number x + N.
3744 //
3745 // For instance,
3746 //
3747 // -N + 1 (the most negative number representable using
3748 // sign-and-magnitude) is represented by 1;
3749 // 0 is represented by N; and
3750 // N - 1 (the biggest number representable using
3751 // sign-and-magnitude) is represented by 2N - 1.
3752 //
3753 // Read http://en.wikipedia.org/wiki/Signed_number_representations
3754 // for more details on signed number representations.
3755 static Bits SignAndMagnitudeToBiased(const Bits &sam) {
3756 if (kSignBitMask & sam) {
3757 // sam represents a negative number.
3758 return ~sam + 1;
3759 } else {
3760 // sam represents a positive number.
3761 return kSignBitMask | sam;
3762 }
3763 }
3764
3765 // Given two numbers in the sign-and-magnitude representation,
3766 // returns the distance between them as an unsigned number.
3767 static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
3768 const Bits &sam2) {
3769 const Bits biased1 = SignAndMagnitudeToBiased(sam1);
3770 const Bits biased2 = SignAndMagnitudeToBiased(sam2);
3771 return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
3772 }
3773
3774 FloatingPointUnion u_;
3775};
3776
3777// We cannot use std::numeric_limits<T>::max() as it clashes with the max()
3778// macro defined by <windows.h>.
3779template <>
3780inline float FloatingPoint<float>::Max() { return FLT_MAX; }
3781template <>
3782inline double FloatingPoint<double>::Max() { return DBL_MAX; }
3783
3784// Typedefs the instances of the FloatingPoint template class that we
3785// care to use.
3786typedef FloatingPoint<float> Float;
3787typedef FloatingPoint<double> Double;
3788
3789// In order to catch the mistake of putting tests that use different
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003790// test fixture classes in the same test suite, we need to assign
Austin Schuh70cc9552019-01-21 19:46:48 -08003791// unique IDs to fixture classes and compare them. The TypeId type is
3792// used to hold such IDs. The user should treat TypeId as an opaque
3793// type: the only operation allowed on TypeId values is to compare
3794// them for equality using the == operator.
3795typedef const void* TypeId;
3796
3797template <typename T>
3798class TypeIdHelper {
3799 public:
3800 // dummy_ must not have a const type. Otherwise an overly eager
3801 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
3802 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
3803 static bool dummy_;
3804};
3805
3806template <typename T>
3807bool TypeIdHelper<T>::dummy_ = false;
3808
3809// GetTypeId<T>() returns the ID of type T. Different values will be
3810// returned for different types. Calling the function twice with the
3811// same type argument is guaranteed to return the same ID.
3812template <typename T>
3813TypeId GetTypeId() {
3814 // The compiler is required to allocate a different
3815 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
3816 // the template. Therefore, the address of dummy_ is guaranteed to
3817 // be unique.
3818 return &(TypeIdHelper<T>::dummy_);
3819}
3820
3821// Returns the type ID of ::testing::Test. Always call this instead
3822// of GetTypeId< ::testing::Test>() to get the type ID of
3823// ::testing::Test, as the latter may give the wrong result due to a
3824// suspected linker bug when compiling Google Test as a Mac OS X
3825// framework.
3826GTEST_API_ TypeId GetTestTypeId();
3827
3828// Defines the abstract factory interface that creates instances
3829// of a Test object.
3830class TestFactoryBase {
3831 public:
3832 virtual ~TestFactoryBase() {}
3833
3834 // Creates a test instance to run. The instance is both created and destroyed
3835 // within TestInfoImpl::Run()
3836 virtual Test* CreateTest() = 0;
3837
3838 protected:
3839 TestFactoryBase() {}
3840
3841 private:
3842 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
3843};
3844
3845// This class provides implementation of TeastFactoryBase interface.
3846// It is used in TEST and TEST_F macros.
3847template <class TestClass>
3848class TestFactoryImpl : public TestFactoryBase {
3849 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003850 Test* CreateTest() override { return new TestClass; }
Austin Schuh70cc9552019-01-21 19:46:48 -08003851};
3852
3853#if GTEST_OS_WINDOWS
3854
3855// Predicate-formatters for implementing the HRESULT checking macros
3856// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
3857// We pass a long instead of HRESULT to avoid causing an
3858// include dependency for the HRESULT type.
3859GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
3860 long hr); // NOLINT
3861GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
3862 long hr); // NOLINT
3863
3864#endif // GTEST_OS_WINDOWS
3865
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003866// Types of SetUpTestSuite() and TearDownTestSuite() functions.
3867using SetUpTestSuiteFunc = void (*)();
3868using TearDownTestSuiteFunc = void (*)();
Austin Schuh70cc9552019-01-21 19:46:48 -08003869
3870struct CodeLocation {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003871 CodeLocation(const std::string& a_file, int a_line)
3872 : file(a_file), line(a_line) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08003873
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003874 std::string file;
Austin Schuh70cc9552019-01-21 19:46:48 -08003875 int line;
3876};
3877
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003878// Helper to identify which setup function for TestCase / TestSuite to call.
3879// Only one function is allowed, either TestCase or TestSute but not both.
3880
3881// Utility functions to help SuiteApiResolver
3882using SetUpTearDownSuiteFuncType = void (*)();
3883
3884inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
3885 SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {
3886 return a == def ? nullptr : a;
3887}
3888
3889template <typename T>
3890// Note that SuiteApiResolver inherits from T because
3891// SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
3892// SuiteApiResolver can access them.
3893struct SuiteApiResolver : T {
3894 // testing::Test is only forward declared at this point. So we make it a
3895 // dependend class for the compiler to be OK with it.
3896 using Test =
3897 typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
3898
Austin Schuh3de38b02024-06-25 18:25:10 -07003899 static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
3900 int line_num) {
3901#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003902 SetUpTearDownSuiteFuncType test_case_fp =
3903 GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
3904 SetUpTearDownSuiteFuncType test_suite_fp =
3905 GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);
3906
3907 GTEST_CHECK_(!test_case_fp || !test_suite_fp)
3908 << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
Austin Schuh3de38b02024-06-25 18:25:10 -07003909 "make sure there is only one present at "
3910 << filename << ":" << line_num;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003911
3912 return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
Austin Schuh3de38b02024-06-25 18:25:10 -07003913#else
3914 (void)(filename);
3915 (void)(line_num);
3916 return &T::SetUpTestSuite;
3917#endif
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003918 }
3919
Austin Schuh3de38b02024-06-25 18:25:10 -07003920 static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
3921 int line_num) {
3922#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003923 SetUpTearDownSuiteFuncType test_case_fp =
3924 GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
3925 SetUpTearDownSuiteFuncType test_suite_fp =
3926 GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);
3927
3928 GTEST_CHECK_(!test_case_fp || !test_suite_fp)
3929 << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
Austin Schuh3de38b02024-06-25 18:25:10 -07003930 " please make sure there is only one present at"
3931 << filename << ":" << line_num;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003932
3933 return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
Austin Schuh3de38b02024-06-25 18:25:10 -07003934#else
3935 (void)(filename);
3936 (void)(line_num);
3937 return &T::TearDownTestSuite;
3938#endif
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003939 }
3940};
3941
Austin Schuh70cc9552019-01-21 19:46:48 -08003942// Creates a new TestInfo object and registers it with Google Test;
3943// returns the created object.
3944//
3945// Arguments:
3946//
Austin Schuh3de38b02024-06-25 18:25:10 -07003947// test_suite_name: name of the test suite
Austin Schuh70cc9552019-01-21 19:46:48 -08003948// name: name of the test
Austin Schuh3de38b02024-06-25 18:25:10 -07003949// type_param: the name of the test's type parameter, or NULL if
Austin Schuh70cc9552019-01-21 19:46:48 -08003950// this is not a typed or a type-parameterized test.
Austin Schuh3de38b02024-06-25 18:25:10 -07003951// value_param: text representation of the test's value parameter,
Austin Schuh70cc9552019-01-21 19:46:48 -08003952// or NULL if this is not a type-parameterized test.
3953// code_location: code location where the test is defined
3954// fixture_class_id: ID of the test fixture class
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003955// set_up_tc: pointer to the function that sets up the test suite
3956// tear_down_tc: pointer to the function that tears down the test suite
Austin Schuh70cc9552019-01-21 19:46:48 -08003957// factory: pointer to the factory that creates a test object.
3958// The newly created TestInfo instance will assume
3959// ownership of the factory object.
3960GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003961 const char* test_suite_name, const char* name, const char* type_param,
3962 const char* value_param, CodeLocation code_location,
3963 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
3964 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
Austin Schuh70cc9552019-01-21 19:46:48 -08003965
3966// If *pstr starts with the given prefix, modifies *pstr to be right
3967// past the prefix and returns true; otherwise leaves *pstr unchanged
3968// and returns false. None of pstr, *pstr, and prefix can be NULL.
3969GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
3970
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003971GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
3972/* class A needs to have dll-interface to be used by clients of class B */)
3973
3974// State of the definition of a type-parameterized test suite.
3975class GTEST_API_ TypedTestSuitePState {
Austin Schuh70cc9552019-01-21 19:46:48 -08003976 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003977 TypedTestSuitePState() : registered_(false) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08003978
3979 // Adds the given test name to defined_test_names_ and return true
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003980 // if the test suite hasn't been registered; otherwise aborts the
Austin Schuh70cc9552019-01-21 19:46:48 -08003981 // program.
3982 bool AddTestName(const char* file, int line, const char* case_name,
3983 const char* test_name) {
3984 if (registered_) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08003985 fprintf(stderr,
3986 "%s Test %s must be defined before "
3987 "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
Austin Schuh70cc9552019-01-21 19:46:48 -08003988 FormatFileLocation(file, line).c_str(), test_name, case_name);
3989 fflush(stderr);
3990 posix::Abort();
3991 }
3992 registered_tests_.insert(
3993 ::std::make_pair(test_name, CodeLocation(file, line)));
3994 return true;
3995 }
3996
3997 bool TestExists(const std::string& test_name) const {
3998 return registered_tests_.count(test_name) > 0;
3999 }
4000
4001 const CodeLocation& GetCodeLocation(const std::string& test_name) const {
4002 RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
4003 GTEST_CHECK_(it != registered_tests_.end());
4004 return it->second;
4005 }
4006
4007 // Verifies that registered_tests match the test names in
4008 // defined_test_names_; returns registered_tests if successful, or
4009 // aborts the program otherwise.
Austin Schuh3de38b02024-06-25 18:25:10 -07004010 const char* VerifyRegisteredTestNames(const char* test_suite_name,
4011 const char* file, int line,
4012 const char* registered_tests);
Austin Schuh70cc9552019-01-21 19:46:48 -08004013
4014 private:
4015 typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
4016
4017 bool registered_;
4018 RegisteredTestsMap registered_tests_;
4019};
4020
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004021// Legacy API is deprecated but still available
4022#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4023using TypedTestCasePState = TypedTestSuitePState;
4024#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4025
4026GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
4027
Austin Schuh70cc9552019-01-21 19:46:48 -08004028// Skips to the first non-space char after the first comma in 'str';
4029// returns NULL if no comma is found in 'str'.
4030inline const char* SkipComma(const char* str) {
4031 const char* comma = strchr(str, ',');
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004032 if (comma == nullptr) {
4033 return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -08004034 }
4035 while (IsSpace(*(++comma))) {}
4036 return comma;
4037}
4038
4039// Returns the prefix of 'str' before the first comma in it; returns
4040// the entire string if it contains no comma.
4041inline std::string GetPrefixUntilComma(const char* str) {
4042 const char* comma = strchr(str, ',');
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004043 return comma == nullptr ? str : std::string(str, comma);
Austin Schuh70cc9552019-01-21 19:46:48 -08004044}
4045
4046// Splits a given string on a given delimiter, populating a given
4047// vector with the fields.
4048void SplitString(const ::std::string& str, char delimiter,
4049 ::std::vector< ::std::string>* dest);
4050
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004051// The default argument to the template below for the case when the user does
4052// not provide a name generator.
4053struct DefaultNameGenerator {
4054 template <typename T>
4055 static std::string GetName(int i) {
4056 return StreamableToString(i);
4057 }
4058};
4059
4060template <typename Provided = DefaultNameGenerator>
4061struct NameGeneratorSelector {
4062 typedef Provided type;
4063};
4064
4065template <typename NameGenerator>
Austin Schuh3de38b02024-06-25 18:25:10 -07004066void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004067
4068template <typename NameGenerator, typename Types>
4069void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
4070 result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
4071 GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
4072 i + 1);
4073}
4074
4075template <typename NameGenerator, typename Types>
4076std::vector<std::string> GenerateNames() {
4077 std::vector<std::string> result;
4078 GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
4079 return result;
4080}
4081
Austin Schuh70cc9552019-01-21 19:46:48 -08004082// TypeParameterizedTest<Fixture, TestSel, Types>::Register()
4083// registers a list of type-parameterized tests with Google Test. The
4084// return value is insignificant - we just need to return something
4085// such that we can call this function in a namespace scope.
4086//
4087// Implementation note: The GTEST_TEMPLATE_ macro declares a template
4088// template parameter. It's defined in gtest-type-util.h.
4089template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
4090class TypeParameterizedTest {
4091 public:
4092 // 'index' is the index of the test in the type list 'Types'
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004093 // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
Austin Schuh70cc9552019-01-21 19:46:48 -08004094 // Types). Valid values for 'index' are [0, N - 1] where N is the
4095 // length of Types.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004096 static bool Register(const char* prefix, const CodeLocation& code_location,
4097 const char* case_name, const char* test_names, int index,
4098 const std::vector<std::string>& type_names =
4099 GenerateNames<DefaultNameGenerator, Types>()) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004100 typedef typename Types::Head Type;
4101 typedef Fixture<Type> FixtureClass;
4102 typedef typename GTEST_BIND_(TestSel, Type) TestClass;
4103
4104 // First, registers the first type-parameterized test in the type
4105 // list.
4106 MakeAndRegisterTestInfo(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004107 (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
Austin Schuh3de38b02024-06-25 18:25:10 -07004108 "/" + type_names[static_cast<size_t>(index)])
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004109 .c_str(),
Austin Schuh70cc9552019-01-21 19:46:48 -08004110 StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
4111 GetTypeName<Type>().c_str(),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004112 nullptr, // No value parameter.
4113 code_location, GetTypeId<FixtureClass>(),
Austin Schuh3de38b02024-06-25 18:25:10 -07004114 SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(
4115 code_location.file.c_str(), code_location.line),
4116 SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(
4117 code_location.file.c_str(), code_location.line),
Austin Schuh70cc9552019-01-21 19:46:48 -08004118 new TestFactoryImpl<TestClass>);
4119
4120 // Next, recurses (at compile time) with the tail of the type list.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004121 return TypeParameterizedTest<Fixture, TestSel,
4122 typename Types::Tail>::Register(prefix,
4123 code_location,
4124 case_name,
4125 test_names,
4126 index + 1,
4127 type_names);
Austin Schuh70cc9552019-01-21 19:46:48 -08004128 }
4129};
4130
4131// The base case for the compile time recursion.
4132template <GTEST_TEMPLATE_ Fixture, class TestSel>
Austin Schuh3de38b02024-06-25 18:25:10 -07004133class TypeParameterizedTest<Fixture, TestSel, internal::None> {
Austin Schuh70cc9552019-01-21 19:46:48 -08004134 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004135 static bool Register(const char* /*prefix*/, const CodeLocation&,
Austin Schuh70cc9552019-01-21 19:46:48 -08004136 const char* /*case_name*/, const char* /*test_names*/,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004137 int /*index*/,
4138 const std::vector<std::string>& =
4139 std::vector<std::string>() /*type_names*/) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004140 return true;
4141 }
4142};
4143
Austin Schuh3de38b02024-06-25 18:25:10 -07004144GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
4145 CodeLocation code_location);
4146GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
4147 const char* case_name);
4148
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004149// TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
Austin Schuh70cc9552019-01-21 19:46:48 -08004150// registers *all combinations* of 'Tests' and 'Types' with Google
4151// Test. The return value is insignificant - we just need to return
4152// something such that we can call this function in a namespace scope.
4153template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004154class TypeParameterizedTestSuite {
Austin Schuh70cc9552019-01-21 19:46:48 -08004155 public:
4156 static bool Register(const char* prefix, CodeLocation code_location,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004157 const TypedTestSuitePState* state, const char* case_name,
4158 const char* test_names,
4159 const std::vector<std::string>& type_names =
4160 GenerateNames<DefaultNameGenerator, Types>()) {
Austin Schuh3de38b02024-06-25 18:25:10 -07004161 RegisterTypeParameterizedTestSuiteInstantiation(case_name);
Austin Schuh70cc9552019-01-21 19:46:48 -08004162 std::string test_name = StripTrailingSpaces(
4163 GetPrefixUntilComma(test_names));
4164 if (!state->TestExists(test_name)) {
4165 fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
4166 case_name, test_name.c_str(),
4167 FormatFileLocation(code_location.file.c_str(),
4168 code_location.line).c_str());
4169 fflush(stderr);
4170 posix::Abort();
4171 }
4172 const CodeLocation& test_location = state->GetCodeLocation(test_name);
4173
4174 typedef typename Tests::Head Head;
4175
4176 // First, register the first test in 'Test' for each type in 'Types'.
4177 TypeParameterizedTest<Fixture, Head, Types>::Register(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004178 prefix, test_location, case_name, test_names, 0, type_names);
Austin Schuh70cc9552019-01-21 19:46:48 -08004179
4180 // Next, recurses (at compile time) with the tail of the test list.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004181 return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
4182 Types>::Register(prefix, code_location,
4183 state, case_name,
4184 SkipComma(test_names),
4185 type_names);
Austin Schuh70cc9552019-01-21 19:46:48 -08004186 }
4187};
4188
4189// The base case for the compile time recursion.
4190template <GTEST_TEMPLATE_ Fixture, typename Types>
Austin Schuh3de38b02024-06-25 18:25:10 -07004191class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
Austin Schuh70cc9552019-01-21 19:46:48 -08004192 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004193 static bool Register(const char* /*prefix*/, const CodeLocation&,
4194 const TypedTestSuitePState* /*state*/,
4195 const char* /*case_name*/, const char* /*test_names*/,
4196 const std::vector<std::string>& =
4197 std::vector<std::string>() /*type_names*/) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004198 return true;
4199 }
4200};
4201
Austin Schuh70cc9552019-01-21 19:46:48 -08004202// Returns the current OS stack trace as an std::string.
4203//
4204// The maximum number of stack frames to be included is specified by
4205// the gtest_stack_trace_depth flag. The skip_count parameter
4206// specifies the number of top frames to be skipped, which doesn't
4207// count against the number of frames to be included.
4208//
4209// For example, if Foo() calls Bar(), which in turn calls
4210// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4211// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4212GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
4213 UnitTest* unit_test, int skip_count);
4214
4215// Helpers for suppressing warnings on unreachable code or constant
4216// condition.
4217
4218// Always returns true.
4219GTEST_API_ bool AlwaysTrue();
4220
4221// Always returns false.
4222inline bool AlwaysFalse() { return !AlwaysTrue(); }
4223
4224// Helper for suppressing false warning from Clang on a const char*
4225// variable declared in a conditional expression always being NULL in
4226// the else branch.
4227struct GTEST_API_ ConstCharPtr {
4228 ConstCharPtr(const char* str) : value(str) {}
4229 operator bool() const { return true; }
4230 const char* value;
4231};
4232
Austin Schuh3de38b02024-06-25 18:25:10 -07004233// Helper for declaring std::string within 'if' statement
4234// in pre C++17 build environment.
4235struct TrueWithString {
4236 TrueWithString() = default;
4237 explicit TrueWithString(const char* str) : value(str) {}
4238 explicit TrueWithString(const std::string& str) : value(str) {}
4239 explicit operator bool() const { return true; }
4240 std::string value;
4241};
4242
Austin Schuh70cc9552019-01-21 19:46:48 -08004243// A simple Linear Congruential Generator for generating random
4244// numbers with a uniform distribution. Unlike rand() and srand(), it
4245// doesn't use global state (and therefore can't interfere with user
4246// code). Unlike rand_r(), it's portable. An LCG isn't very random,
4247// but it's good enough for our purposes.
4248class GTEST_API_ Random {
4249 public:
Austin Schuh3de38b02024-06-25 18:25:10 -07004250 static const uint32_t kMaxRange = 1u << 31;
Austin Schuh70cc9552019-01-21 19:46:48 -08004251
Austin Schuh3de38b02024-06-25 18:25:10 -07004252 explicit Random(uint32_t seed) : state_(seed) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08004253
Austin Schuh3de38b02024-06-25 18:25:10 -07004254 void Reseed(uint32_t seed) { state_ = seed; }
Austin Schuh70cc9552019-01-21 19:46:48 -08004255
4256 // Generates a random number from [0, range). Crashes if 'range' is
4257 // 0 or greater than kMaxRange.
Austin Schuh3de38b02024-06-25 18:25:10 -07004258 uint32_t Generate(uint32_t range);
Austin Schuh70cc9552019-01-21 19:46:48 -08004259
4260 private:
Austin Schuh3de38b02024-06-25 18:25:10 -07004261 uint32_t state_;
Austin Schuh70cc9552019-01-21 19:46:48 -08004262 GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
4263};
4264
Austin Schuh70cc9552019-01-21 19:46:48 -08004265// Turns const U&, U&, const U, and U all into U.
4266#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
Austin Schuh3de38b02024-06-25 18:25:10 -07004267 typename std::remove_const<typename std::remove_reference<T>::type>::type
Austin Schuh70cc9552019-01-21 19:46:48 -08004268
Austin Schuh3de38b02024-06-25 18:25:10 -07004269// HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
4270// that's true if and only if T has methods DebugString() and ShortDebugString()
4271// that return std::string.
Austin Schuh70cc9552019-01-21 19:46:48 -08004272template <typename T>
Austin Schuh3de38b02024-06-25 18:25:10 -07004273class HasDebugStringAndShortDebugString {
4274 private:
4275 template <typename C>
4276 static auto CheckDebugString(C*) -> typename std::is_same<
4277 std::string, decltype(std::declval<const C>().DebugString())>::type;
4278 template <typename>
4279 static std::false_type CheckDebugString(...);
4280
4281 template <typename C>
4282 static auto CheckShortDebugString(C*) -> typename std::is_same<
4283 std::string, decltype(std::declval<const C>().ShortDebugString())>::type;
4284 template <typename>
4285 static std::false_type CheckShortDebugString(...);
4286
4287 using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));
4288 using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));
4289
4290 public:
4291 static constexpr bool value =
4292 HasDebugStringType::value && HasShortDebugStringType::value;
Austin Schuh70cc9552019-01-21 19:46:48 -08004293};
4294
Austin Schuh3de38b02024-06-25 18:25:10 -07004295template <typename T>
4296constexpr bool HasDebugStringAndShortDebugString<T>::value;
4297
Austin Schuh70cc9552019-01-21 19:46:48 -08004298// When the compiler sees expression IsContainerTest<C>(0), if C is an
4299// STL-style container class, the first overload of IsContainerTest
4300// will be viable (since both C::iterator* and C::const_iterator* are
4301// valid types and NULL can be implicitly converted to them). It will
4302// be picked over the second overload as 'int' is a perfect match for
4303// the type of argument 0. If C::iterator or C::const_iterator is not
4304// a valid type, the first overload is not viable, and the second
4305// overload will be picked. Therefore, we can determine whether C is
4306// a container class by checking the type of IsContainerTest<C>(0).
4307// The value of the expression is insignificant.
4308//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004309// In C++11 mode we check the existence of a const_iterator and that an
4310// iterator is properly implemented for the container.
4311//
4312// For pre-C++11 that we look for both C::iterator and C::const_iterator.
4313// The reason is that C++ injects the name of a class as a member of the
Austin Schuh70cc9552019-01-21 19:46:48 -08004314// class itself (e.g. you can refer to class iterator as either
4315// 'iterator' or 'iterator::iterator'). If we look for C::iterator
4316// only, for example, we would mistakenly think that a class named
4317// iterator is an STL container.
4318//
4319// Also note that the simpler approach of overloading
4320// IsContainerTest(typename C::const_iterator*) and
4321// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
4322typedef int IsContainer;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004323template <class C,
4324 class Iterator = decltype(::std::declval<const C&>().begin()),
4325 class = decltype(::std::declval<const C&>().end()),
4326 class = decltype(++::std::declval<Iterator&>()),
4327 class = decltype(*::std::declval<Iterator>()),
4328 class = typename C::const_iterator>
4329IsContainer IsContainerTest(int /* dummy */) {
Austin Schuh70cc9552019-01-21 19:46:48 -08004330 return 0;
4331}
4332
4333typedef char IsNotContainer;
4334template <class C>
4335IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
4336
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004337// Trait to detect whether a type T is a hash table.
4338// The heuristic used is that the type contains an inner type `hasher` and does
4339// not contain an inner type `reverse_iterator`.
4340// If the container is iterable in reverse, then order might actually matter.
4341template <typename T>
4342struct IsHashTable {
4343 private:
4344 template <typename U>
4345 static char test(typename U::hasher*, typename U::reverse_iterator*);
4346 template <typename U>
4347 static int test(typename U::hasher*, ...);
4348 template <typename U>
4349 static char test(...);
4350
4351 public:
4352 static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);
4353};
4354
4355template <typename T>
4356const bool IsHashTable<T>::value;
4357
4358template <typename C,
4359 bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>
4360struct IsRecursiveContainerImpl;
4361
4362template <typename C>
Austin Schuh3de38b02024-06-25 18:25:10 -07004363struct IsRecursiveContainerImpl<C, false> : public std::false_type {};
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004364
4365// Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
4366// obey the same inconsistencies as the IsContainerTest, namely check if
4367// something is a container is relying on only const_iterator in C++11 and
4368// is relying on both const_iterator and iterator otherwise
4369template <typename C>
4370struct IsRecursiveContainerImpl<C, true> {
4371 using value_type = decltype(*std::declval<typename C::const_iterator>());
4372 using type =
Austin Schuh3de38b02024-06-25 18:25:10 -07004373 std::is_same<typename std::remove_const<
4374 typename std::remove_reference<value_type>::type>::type,
4375 C>;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004376};
4377
4378// IsRecursiveContainer<Type> is a unary compile-time predicate that
4379// evaluates whether C is a recursive container type. A recursive container
4380// type is a container type whose value_type is equal to the container type
4381// itself. An example for a recursive container type is
4382// boost::filesystem::path, whose iterator has a value_type that is equal to
4383// boost::filesystem::path.
4384template <typename C>
4385struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};
4386
Austin Schuh70cc9552019-01-21 19:46:48 -08004387// Utilities for native arrays.
4388
4389// ArrayEq() compares two k-dimensional native arrays using the
4390// elements' operator==, where k can be any integer >= 0. When k is
4391// 0, ArrayEq() degenerates into comparing a single pair of values.
4392
4393template <typename T, typename U>
4394bool ArrayEq(const T* lhs, size_t size, const U* rhs);
4395
4396// This generic version is used when k is 0.
4397template <typename T, typename U>
4398inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
4399
4400// This overload is used when k >= 1.
4401template <typename T, typename U, size_t N>
4402inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
4403 return internal::ArrayEq(lhs, N, rhs);
4404}
4405
4406// This helper reduces code bloat. If we instead put its logic inside
4407// the previous ArrayEq() function, arrays with different sizes would
4408// lead to different copies of the template code.
4409template <typename T, typename U>
4410bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
4411 for (size_t i = 0; i != size; i++) {
4412 if (!internal::ArrayEq(lhs[i], rhs[i]))
4413 return false;
4414 }
4415 return true;
4416}
4417
4418// Finds the first element in the iterator range [begin, end) that
4419// equals elem. Element may be a native array type itself.
4420template <typename Iter, typename Element>
4421Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
4422 for (Iter it = begin; it != end; ++it) {
4423 if (internal::ArrayEq(*it, elem))
4424 return it;
4425 }
4426 return end;
4427}
4428
4429// CopyArray() copies a k-dimensional native array using the elements'
4430// operator=, where k can be any integer >= 0. When k is 0,
4431// CopyArray() degenerates into copying a single value.
4432
4433template <typename T, typename U>
4434void CopyArray(const T* from, size_t size, U* to);
4435
4436// This generic version is used when k is 0.
4437template <typename T, typename U>
4438inline void CopyArray(const T& from, U* to) { *to = from; }
4439
4440// This overload is used when k >= 1.
4441template <typename T, typename U, size_t N>
4442inline void CopyArray(const T(&from)[N], U(*to)[N]) {
4443 internal::CopyArray(from, N, *to);
4444}
4445
4446// This helper reduces code bloat. If we instead put its logic inside
4447// the previous CopyArray() function, arrays with different sizes
4448// would lead to different copies of the template code.
4449template <typename T, typename U>
4450void CopyArray(const T* from, size_t size, U* to) {
4451 for (size_t i = 0; i != size; i++) {
4452 internal::CopyArray(from[i], to + i);
4453 }
4454}
4455
4456// The relation between an NativeArray object (see below) and the
4457// native array it represents.
4458// We use 2 different structs to allow non-copyable types to be used, as long
4459// as RelationToSourceReference() is passed.
4460struct RelationToSourceReference {};
4461struct RelationToSourceCopy {};
4462
4463// Adapts a native array to a read-only STL-style container. Instead
4464// of the complete STL container concept, this adaptor only implements
4465// members useful for Google Mock's container matchers. New members
4466// should be added as needed. To simplify the implementation, we only
4467// support Element being a raw type (i.e. having no top-level const or
4468// reference modifier). It's the client's responsibility to satisfy
4469// this requirement. Element can be an array type itself (hence
4470// multi-dimensional arrays are supported).
4471template <typename Element>
4472class NativeArray {
4473 public:
4474 // STL-style container typedefs.
4475 typedef Element value_type;
4476 typedef Element* iterator;
4477 typedef const Element* const_iterator;
4478
4479 // Constructs from a native array. References the source.
4480 NativeArray(const Element* array, size_t count, RelationToSourceReference) {
4481 InitRef(array, count);
4482 }
4483
4484 // Constructs from a native array. Copies the source.
4485 NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
4486 InitCopy(array, count);
4487 }
4488
4489 // Copy constructor.
4490 NativeArray(const NativeArray& rhs) {
4491 (this->*rhs.clone_)(rhs.array_, rhs.size_);
4492 }
4493
4494 ~NativeArray() {
4495 if (clone_ != &NativeArray::InitRef)
4496 delete[] array_;
4497 }
4498
4499 // STL-style container methods.
4500 size_t size() const { return size_; }
4501 const_iterator begin() const { return array_; }
4502 const_iterator end() const { return array_ + size_; }
4503 bool operator==(const NativeArray& rhs) const {
4504 return size() == rhs.size() &&
4505 ArrayEq(begin(), size(), rhs.begin());
4506 }
4507
4508 private:
Austin Schuh3de38b02024-06-25 18:25:10 -07004509 static_assert(!std::is_const<Element>::value, "Type must not be const");
4510 static_assert(!std::is_reference<Element>::value,
4511 "Type must not be a reference");
Austin Schuh70cc9552019-01-21 19:46:48 -08004512
4513 // Initializes this object with a copy of the input.
4514 void InitCopy(const Element* array, size_t a_size) {
4515 Element* const copy = new Element[a_size];
4516 CopyArray(array, a_size, copy);
4517 array_ = copy;
4518 size_ = a_size;
4519 clone_ = &NativeArray::InitCopy;
4520 }
4521
4522 // Initializes this object with a reference of the input.
4523 void InitRef(const Element* array, size_t a_size) {
4524 array_ = array;
4525 size_ = a_size;
4526 clone_ = &NativeArray::InitRef;
4527 }
4528
4529 const Element* array_;
4530 size_t size_;
4531 void (NativeArray::*clone_)(const Element*, size_t);
Austin Schuh70cc9552019-01-21 19:46:48 -08004532};
4533
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004534// Backport of std::index_sequence.
4535template <size_t... Is>
4536struct IndexSequence {
4537 using type = IndexSequence;
4538};
4539
4540// Double the IndexSequence, and one if plus_one is true.
4541template <bool plus_one, typename T, size_t sizeofT>
4542struct DoubleSequence;
4543template <size_t... I, size_t sizeofT>
4544struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
4545 using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
4546};
4547template <size_t... I, size_t sizeofT>
4548struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
4549 using type = IndexSequence<I..., (sizeofT + I)...>;
4550};
4551
4552// Backport of std::make_index_sequence.
4553// It uses O(ln(N)) instantiation depth.
4554template <size_t N>
Austin Schuh3de38b02024-06-25 18:25:10 -07004555struct MakeIndexSequenceImpl
4556 : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004557 N / 2>::type {};
4558
4559template <>
Austin Schuh3de38b02024-06-25 18:25:10 -07004560struct MakeIndexSequenceImpl<0> : IndexSequence<> {};
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004561
Austin Schuh3de38b02024-06-25 18:25:10 -07004562template <size_t N>
4563using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004564
Austin Schuh3de38b02024-06-25 18:25:10 -07004565template <typename... T>
4566using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;
4567
4568template <size_t>
4569struct Ignore {
4570 Ignore(...); // NOLINT
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004571};
4572
Austin Schuh3de38b02024-06-25 18:25:10 -07004573template <typename>
4574struct ElemFromListImpl;
4575template <size_t... I>
4576struct ElemFromListImpl<IndexSequence<I...>> {
4577 // We make Ignore a template to solve a problem with MSVC.
4578 // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but
4579 // MSVC doesn't understand how to deal with that pack expansion.
4580 // Use `0 * I` to have a single instantiation of Ignore.
4581 template <typename R>
4582 static R Apply(Ignore<0 * I>..., R (*)(), ...);
4583};
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004584
Austin Schuh3de38b02024-06-25 18:25:10 -07004585template <size_t N, typename... T>
4586struct ElemFromList {
4587 using type =
4588 decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply(
4589 static_cast<T (*)()>(nullptr)...));
4590};
4591
4592struct FlatTupleConstructTag {};
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004593
4594template <typename... T>
4595class FlatTuple;
4596
4597template <typename Derived, size_t I>
4598struct FlatTupleElemBase;
4599
4600template <typename... T, size_t I>
4601struct FlatTupleElemBase<FlatTuple<T...>, I> {
Austin Schuh3de38b02024-06-25 18:25:10 -07004602 using value_type = typename ElemFromList<I, T...>::type;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004603 FlatTupleElemBase() = default;
Austin Schuh3de38b02024-06-25 18:25:10 -07004604 template <typename Arg>
4605 explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)
4606 : value(std::forward<Arg>(t)) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004607 value_type value;
4608};
4609
4610template <typename Derived, typename Idx>
4611struct FlatTupleBase;
4612
4613template <size_t... Idx, typename... T>
4614struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
4615 : FlatTupleElemBase<FlatTuple<T...>, Idx>... {
4616 using Indices = IndexSequence<Idx...>;
4617 FlatTupleBase() = default;
Austin Schuh3de38b02024-06-25 18:25:10 -07004618 template <typename... Args>
4619 explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)
4620 : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},
4621 std::forward<Args>(args))... {}
4622
4623 template <size_t I>
4624 const typename ElemFromList<I, T...>::type& Get() const {
4625 return FlatTupleElemBase<FlatTuple<T...>, I>::value;
4626 }
4627
4628 template <size_t I>
4629 typename ElemFromList<I, T...>::type& Get() {
4630 return FlatTupleElemBase<FlatTuple<T...>, I>::value;
4631 }
4632
4633 template <typename F>
4634 auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
4635 return std::forward<F>(f)(Get<Idx>()...);
4636 }
4637
4638 template <typename F>
4639 auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
4640 return std::forward<F>(f)(Get<Idx>()...);
4641 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004642};
4643
4644// Analog to std::tuple but with different tradeoffs.
4645// This class minimizes the template instantiation depth, thus allowing more
Austin Schuh3de38b02024-06-25 18:25:10 -07004646// elements than std::tuple would. std::tuple has been seen to require an
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004647// instantiation depth of more than 10x the number of elements in some
4648// implementations.
4649// FlatTuple and ElemFromList are not recursive and have a fixed depth
4650// regardless of T...
4651// MakeIndexSequence, on the other hand, it is recursive but with an
4652// instantiation depth of O(ln(N)).
4653template <typename... T>
4654class FlatTuple
4655 : private FlatTupleBase<FlatTuple<T...>,
4656 typename MakeIndexSequence<sizeof...(T)>::type> {
Austin Schuh3de38b02024-06-25 18:25:10 -07004657 using Indices = typename FlatTupleBase<
4658 FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004659
4660 public:
4661 FlatTuple() = default;
Austin Schuh3de38b02024-06-25 18:25:10 -07004662 template <typename... Args>
4663 explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)
4664 : FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004665
Austin Schuh3de38b02024-06-25 18:25:10 -07004666 using FlatTuple::FlatTupleBase::Apply;
4667 using FlatTuple::FlatTupleBase::Get;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004668};
4669
4670// Utility functions to be called with static_assert to induce deprecation
4671// warnings.
4672GTEST_INTERNAL_DEPRECATED(
4673 "INSTANTIATE_TEST_CASE_P is deprecated, please use "
4674 "INSTANTIATE_TEST_SUITE_P")
4675constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
4676
4677GTEST_INTERNAL_DEPRECATED(
4678 "TYPED_TEST_CASE_P is deprecated, please use "
4679 "TYPED_TEST_SUITE_P")
4680constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
4681
4682GTEST_INTERNAL_DEPRECATED(
4683 "TYPED_TEST_CASE is deprecated, please use "
4684 "TYPED_TEST_SUITE")
4685constexpr bool TypedTestCaseIsDeprecated() { return true; }
4686
4687GTEST_INTERNAL_DEPRECATED(
4688 "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
4689 "REGISTER_TYPED_TEST_SUITE_P")
4690constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
4691
4692GTEST_INTERNAL_DEPRECATED(
4693 "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
4694 "INSTANTIATE_TYPED_TEST_SUITE_P")
4695constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
4696
Austin Schuh70cc9552019-01-21 19:46:48 -08004697} // namespace internal
4698} // namespace testing
4699
Austin Schuh3de38b02024-06-25 18:25:10 -07004700namespace std {
4701// Some standard library implementations use `struct tuple_size` and some use
4702// `class tuple_size`. Clang warns about the mismatch.
4703// https://reviews.llvm.org/D55466
4704#ifdef __clang__
4705#pragma clang diagnostic push
4706#pragma clang diagnostic ignored "-Wmismatched-tags"
4707#endif
4708template <typename... Ts>
4709struct tuple_size<testing::internal::FlatTuple<Ts...>>
4710 : std::integral_constant<size_t, sizeof...(Ts)> {};
4711#ifdef __clang__
4712#pragma clang diagnostic pop
4713#endif
4714} // namespace std
4715
Austin Schuh70cc9552019-01-21 19:46:48 -08004716#define GTEST_MESSAGE_AT_(file, line, message, result_type) \
4717 ::testing::internal::AssertHelper(result_type, file, line, message) \
4718 = ::testing::Message()
4719
4720#define GTEST_MESSAGE_(message, result_type) \
4721 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
4722
4723#define GTEST_FATAL_FAILURE_(message) \
4724 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
4725
4726#define GTEST_NONFATAL_FAILURE_(message) \
4727 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
4728
4729#define GTEST_SUCCESS_(message) \
4730 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
4731
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004732#define GTEST_SKIP_(message) \
4733 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
4734
4735// Suppress MSVC warning 4072 (unreachable code) for the code following
Austin Schuh70cc9552019-01-21 19:46:48 -08004736// statement if it returns or throws (or doesn't return or throw in some
4737// situations).
Austin Schuh3de38b02024-06-25 18:25:10 -07004738// NOTE: The "else" is important to keep this expansion to prevent a top-level
4739// "else" from attaching to our "if".
Austin Schuh70cc9552019-01-21 19:46:48 -08004740#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
Austin Schuh3de38b02024-06-25 18:25:10 -07004741 if (::testing::internal::AlwaysTrue()) { \
4742 statement; \
4743 } else /* NOLINT */ \
4744 static_assert(true, "") // User must have a semicolon after expansion.
Austin Schuh70cc9552019-01-21 19:46:48 -08004745
Austin Schuh3de38b02024-06-25 18:25:10 -07004746#if GTEST_HAS_EXCEPTIONS
4747
4748namespace testing {
4749namespace internal {
4750
4751class NeverThrown {
4752 public:
4753 const char* what() const noexcept {
4754 return "this exception should never be thrown";
4755 }
4756};
4757
4758} // namespace internal
4759} // namespace testing
4760
4761#if GTEST_HAS_RTTI
4762
4763#define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
4764
4765#else // GTEST_HAS_RTTI
4766
4767#define GTEST_EXCEPTION_TYPE_(e) \
4768 std::string { "an std::exception-derived error" }
4769
4770#endif // GTEST_HAS_RTTI
4771
4772#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
4773 catch (typename std::conditional< \
4774 std::is_same<typename std::remove_cv<typename std::remove_reference< \
4775 expected_exception>::type>::type, \
4776 std::exception>::value, \
4777 const ::testing::internal::NeverThrown&, const std::exception&>::type \
4778 e) { \
4779 gtest_msg.value = "Expected: " #statement \
4780 " throws an exception of type " #expected_exception \
4781 ".\n Actual: it throws "; \
4782 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
4783 gtest_msg.value += " with description \""; \
4784 gtest_msg.value += e.what(); \
4785 gtest_msg.value += "\"."; \
4786 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4787 }
4788
4789#else // GTEST_HAS_EXCEPTIONS
4790
4791#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
4792
4793#endif // GTEST_HAS_EXCEPTIONS
4794
4795#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
4796 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4797 if (::testing::internal::TrueWithString gtest_msg{}) { \
4798 bool gtest_caught_expected = false; \
4799 try { \
4800 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4801 } catch (expected_exception const&) { \
4802 gtest_caught_expected = true; \
4803 } \
4804 GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
4805 catch (...) { \
4806 gtest_msg.value = "Expected: " #statement \
4807 " throws an exception of type " #expected_exception \
4808 ".\n Actual: it throws a different type."; \
4809 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4810 } \
4811 if (!gtest_caught_expected) { \
4812 gtest_msg.value = "Expected: " #statement \
4813 " throws an exception of type " #expected_exception \
4814 ".\n Actual: it throws nothing."; \
4815 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4816 } \
4817 } else /*NOLINT*/ \
4818 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
4819 : fail(gtest_msg.value.c_str())
4820
4821#if GTEST_HAS_EXCEPTIONS
4822
4823#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
4824 catch (std::exception const& e) { \
4825 gtest_msg.value = "it throws "; \
4826 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
4827 gtest_msg.value += " with description \""; \
4828 gtest_msg.value += e.what(); \
4829 gtest_msg.value += "\"."; \
4830 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
4831 }
4832
4833#else // GTEST_HAS_EXCEPTIONS
4834
4835#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()
4836
4837#endif // GTEST_HAS_EXCEPTIONS
Austin Schuh70cc9552019-01-21 19:46:48 -08004838
4839#define GTEST_TEST_NO_THROW_(statement, fail) \
4840 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
Austin Schuh3de38b02024-06-25 18:25:10 -07004841 if (::testing::internal::TrueWithString gtest_msg{}) { \
Austin Schuh70cc9552019-01-21 19:46:48 -08004842 try { \
4843 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4844 } \
Austin Schuh3de38b02024-06-25 18:25:10 -07004845 GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
Austin Schuh70cc9552019-01-21 19:46:48 -08004846 catch (...) { \
Austin Schuh3de38b02024-06-25 18:25:10 -07004847 gtest_msg.value = "it throws."; \
Austin Schuh70cc9552019-01-21 19:46:48 -08004848 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
4849 } \
4850 } else \
4851 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
Austin Schuh3de38b02024-06-25 18:25:10 -07004852 fail(("Expected: " #statement " doesn't throw an exception.\n" \
4853 " Actual: " + gtest_msg.value).c_str())
Austin Schuh70cc9552019-01-21 19:46:48 -08004854
4855#define GTEST_TEST_ANY_THROW_(statement, fail) \
4856 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4857 if (::testing::internal::AlwaysTrue()) { \
4858 bool gtest_caught_any = false; \
4859 try { \
4860 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4861 } \
4862 catch (...) { \
4863 gtest_caught_any = true; \
4864 } \
4865 if (!gtest_caught_any) { \
4866 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
4867 } \
4868 } else \
4869 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
4870 fail("Expected: " #statement " throws an exception.\n" \
4871 " Actual: it doesn't.")
4872
4873
4874// Implements Boolean test assertions such as EXPECT_TRUE. expression can be
4875// either a boolean expression or an AssertionResult. text is a textual
Austin Schuh3de38b02024-06-25 18:25:10 -07004876// representation of expression as it was passed into the EXPECT_TRUE.
Austin Schuh70cc9552019-01-21 19:46:48 -08004877#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
4878 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4879 if (const ::testing::AssertionResult gtest_ar_ = \
4880 ::testing::AssertionResult(expression)) \
4881 ; \
4882 else \
4883 fail(::testing::internal::GetBoolAssertionFailureMessage(\
4884 gtest_ar_, text, #actual, #expected).c_str())
4885
4886#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
4887 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4888 if (::testing::internal::AlwaysTrue()) { \
4889 ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
4890 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4891 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
4892 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
4893 } \
4894 } else \
4895 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
4896 fail("Expected: " #statement " doesn't generate new fatal " \
4897 "failures in the current thread.\n" \
4898 " Actual: it does.")
4899
4900// Expands to the name of the class that implements the given test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004901#define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
4902 test_suite_name##_##test_name##_Test
Austin Schuh70cc9552019-01-21 19:46:48 -08004903
4904// Helper macro for defining tests.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004905#define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
Austin Schuh3de38b02024-06-25 18:25:10 -07004906 static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \
4907 "test_suite_name must not be empty"); \
4908 static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \
4909 "test_name must not be empty"); \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004910 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
4911 : public parent_class { \
4912 public: \
Austin Schuh3de38b02024-06-25 18:25:10 -07004913 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
4914 ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004915 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
4916 test_name)); \
Austin Schuh3de38b02024-06-25 18:25:10 -07004917 GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
4918 test_name)); \
4919 \
4920 private: \
4921 void TestBody() override; \
4922 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004923 }; \
4924 \
4925 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
4926 test_name)::test_info_ = \
4927 ::testing::internal::MakeAndRegisterTestInfo( \
4928 #test_suite_name, #test_name, nullptr, nullptr, \
4929 ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
4930 ::testing::internal::SuiteApiResolver< \
Austin Schuh3de38b02024-06-25 18:25:10 -07004931 parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004932 ::testing::internal::SuiteApiResolver< \
Austin Schuh3de38b02024-06-25 18:25:10 -07004933 parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004934 new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
4935 test_suite_name, test_name)>); \
4936 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
Austin Schuh70cc9552019-01-21 19:46:48 -08004937
Austin Schuh3de38b02024-06-25 18:25:10 -07004938#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08004939// Copyright 2005, Google Inc.
4940// All rights reserved.
4941//
4942// Redistribution and use in source and binary forms, with or without
4943// modification, are permitted provided that the following conditions are
4944// met:
4945//
4946// * Redistributions of source code must retain the above copyright
4947// notice, this list of conditions and the following disclaimer.
4948// * Redistributions in binary form must reproduce the above
4949// copyright notice, this list of conditions and the following disclaimer
4950// in the documentation and/or other materials provided with the
4951// distribution.
4952// * Neither the name of Google Inc. nor the names of its
4953// contributors may be used to endorse or promote products derived from
4954// this software without specific prior written permission.
4955//
4956// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4957// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
4958// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
4959// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
4960// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
4961// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
4962// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
4963// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
4964// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
4965// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
4966// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004967
Austin Schuh70cc9552019-01-21 19:46:48 -08004968//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004969// The Google C++ Testing and Mocking Framework (Google Test)
Austin Schuh70cc9552019-01-21 19:46:48 -08004970//
4971// This header file defines the public API for death tests. It is
4972// #included by gtest.h so a user doesn't need to include this
4973// directly.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08004974// GOOGLETEST_CM0001 DO NOT DELETE
Austin Schuh70cc9552019-01-21 19:46:48 -08004975
Austin Schuh3de38b02024-06-25 18:25:10 -07004976#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
4977#define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08004978
4979// Copyright 2005, Google Inc.
4980// All rights reserved.
4981//
4982// Redistribution and use in source and binary forms, with or without
4983// modification, are permitted provided that the following conditions are
4984// met:
4985//
4986// * Redistributions of source code must retain the above copyright
4987// notice, this list of conditions and the following disclaimer.
4988// * Redistributions in binary form must reproduce the above
4989// copyright notice, this list of conditions and the following disclaimer
4990// in the documentation and/or other materials provided with the
4991// distribution.
4992// * Neither the name of Google Inc. nor the names of its
4993// contributors may be used to endorse or promote products derived from
4994// this software without specific prior written permission.
4995//
4996// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4997// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
4998// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
4999// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5000// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5001// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5002// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5003// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5004// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5005// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5006// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5007//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005008// The Google C++ Testing and Mocking Framework (Google Test)
Austin Schuh70cc9552019-01-21 19:46:48 -08005009//
5010// This header file defines internal utilities needed for implementing
5011// death tests. They are subject to change without notice.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005012// GOOGLETEST_CM0001 DO NOT DELETE
Austin Schuh70cc9552019-01-21 19:46:48 -08005013
Austin Schuh3de38b02024-06-25 18:25:10 -07005014#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
5015#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08005016
Austin Schuh70cc9552019-01-21 19:46:48 -08005017// Copyright 2007, Google Inc.
5018// All rights reserved.
5019//
5020// Redistribution and use in source and binary forms, with or without
5021// modification, are permitted provided that the following conditions are
5022// met:
5023//
5024// * Redistributions of source code must retain the above copyright
5025// notice, this list of conditions and the following disclaimer.
5026// * Redistributions in binary form must reproduce the above
5027// copyright notice, this list of conditions and the following disclaimer
5028// in the documentation and/or other materials provided with the
5029// distribution.
5030// * Neither the name of Google Inc. nor the names of its
5031// contributors may be used to endorse or promote products derived from
5032// this software without specific prior written permission.
5033//
5034// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5035// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5036// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5037// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5038// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5039// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5040// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5041// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5042// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5043// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5044// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh70cc9552019-01-21 19:46:48 -08005045
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005046// The Google C++ Testing and Mocking Framework (Google Test)
5047//
5048// This file implements just enough of the matcher interface to allow
5049// EXPECT_DEATH and friends to accept a matcher argument.
5050
Austin Schuh3de38b02024-06-25 18:25:10 -07005051#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
5052#define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005053
Austin Schuh3de38b02024-06-25 18:25:10 -07005054#include <atomic>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005055#include <memory>
5056#include <ostream>
5057#include <string>
Austin Schuh3de38b02024-06-25 18:25:10 -07005058#include <type_traits>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005059
5060// Copyright 2007, Google Inc.
5061// All rights reserved.
5062//
5063// Redistribution and use in source and binary forms, with or without
5064// modification, are permitted provided that the following conditions are
5065// met:
5066//
5067// * Redistributions of source code must retain the above copyright
5068// notice, this list of conditions and the following disclaimer.
5069// * Redistributions in binary form must reproduce the above
5070// copyright notice, this list of conditions and the following disclaimer
5071// in the documentation and/or other materials provided with the
5072// distribution.
5073// * Neither the name of Google Inc. nor the names of its
5074// contributors may be used to endorse or promote products derived from
5075// this software without specific prior written permission.
5076//
5077// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5078// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5079// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5080// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5081// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5082// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5083// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5084// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5085// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5086// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5087// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5088
5089
5090// Google Test - The Google C++ Testing and Mocking Framework
Austin Schuh70cc9552019-01-21 19:46:48 -08005091//
5092// This file implements a universal value printer that can print a
5093// value of any type T:
5094//
5095// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
5096//
5097// A user can teach this function how to print a class type T by
5098// defining either operator<<() or PrintTo() in the namespace that
5099// defines T. More specifically, the FIRST defined function in the
5100// following list will be used (assuming T is defined in namespace
5101// foo):
5102//
5103// 1. foo::PrintTo(const T&, ostream*)
5104// 2. operator<<(ostream&, const T&) defined in either foo or the
5105// global namespace.
5106//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005107// However if T is an STL-style container then it is printed element-wise
5108// unless foo::PrintTo(const T&, ostream*) is defined. Note that
5109// operator<<() is ignored for container types.
5110//
Austin Schuh70cc9552019-01-21 19:46:48 -08005111// If none of the above is defined, it will print the debug string of
5112// the value if it is a protocol buffer, or print the raw bytes in the
5113// value otherwise.
5114//
5115// To aid debugging: when T is a reference type, the address of the
5116// value is also printed; when T is a (const) char pointer, both the
5117// pointer value and the NUL-terminated string it points to are
5118// printed.
5119//
5120// We also provide some convenient wrappers:
5121//
5122// // Prints a value to a string. For a (const or not) char
5123// // pointer, the NUL-terminated string (but not the pointer) is
5124// // printed.
5125// std::string ::testing::PrintToString(const T& value);
5126//
5127// // Prints a value tersely: for a reference type, the referenced
5128// // value (but not the address) is printed; for a (const or not) char
5129// // pointer, the NUL-terminated string (but not the pointer) is
5130// // printed.
5131// void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
5132//
5133// // Prints value using the type inferred by the compiler. The difference
5134// // from UniversalTersePrint() is that this function prints both the
5135// // pointer and the NUL-terminated string for a (const or not) char pointer.
5136// void ::testing::internal::UniversalPrint(const T& value, ostream*);
5137//
5138// // Prints the fields of a tuple tersely to a string vector, one
5139// // element for each field. Tuple support must be enabled in
5140// // gtest-port.h.
5141// std::vector<string> UniversalTersePrintTupleFieldsToStrings(
5142// const Tuple& value);
5143//
5144// Known limitation:
5145//
5146// The print primitives print the elements of an STL-style container
5147// using the compiler-inferred type of *iter where iter is a
5148// const_iterator of the container. When const_iterator is an input
5149// iterator but not a forward iterator, this inferred type may not
5150// match value_type, and the print output may be incorrect. In
5151// practice, this is rarely a problem as for most containers
5152// const_iterator is a forward iterator. We'll fix this if there's an
5153// actual need for it. Note that this fix cannot rely on value_type
5154// being defined as many user-defined container types don't have
5155// value_type.
5156
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005157// GOOGLETEST_CM0001 DO NOT DELETE
5158
Austin Schuh3de38b02024-06-25 18:25:10 -07005159#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
5160#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08005161
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005162#include <functional>
Austin Schuh3de38b02024-06-25 18:25:10 -07005163#include <memory>
Austin Schuh70cc9552019-01-21 19:46:48 -08005164#include <ostream> // NOLINT
5165#include <sstream>
5166#include <string>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005167#include <tuple>
5168#include <type_traits>
Austin Schuh70cc9552019-01-21 19:46:48 -08005169#include <utility>
5170#include <vector>
5171
Austin Schuh70cc9552019-01-21 19:46:48 -08005172
5173namespace testing {
5174
Austin Schuh3de38b02024-06-25 18:25:10 -07005175// Definitions in the internal* namespaces are subject to change without notice.
5176// DO NOT USE THEM IN USER CODE!
5177namespace internal {
Austin Schuh70cc9552019-01-21 19:46:48 -08005178
Austin Schuh3de38b02024-06-25 18:25:10 -07005179template <typename T>
5180void UniversalPrint(const T& value, ::std::ostream* os);
Austin Schuh70cc9552019-01-21 19:46:48 -08005181
Austin Schuh3de38b02024-06-25 18:25:10 -07005182// Used to print an STL-style container when the user doesn't define
5183// a PrintTo() for it.
5184struct ContainerPrinter {
5185 template <typename T,
5186 typename = typename std::enable_if<
5187 (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
5188 !IsRecursiveContainer<T>::value>::type>
5189 static void PrintValue(const T& container, std::ostream* os) {
5190 const size_t kMaxCount = 32; // The maximum number of elements to print.
5191 *os << '{';
5192 size_t count = 0;
5193 for (auto&& elem : container) {
5194 if (count > 0) {
5195 *os << ',';
5196 if (count == kMaxCount) { // Enough has been printed.
5197 *os << " ...";
5198 break;
5199 }
5200 }
5201 *os << ' ';
5202 // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
5203 // handle `elem` being a native array.
5204 internal::UniversalPrint(elem, os);
5205 ++count;
5206 }
Austin Schuh70cc9552019-01-21 19:46:48 -08005207
Austin Schuh3de38b02024-06-25 18:25:10 -07005208 if (count > 0) {
5209 *os << ' ';
5210 }
5211 *os << '}';
Austin Schuh70cc9552019-01-21 19:46:48 -08005212 }
5213};
5214
Austin Schuh3de38b02024-06-25 18:25:10 -07005215// Used to print a pointer that is neither a char pointer nor a member
5216// pointer, when the user doesn't define PrintTo() for it. (A member
5217// variable pointer or member function pointer doesn't really point to
5218// a location in the address space. Their representation is
5219// implementation-defined. Therefore they will be printed as raw
5220// bytes.)
5221struct FunctionPointerPrinter {
5222 template <typename T, typename = typename std::enable_if<
5223 std::is_function<T>::value>::type>
5224 static void PrintValue(T* p, ::std::ostream* os) {
5225 if (p == nullptr) {
5226 *os << "NULL";
5227 } else {
5228 // T is a function type, so '*os << p' doesn't do what we want
5229 // (it just prints p as bool). We want to print p as a const
5230 // void*.
5231 *os << reinterpret_cast<const void*>(p);
5232 }
5233 }
5234};
Austin Schuh70cc9552019-01-21 19:46:48 -08005235
Austin Schuh3de38b02024-06-25 18:25:10 -07005236struct PointerPrinter {
5237 template <typename T>
5238 static void PrintValue(T* p, ::std::ostream* os) {
5239 if (p == nullptr) {
5240 *os << "NULL";
5241 } else {
5242 // T is not a function type. We just call << to print p,
5243 // relying on ADL to pick up user-defined << for their pointer
5244 // types, if any.
5245 *os << p;
5246 }
5247 }
5248};
5249
5250namespace internal_stream_operator_without_lexical_name_lookup {
5251
5252// The presence of an operator<< here will terminate lexical scope lookup
5253// straight away (even though it cannot be a match because of its argument
5254// types). Thus, the two operator<< calls in StreamPrinter will find only ADL
5255// candidates.
5256struct LookupBlocker {};
5257void operator<<(LookupBlocker, LookupBlocker);
5258
5259struct StreamPrinter {
5260 template <typename T,
5261 // Don't accept member pointers here. We'd print them via implicit
5262 // conversion to bool, which isn't useful.
5263 typename = typename std::enable_if<
5264 !std::is_member_pointer<T>::value>::type,
5265 // Only accept types for which we can find a streaming operator via
5266 // ADL (possibly involving implicit conversions).
5267 typename = decltype(std::declval<std::ostream&>()
5268 << std::declval<const T&>())>
5269 static void PrintValue(const T& value, ::std::ostream* os) {
5270 // Call streaming operator found by ADL, possibly with implicit conversions
5271 // of the arguments.
5272 *os << value;
5273 }
5274};
5275
5276} // namespace internal_stream_operator_without_lexical_name_lookup
5277
5278struct ProtobufPrinter {
5279 // We print a protobuf using its ShortDebugString() when the string
5280 // doesn't exceed this many characters; otherwise we print it using
5281 // DebugString() for better readability.
5282 static const size_t kProtobufOneLinerMaxLength = 50;
5283
5284 template <typename T,
5285 typename = typename std::enable_if<
5286 internal::HasDebugStringAndShortDebugString<T>::value>::type>
Austin Schuh70cc9552019-01-21 19:46:48 -08005287 static void PrintValue(const T& value, ::std::ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005288 std::string pretty_str = value.ShortDebugString();
5289 if (pretty_str.length() > kProtobufOneLinerMaxLength) {
5290 pretty_str = "\n" + value.DebugString();
5291 }
Austin Schuh70cc9552019-01-21 19:46:48 -08005292 *os << ("<" + pretty_str + ">");
5293 }
5294};
5295
Austin Schuh3de38b02024-06-25 18:25:10 -07005296struct ConvertibleToIntegerPrinter {
Austin Schuh70cc9552019-01-21 19:46:48 -08005297 // Since T has no << operator or PrintTo() but can be implicitly
5298 // converted to BiggestInt, we print it as a BiggestInt.
5299 //
5300 // Most likely T is an enum type (either named or unnamed), in which
5301 // case printing it as an integer is the desired behavior. In case
5302 // T is not an enum, printing it as an integer is the best we can do
5303 // given that it has no user-defined printer.
Austin Schuh3de38b02024-06-25 18:25:10 -07005304 static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
5305 *os << value;
Austin Schuh70cc9552019-01-21 19:46:48 -08005306 }
5307};
5308
Austin Schuh3de38b02024-06-25 18:25:10 -07005309struct ConvertibleToStringViewPrinter {
5310#if GTEST_INTERNAL_HAS_STRING_VIEW
5311 static void PrintValue(internal::StringView value, ::std::ostream* os) {
5312 internal::UniversalPrint(value, os);
5313 }
5314#endif
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005315};
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005316
Austin Schuh70cc9552019-01-21 19:46:48 -08005317
Austin Schuh3de38b02024-06-25 18:25:10 -07005318// Prints the given number of bytes in the given object to the given
5319// ostream.
5320GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
5321 size_t count,
5322 ::std::ostream* os);
5323struct RawBytesPrinter {
5324 // SFINAE on `sizeof` to make sure we have a complete type.
5325 template <typename T, size_t = sizeof(T)>
5326 static void PrintValue(const T& value, ::std::ostream* os) {
5327 PrintBytesInObjectTo(
5328 static_cast<const unsigned char*>(
5329 // Load bearing cast to void* to support iOS
5330 reinterpret_cast<const void*>(std::addressof(value))),
5331 sizeof(value), os);
5332 }
5333};
Austin Schuh70cc9552019-01-21 19:46:48 -08005334
Austin Schuh3de38b02024-06-25 18:25:10 -07005335struct FallbackPrinter {
5336 template <typename T>
5337 static void PrintValue(const T&, ::std::ostream* os) {
5338 *os << "(incomplete type)";
5339 }
5340};
Austin Schuh70cc9552019-01-21 19:46:48 -08005341
Austin Schuh3de38b02024-06-25 18:25:10 -07005342// Try every printer in order and return the first one that works.
5343template <typename T, typename E, typename Printer, typename... Printers>
5344struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
5345
5346template <typename T, typename Printer, typename... Printers>
5347struct FindFirstPrinter<
5348 T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
5349 Printer, Printers...> {
5350 using type = Printer;
5351};
5352
5353// Select the best printer in the following order:
5354// - Print containers (they have begin/end/etc).
5355// - Print function pointers.
5356// - Print object pointers.
5357// - Use the stream operator, if available.
5358// - Print protocol buffers.
5359// - Print types convertible to BiggestInt.
5360// - Print types convertible to StringView, if available.
5361// - Fallback to printing the raw bytes of the object.
Austin Schuh70cc9552019-01-21 19:46:48 -08005362template <typename T>
Austin Schuh3de38b02024-06-25 18:25:10 -07005363void PrintWithFallback(const T& value, ::std::ostream* os) {
5364 using Printer = typename FindFirstPrinter<
5365 T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
5366 internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
5367 ProtobufPrinter, ConvertibleToIntegerPrinter,
5368 ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
5369 Printer::PrintValue(value, os);
Austin Schuh70cc9552019-01-21 19:46:48 -08005370}
5371
Austin Schuh70cc9552019-01-21 19:46:48 -08005372// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
5373// value of type ToPrint that is an operand of a comparison assertion
5374// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
5375// the comparison, and is used to help determine the best way to
5376// format the value. In particular, when the value is a C string
5377// (char pointer) and the other operand is an STL string object, we
5378// want to format the C string as a string, since we know it is
5379// compared by value with the string object. If the value is a char
5380// pointer but the other operand is not an STL string object, we don't
5381// know whether the pointer is supposed to point to a NUL-terminated
5382// string, and thus want to print it as a pointer to be safe.
5383//
5384// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
5385
5386// The default case.
5387template <typename ToPrint, typename OtherOperand>
5388class FormatForComparison {
5389 public:
5390 static ::std::string Format(const ToPrint& value) {
5391 return ::testing::PrintToString(value);
5392 }
5393};
5394
5395// Array.
5396template <typename ToPrint, size_t N, typename OtherOperand>
5397class FormatForComparison<ToPrint[N], OtherOperand> {
5398 public:
5399 static ::std::string Format(const ToPrint* value) {
5400 return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
5401 }
5402};
5403
5404// By default, print C string as pointers to be safe, as we don't know
5405// whether they actually point to a NUL-terminated string.
5406
5407#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
5408 template <typename OtherOperand> \
5409 class FormatForComparison<CharType*, OtherOperand> { \
5410 public: \
5411 static ::std::string Format(CharType* value) { \
5412 return ::testing::PrintToString(static_cast<const void*>(value)); \
5413 } \
5414 }
5415
5416GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
5417GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
5418GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
5419GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
Austin Schuh3de38b02024-06-25 18:25:10 -07005420#ifdef __cpp_char8_t
5421GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
5422GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
5423#endif
5424GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
5425GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
5426GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
5427GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
Austin Schuh70cc9552019-01-21 19:46:48 -08005428
5429#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
5430
5431// If a C string is compared with an STL string object, we know it's meant
5432// to point to a NUL-terminated string, and thus can print it as a string.
5433
5434#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
5435 template <> \
5436 class FormatForComparison<CharType*, OtherStringType> { \
5437 public: \
5438 static ::std::string Format(CharType* value) { \
5439 return ::testing::PrintToString(value); \
5440 } \
5441 }
5442
5443GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
5444GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
Austin Schuh3de38b02024-06-25 18:25:10 -07005445#ifdef __cpp_char8_t
5446GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
5447GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
Austin Schuh70cc9552019-01-21 19:46:48 -08005448#endif
Austin Schuh3de38b02024-06-25 18:25:10 -07005449GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
5450GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
5451GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
5452GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
Austin Schuh70cc9552019-01-21 19:46:48 -08005453
5454#if GTEST_HAS_STD_WSTRING
5455GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
5456GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
5457#endif
5458
5459#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
5460
5461// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
5462// operand to be used in a failure message. The type (but not value)
5463// of the other operand may affect the format. This allows us to
5464// print a char* as a raw pointer when it is compared against another
5465// char* or void*, and print it as a C string when it is compared
5466// against an std::string object, for example.
5467//
5468// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
5469template <typename T1, typename T2>
5470std::string FormatForComparisonFailureMessage(
5471 const T1& value, const T2& /* other_operand */) {
5472 return FormatForComparison<T1, T2>::Format(value);
5473}
5474
5475// UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
5476// value to the given ostream. The caller must ensure that
5477// 'ostream_ptr' is not NULL, or the behavior is undefined.
5478//
5479// We define UniversalPrinter as a class template (as opposed to a
5480// function template), as we need to partially specialize it for
5481// reference types, which cannot be done with function templates.
5482template <typename T>
5483class UniversalPrinter;
5484
Austin Schuh70cc9552019-01-21 19:46:48 -08005485// Prints the given value using the << operator if it has one;
5486// otherwise prints the bytes in it. This is what
5487// UniversalPrinter<T>::Print() does when PrintTo() is not specialized
5488// or overloaded for type T.
5489//
5490// A user can override this behavior for a class type Foo by defining
5491// an overload of PrintTo() in the namespace where Foo is defined. We
5492// give the user this option as sometimes defining a << operator for
5493// Foo is not desirable (e.g. the coding style may prevent doing it,
5494// or there is already a << operator but it doesn't do what the user
5495// wants).
5496template <typename T>
5497void PrintTo(const T& value, ::std::ostream* os) {
Austin Schuh3de38b02024-06-25 18:25:10 -07005498 internal::PrintWithFallback(value, os);
Austin Schuh70cc9552019-01-21 19:46:48 -08005499}
5500
5501// The following list of PrintTo() overloads tells
5502// UniversalPrinter<T>::Print() how to print standard types (built-in
5503// types, strings, plain arrays, and pointers).
5504
5505// Overloads for various char types.
5506GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
5507GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
5508inline void PrintTo(char c, ::std::ostream* os) {
5509 // When printing a plain char, we always treat it as unsigned. This
5510 // way, the output won't be affected by whether the compiler thinks
5511 // char is signed or not.
5512 PrintTo(static_cast<unsigned char>(c), os);
5513}
5514
5515// Overloads for other simple built-in types.
5516inline void PrintTo(bool x, ::std::ostream* os) {
5517 *os << (x ? "true" : "false");
5518}
5519
5520// Overload for wchar_t type.
5521// Prints a wchar_t as a symbol if it is printable or as its internal
5522// code otherwise and also as its decimal code (except for L'\0').
5523// The L'\0' char is printed as "L'\\0'". The decimal code is printed
5524// as signed integer when wchar_t is implemented by the compiler
5525// as a signed type and is printed as an unsigned integer when wchar_t
5526// is implemented as an unsigned type.
5527GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
5528
Austin Schuh3de38b02024-06-25 18:25:10 -07005529GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
5530inline void PrintTo(char16_t c, ::std::ostream* os) {
5531 PrintTo(ImplicitCast_<char32_t>(c), os);
5532}
5533#ifdef __cpp_char8_t
5534inline void PrintTo(char8_t c, ::std::ostream* os) {
5535 PrintTo(ImplicitCast_<char32_t>(c), os);
5536}
5537#endif
5538
Austin Schuh70cc9552019-01-21 19:46:48 -08005539// Overloads for C strings.
5540GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
5541inline void PrintTo(char* s, ::std::ostream* os) {
5542 PrintTo(ImplicitCast_<const char*>(s), os);
5543}
5544
5545// signed/unsigned char is often used for representing binary data, so
5546// we print pointers to it as void* to be safe.
5547inline void PrintTo(const signed char* s, ::std::ostream* os) {
5548 PrintTo(ImplicitCast_<const void*>(s), os);
5549}
5550inline void PrintTo(signed char* s, ::std::ostream* os) {
5551 PrintTo(ImplicitCast_<const void*>(s), os);
5552}
5553inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
5554 PrintTo(ImplicitCast_<const void*>(s), os);
5555}
5556inline void PrintTo(unsigned char* s, ::std::ostream* os) {
5557 PrintTo(ImplicitCast_<const void*>(s), os);
5558}
Austin Schuh3de38b02024-06-25 18:25:10 -07005559#ifdef __cpp_char8_t
5560// Overloads for u8 strings.
5561GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
5562inline void PrintTo(char8_t* s, ::std::ostream* os) {
5563 PrintTo(ImplicitCast_<const char8_t*>(s), os);
5564}
5565#endif
5566// Overloads for u16 strings.
5567GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);
5568inline void PrintTo(char16_t* s, ::std::ostream* os) {
5569 PrintTo(ImplicitCast_<const char16_t*>(s), os);
5570}
5571// Overloads for u32 strings.
5572GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);
5573inline void PrintTo(char32_t* s, ::std::ostream* os) {
5574 PrintTo(ImplicitCast_<const char32_t*>(s), os);
5575}
Austin Schuh70cc9552019-01-21 19:46:48 -08005576
5577// MSVC can be configured to define wchar_t as a typedef of unsigned
5578// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
5579// type. When wchar_t is a typedef, defining an overload for const
5580// wchar_t* would cause unsigned short* be printed as a wide string,
5581// possibly causing invalid memory accesses.
5582#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
5583// Overloads for wide C strings
5584GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
5585inline void PrintTo(wchar_t* s, ::std::ostream* os) {
5586 PrintTo(ImplicitCast_<const wchar_t*>(s), os);
5587}
5588#endif
5589
5590// Overload for C arrays. Multi-dimensional arrays are printed
5591// properly.
5592
5593// Prints the given number of elements in an array, without printing
5594// the curly braces.
5595template <typename T>
5596void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
5597 UniversalPrint(a[0], os);
5598 for (size_t i = 1; i != count; i++) {
5599 *os << ", ";
5600 UniversalPrint(a[i], os);
5601 }
5602}
5603
Austin Schuh3de38b02024-06-25 18:25:10 -07005604// Overloads for ::std::string.
Austin Schuh70cc9552019-01-21 19:46:48 -08005605GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
5606inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
5607 PrintStringTo(s, os);
5608}
5609
Austin Schuh3de38b02024-06-25 18:25:10 -07005610// Overloads for ::std::u8string
5611#ifdef __cpp_char8_t
5612GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
5613inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
5614 PrintU8StringTo(s, os);
Austin Schuh70cc9552019-01-21 19:46:48 -08005615}
Austin Schuh3de38b02024-06-25 18:25:10 -07005616#endif
Austin Schuh70cc9552019-01-21 19:46:48 -08005617
Austin Schuh3de38b02024-06-25 18:25:10 -07005618// Overloads for ::std::u16string
5619GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
5620inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
5621 PrintU16StringTo(s, os);
5622}
5623
5624// Overloads for ::std::u32string
5625GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
5626inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
5627 PrintU32StringTo(s, os);
5628}
5629
5630// Overloads for ::std::wstring.
Austin Schuh70cc9552019-01-21 19:46:48 -08005631#if GTEST_HAS_STD_WSTRING
5632GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
5633inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
5634 PrintWideStringTo(s, os);
5635}
5636#endif // GTEST_HAS_STD_WSTRING
5637
Austin Schuh3de38b02024-06-25 18:25:10 -07005638#if GTEST_INTERNAL_HAS_STRING_VIEW
5639// Overload for internal::StringView.
5640inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005641 PrintTo(::std::string(sp), os);
5642}
Austin Schuh3de38b02024-06-25 18:25:10 -07005643#endif // GTEST_INTERNAL_HAS_STRING_VIEW
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005644
5645inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
5646
5647template <typename T>
5648void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
5649 UniversalPrinter<T&>::Print(ref.get(), os);
5650}
5651
Austin Schuh3de38b02024-06-25 18:25:10 -07005652inline const void* VoidifyPointer(const void* p) { return p; }
5653inline const void* VoidifyPointer(volatile const void* p) {
5654 return const_cast<const void*>(p);
5655}
5656
5657template <typename T, typename Ptr>
5658void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
5659 if (ptr == nullptr) {
5660 *os << "(nullptr)";
5661 } else {
5662 // We can't print the value. Just print the pointer..
5663 *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
5664 }
5665}
5666template <typename T, typename Ptr,
5667 typename = typename std::enable_if<!std::is_void<T>::value &&
5668 !std::is_array<T>::value>::type>
5669void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
5670 if (ptr == nullptr) {
5671 *os << "(nullptr)";
5672 } else {
5673 *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
5674 UniversalPrinter<T>::Print(*ptr, os);
5675 *os << ")";
5676 }
5677}
5678
5679template <typename T, typename D>
5680void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
5681 (PrintSmartPointer<T>)(ptr, os, 0);
5682}
5683
5684template <typename T>
5685void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
5686 (PrintSmartPointer<T>)(ptr, os, 0);
5687}
5688
Austin Schuh70cc9552019-01-21 19:46:48 -08005689// Helper function for printing a tuple. T must be instantiated with
5690// a tuple type.
5691template <typename T>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005692void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
5693 ::std::ostream*) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08005694
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005695template <typename T, size_t I>
5696void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
5697 ::std::ostream* os) {
5698 PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
5699 GTEST_INTENTIONAL_CONST_COND_PUSH_()
5700 if (I > 1) {
5701 GTEST_INTENTIONAL_CONST_COND_POP_()
5702 *os << ", ";
5703 }
5704 UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
5705 std::get<I - 1>(t), os);
Austin Schuh70cc9552019-01-21 19:46:48 -08005706}
5707
Austin Schuh70cc9552019-01-21 19:46:48 -08005708template <typename... Types>
5709void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005710 *os << "(";
5711 PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
5712 *os << ")";
Austin Schuh70cc9552019-01-21 19:46:48 -08005713}
Austin Schuh70cc9552019-01-21 19:46:48 -08005714
5715// Overload for std::pair.
5716template <typename T1, typename T2>
5717void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
5718 *os << '(';
5719 // We cannot use UniversalPrint(value.first, os) here, as T1 may be
5720 // a reference type. The same for printing value.second.
5721 UniversalPrinter<T1>::Print(value.first, os);
5722 *os << ", ";
5723 UniversalPrinter<T2>::Print(value.second, os);
5724 *os << ')';
5725}
5726
5727// Implements printing a non-reference type T by letting the compiler
5728// pick the right overload of PrintTo() for T.
5729template <typename T>
5730class UniversalPrinter {
5731 public:
5732 // MSVC warns about adding const to a function type, so we want to
5733 // disable the warning.
5734 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
5735
5736 // Note: we deliberately don't call this PrintTo(), as that name
5737 // conflicts with ::testing::internal::PrintTo in the body of the
5738 // function.
5739 static void Print(const T& value, ::std::ostream* os) {
5740 // By default, ::testing::internal::PrintTo() is used for printing
5741 // the value.
5742 //
5743 // Thanks to Koenig look-up, if T is a class and has its own
5744 // PrintTo() function defined in its namespace, that function will
5745 // be visible here. Since it is more specific than the generic ones
5746 // in ::testing::internal, it will be picked by the compiler in the
5747 // following statement - exactly what we want.
5748 PrintTo(value, os);
5749 }
5750
5751 GTEST_DISABLE_MSC_WARNINGS_POP_()
5752};
5753
Austin Schuh3de38b02024-06-25 18:25:10 -07005754// Remove any const-qualifiers before passing a type to UniversalPrinter.
5755template <typename T>
5756class UniversalPrinter<const T> : public UniversalPrinter<T> {};
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005757
Austin Schuh3de38b02024-06-25 18:25:10 -07005758#if GTEST_INTERNAL_HAS_ANY
5759
5760// Printer for std::any / absl::any
5761
5762template <>
5763class UniversalPrinter<Any> {
5764 public:
5765 static void Print(const Any& value, ::std::ostream* os) {
5766 if (value.has_value()) {
5767 *os << "value of type " << GetTypeName(value);
5768 } else {
5769 *os << "no value";
5770 }
5771 }
5772
5773 private:
5774 static std::string GetTypeName(const Any& value) {
5775#if GTEST_HAS_RTTI
5776 return internal::GetTypeName(value.type());
5777#else
5778 static_cast<void>(value); // possibly unused
5779 return "<unknown_type>";
5780#endif // GTEST_HAS_RTTI
5781 }
5782};
5783
5784#endif // GTEST_INTERNAL_HAS_ANY
5785
5786#if GTEST_INTERNAL_HAS_OPTIONAL
5787
5788// Printer for std::optional / absl::optional
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005789
5790template <typename T>
Austin Schuh3de38b02024-06-25 18:25:10 -07005791class UniversalPrinter<Optional<T>> {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005792 public:
Austin Schuh3de38b02024-06-25 18:25:10 -07005793 static void Print(const Optional<T>& value, ::std::ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005794 *os << '(';
5795 if (!value) {
5796 *os << "nullopt";
5797 } else {
5798 UniversalPrint(*value, os);
5799 }
5800 *os << ')';
5801 }
5802};
5803
Austin Schuh3de38b02024-06-25 18:25:10 -07005804#endif // GTEST_INTERNAL_HAS_OPTIONAL
5805
5806#if GTEST_INTERNAL_HAS_VARIANT
5807
5808// Printer for std::variant / absl::variant
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005809
5810template <typename... T>
Austin Schuh3de38b02024-06-25 18:25:10 -07005811class UniversalPrinter<Variant<T...>> {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005812 public:
Austin Schuh3de38b02024-06-25 18:25:10 -07005813 static void Print(const Variant<T...>& value, ::std::ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005814 *os << '(';
Austin Schuh3de38b02024-06-25 18:25:10 -07005815#if GTEST_HAS_ABSL
5816 absl::visit(Visitor{os, value.index()}, value);
5817#else
5818 std::visit(Visitor{os, value.index()}, value);
5819#endif // GTEST_HAS_ABSL
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005820 *os << ')';
5821 }
5822
5823 private:
5824 struct Visitor {
5825 template <typename U>
5826 void operator()(const U& u) const {
Austin Schuh3de38b02024-06-25 18:25:10 -07005827 *os << "'" << GetTypeName<U>() << "(index = " << index
5828 << ")' with value ";
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005829 UniversalPrint(u, os);
5830 }
5831 ::std::ostream* os;
Austin Schuh3de38b02024-06-25 18:25:10 -07005832 std::size_t index;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005833 };
5834};
5835
Austin Schuh3de38b02024-06-25 18:25:10 -07005836#endif // GTEST_INTERNAL_HAS_VARIANT
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005837
Austin Schuh70cc9552019-01-21 19:46:48 -08005838// UniversalPrintArray(begin, len, os) prints an array of 'len'
5839// elements, starting at address 'begin'.
5840template <typename T>
5841void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
5842 if (len == 0) {
5843 *os << "{}";
5844 } else {
5845 *os << "{ ";
5846 const size_t kThreshold = 18;
5847 const size_t kChunkSize = 8;
5848 // If the array has more than kThreshold elements, we'll have to
5849 // omit some details by printing only the first and the last
5850 // kChunkSize elements.
Austin Schuh70cc9552019-01-21 19:46:48 -08005851 if (len <= kThreshold) {
5852 PrintRawArrayTo(begin, len, os);
5853 } else {
5854 PrintRawArrayTo(begin, kChunkSize, os);
5855 *os << ", ..., ";
5856 PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
5857 }
5858 *os << " }";
5859 }
5860}
5861// This overload prints a (const) char array compactly.
5862GTEST_API_ void UniversalPrintArray(
5863 const char* begin, size_t len, ::std::ostream* os);
5864
Austin Schuh3de38b02024-06-25 18:25:10 -07005865#ifdef __cpp_char8_t
5866// This overload prints a (const) char8_t array compactly.
5867GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
5868 ::std::ostream* os);
5869#endif
5870
5871// This overload prints a (const) char16_t array compactly.
5872GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
5873 ::std::ostream* os);
5874
5875// This overload prints a (const) char32_t array compactly.
5876GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
5877 ::std::ostream* os);
5878
Austin Schuh70cc9552019-01-21 19:46:48 -08005879// This overload prints a (const) wchar_t array compactly.
5880GTEST_API_ void UniversalPrintArray(
5881 const wchar_t* begin, size_t len, ::std::ostream* os);
5882
5883// Implements printing an array type T[N].
5884template <typename T, size_t N>
5885class UniversalPrinter<T[N]> {
5886 public:
5887 // Prints the given array, omitting some elements when there are too
5888 // many.
5889 static void Print(const T (&a)[N], ::std::ostream* os) {
5890 UniversalPrintArray(a, N, os);
5891 }
5892};
5893
5894// Implements printing a reference type T&.
5895template <typename T>
5896class UniversalPrinter<T&> {
5897 public:
5898 // MSVC warns about adding const to a function type, so we want to
5899 // disable the warning.
5900 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
5901
5902 static void Print(const T& value, ::std::ostream* os) {
5903 // Prints the address of the value. We use reinterpret_cast here
5904 // as static_cast doesn't compile when T is a function type.
5905 *os << "@" << reinterpret_cast<const void*>(&value) << " ";
5906
5907 // Then prints the value itself.
5908 UniversalPrint(value, os);
5909 }
5910
5911 GTEST_DISABLE_MSC_WARNINGS_POP_()
5912};
5913
5914// Prints a value tersely: for a reference type, the referenced value
5915// (but not the address) is printed; for a (const) char pointer, the
5916// NUL-terminated string (but not the pointer) is printed.
5917
5918template <typename T>
5919class UniversalTersePrinter {
5920 public:
5921 static void Print(const T& value, ::std::ostream* os) {
5922 UniversalPrint(value, os);
5923 }
5924};
5925template <typename T>
5926class UniversalTersePrinter<T&> {
5927 public:
5928 static void Print(const T& value, ::std::ostream* os) {
5929 UniversalPrint(value, os);
5930 }
5931};
5932template <typename T, size_t N>
5933class UniversalTersePrinter<T[N]> {
5934 public:
5935 static void Print(const T (&value)[N], ::std::ostream* os) {
5936 UniversalPrinter<T[N]>::Print(value, os);
5937 }
5938};
5939template <>
5940class UniversalTersePrinter<const char*> {
5941 public:
5942 static void Print(const char* str, ::std::ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005943 if (str == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08005944 *os << "NULL";
5945 } else {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08005946 UniversalPrint(std::string(str), os);
Austin Schuh70cc9552019-01-21 19:46:48 -08005947 }
5948 }
5949};
5950template <>
Austin Schuh3de38b02024-06-25 18:25:10 -07005951class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
5952};
5953
5954#ifdef __cpp_char8_t
5955template <>
5956class UniversalTersePrinter<const char8_t*> {
Austin Schuh70cc9552019-01-21 19:46:48 -08005957 public:
Austin Schuh3de38b02024-06-25 18:25:10 -07005958 static void Print(const char8_t* str, ::std::ostream* os) {
5959 if (str == nullptr) {
5960 *os << "NULL";
5961 } else {
5962 UniversalPrint(::std::u8string(str), os);
5963 }
Austin Schuh70cc9552019-01-21 19:46:48 -08005964 }
5965};
Austin Schuh3de38b02024-06-25 18:25:10 -07005966template <>
5967class UniversalTersePrinter<char8_t*>
5968 : public UniversalTersePrinter<const char8_t*> {};
5969#endif
5970
5971template <>
5972class UniversalTersePrinter<const char16_t*> {
5973 public:
5974 static void Print(const char16_t* str, ::std::ostream* os) {
5975 if (str == nullptr) {
5976 *os << "NULL";
5977 } else {
5978 UniversalPrint(::std::u16string(str), os);
5979 }
5980 }
5981};
5982template <>
5983class UniversalTersePrinter<char16_t*>
5984 : public UniversalTersePrinter<const char16_t*> {};
5985
5986template <>
5987class UniversalTersePrinter<const char32_t*> {
5988 public:
5989 static void Print(const char32_t* str, ::std::ostream* os) {
5990 if (str == nullptr) {
5991 *os << "NULL";
5992 } else {
5993 UniversalPrint(::std::u32string(str), os);
5994 }
5995 }
5996};
5997template <>
5998class UniversalTersePrinter<char32_t*>
5999 : public UniversalTersePrinter<const char32_t*> {};
Austin Schuh70cc9552019-01-21 19:46:48 -08006000
6001#if GTEST_HAS_STD_WSTRING
6002template <>
6003class UniversalTersePrinter<const wchar_t*> {
6004 public:
6005 static void Print(const wchar_t* str, ::std::ostream* os) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006006 if (str == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -08006007 *os << "NULL";
6008 } else {
6009 UniversalPrint(::std::wstring(str), os);
6010 }
6011 }
6012};
6013#endif
6014
6015template <>
6016class UniversalTersePrinter<wchar_t*> {
6017 public:
6018 static void Print(wchar_t* str, ::std::ostream* os) {
6019 UniversalTersePrinter<const wchar_t*>::Print(str, os);
6020 }
6021};
6022
6023template <typename T>
6024void UniversalTersePrint(const T& value, ::std::ostream* os) {
6025 UniversalTersePrinter<T>::Print(value, os);
6026}
6027
6028// Prints a value using the type inferred by the compiler. The
6029// difference between this and UniversalTersePrint() is that for a
6030// (const) char pointer, this prints both the pointer and the
6031// NUL-terminated string.
6032template <typename T>
6033void UniversalPrint(const T& value, ::std::ostream* os) {
6034 // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
6035 // UniversalPrinter with T directly.
6036 typedef T T1;
6037 UniversalPrinter<T1>::Print(value, os);
6038}
6039
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006040typedef ::std::vector< ::std::string> Strings;
Austin Schuh70cc9552019-01-21 19:46:48 -08006041
6042 // Tersely prints the first N fields of a tuple to a string vector,
6043 // one element for each field.
Austin Schuh70cc9552019-01-21 19:46:48 -08006044template <typename Tuple>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006045void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
6046 Strings*) {}
6047template <typename Tuple, size_t I>
6048void TersePrintPrefixToStrings(const Tuple& t,
6049 std::integral_constant<size_t, I>,
6050 Strings* strings) {
6051 TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
6052 strings);
6053 ::std::stringstream ss;
6054 UniversalTersePrint(std::get<I - 1>(t), &ss);
6055 strings->push_back(ss.str());
Austin Schuh70cc9552019-01-21 19:46:48 -08006056}
6057
6058// Prints the fields of a tuple tersely to a string vector, one
6059// element for each field. See the comment before
6060// UniversalTersePrint() for how we define "tersely".
6061template <typename Tuple>
6062Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
6063 Strings result;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006064 TersePrintPrefixToStrings(
6065 value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
6066 &result);
Austin Schuh70cc9552019-01-21 19:46:48 -08006067 return result;
6068}
Austin Schuh70cc9552019-01-21 19:46:48 -08006069
6070} // namespace internal
6071
6072template <typename T>
6073::std::string PrintToString(const T& value) {
6074 ::std::stringstream ss;
6075 internal::UniversalTersePrinter<T>::Print(value, &ss);
6076 return ss.str();
6077}
6078
6079} // namespace testing
6080
6081// Include any custom printer added by the local installation.
6082// We must include this header at the end to make sure it can use the
6083// declarations from this file.
6084// Copyright 2015, Google Inc.
6085// All rights reserved.
6086//
6087// Redistribution and use in source and binary forms, with or without
6088// modification, are permitted provided that the following conditions are
6089// met:
6090//
6091// * Redistributions of source code must retain the above copyright
6092// notice, this list of conditions and the following disclaimer.
6093// * Redistributions in binary form must reproduce the above
6094// copyright notice, this list of conditions and the following disclaimer
6095// in the documentation and/or other materials provided with the
6096// distribution.
6097// * Neither the name of Google Inc. nor the names of its
6098// contributors may be used to endorse or promote products derived from
6099// this software without specific prior written permission.
6100//
6101// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6102// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6103// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6104// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6105// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6106// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6107// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6108// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6109// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6110// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6111// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6112//
6113// This file provides an injection point for custom printers in a local
6114// installation of gTest.
6115// It will be included from gtest-printers.h and the overrides in this file
6116// will be visible to everyone.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006117//
6118// Injection point for custom user configurations. See README for details
Austin Schuh70cc9552019-01-21 19:46:48 -08006119//
6120// ** Custom implementation starts here **
6121
Austin Schuh3de38b02024-06-25 18:25:10 -07006122#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
6123#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08006124
Austin Schuh3de38b02024-06-25 18:25:10 -07006125#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08006126
Austin Schuh3de38b02024-06-25 18:25:10 -07006127#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
6128
6129// MSVC warning C5046 is new as of VS2017 version 15.8.
6130#if defined(_MSC_VER) && _MSC_VER >= 1915
6131#define GTEST_MAYBE_5046_ 5046
6132#else
6133#define GTEST_MAYBE_5046_
6134#endif
Austin Schuh70cc9552019-01-21 19:46:48 -08006135
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006136GTEST_DISABLE_MSC_WARNINGS_PUSH_(
Austin Schuh3de38b02024-06-25 18:25:10 -07006137 4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
6138 clients of class B */
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006139 /* Symbol involving type with internal linkage not defined */)
Austin Schuh70cc9552019-01-21 19:46:48 -08006140
6141namespace testing {
6142
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006143// To implement a matcher Foo for type T, define:
Austin Schuh3de38b02024-06-25 18:25:10 -07006144// 1. a class FooMatcherMatcher that implements the matcher interface:
6145// using is_gtest_matcher = void;
6146// bool MatchAndExplain(const T&, std::ostream*);
6147// (MatchResultListener* can also be used instead of std::ostream*)
6148// void DescribeTo(std::ostream*);
6149// void DescribeNegationTo(std::ostream*);
6150//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006151// 2. a factory function that creates a Matcher<T> object from a
Austin Schuh3de38b02024-06-25 18:25:10 -07006152// FooMatcherMatcher.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006153
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006154class MatchResultListener {
6155 public:
6156 // Creates a listener object with the given underlying ostream. The
6157 // listener does not own the ostream, and does not dereference it
6158 // in the constructor or destructor.
6159 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
6160 virtual ~MatchResultListener() = 0; // Makes this class abstract.
6161
6162 // Streams x to the underlying ostream; does nothing if the ostream
6163 // is NULL.
6164 template <typename T>
6165 MatchResultListener& operator<<(const T& x) {
6166 if (stream_ != nullptr) *stream_ << x;
6167 return *this;
6168 }
6169
6170 // Returns the underlying ostream.
6171 ::std::ostream* stream() { return stream_; }
6172
Austin Schuh3de38b02024-06-25 18:25:10 -07006173 // Returns true if and only if the listener is interested in an explanation
6174 // of the match result. A matcher's MatchAndExplain() method can use
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006175 // this information to avoid generating the explanation when no one
6176 // intends to hear it.
6177 bool IsInterested() const { return stream_ != nullptr; }
6178
6179 private:
6180 ::std::ostream* const stream_;
6181
6182 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
6183};
6184
6185inline MatchResultListener::~MatchResultListener() {
6186}
6187
6188// An instance of a subclass of this knows how to describe itself as a
6189// matcher.
Austin Schuh3de38b02024-06-25 18:25:10 -07006190class GTEST_API_ MatcherDescriberInterface {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006191 public:
6192 virtual ~MatcherDescriberInterface() {}
6193
6194 // Describes this matcher to an ostream. The function should print
6195 // a verb phrase that describes the property a value matching this
6196 // matcher should have. The subject of the verb phrase is the value
6197 // being matched. For example, the DescribeTo() method of the Gt(7)
6198 // matcher prints "is greater than 7".
6199 virtual void DescribeTo(::std::ostream* os) const = 0;
6200
6201 // Describes the negation of this matcher to an ostream. For
6202 // example, if the description of this matcher is "is greater than
6203 // 7", the negated description could be "is not greater than 7".
6204 // You are not required to override this when implementing
6205 // MatcherInterface, but it is highly advised so that your matcher
6206 // can produce good error messages.
6207 virtual void DescribeNegationTo(::std::ostream* os) const {
6208 *os << "not (";
6209 DescribeTo(os);
6210 *os << ")";
6211 }
6212};
6213
6214// The implementation of a matcher.
6215template <typename T>
6216class MatcherInterface : public MatcherDescriberInterface {
6217 public:
Austin Schuh3de38b02024-06-25 18:25:10 -07006218 // Returns true if and only if the matcher matches x; also explains the
6219 // match result to 'listener' if necessary (see the next paragraph), in
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006220 // the form of a non-restrictive relative clause ("which ...",
6221 // "whose ...", etc) that describes x. For example, the
6222 // MatchAndExplain() method of the Pointee(...) matcher should
6223 // generate an explanation like "which points to ...".
6224 //
6225 // Implementations of MatchAndExplain() should add an explanation of
6226 // the match result *if and only if* they can provide additional
6227 // information that's not already present (or not obvious) in the
6228 // print-out of x and the matcher's description. Whether the match
6229 // succeeds is not a factor in deciding whether an explanation is
6230 // needed, as sometimes the caller needs to print a failure message
6231 // when the match succeeds (e.g. when the matcher is used inside
6232 // Not()).
6233 //
6234 // For example, a "has at least 10 elements" matcher should explain
6235 // what the actual element count is, regardless of the match result,
6236 // as it is useful information to the reader; on the other hand, an
6237 // "is empty" matcher probably only needs to explain what the actual
6238 // size is when the match fails, as it's redundant to say that the
6239 // size is 0 when the value is already known to be empty.
6240 //
6241 // You should override this method when defining a new matcher.
6242 //
6243 // It's the responsibility of the caller (Google Test) to guarantee
6244 // that 'listener' is not NULL. This helps to simplify a matcher's
6245 // implementation when it doesn't care about the performance, as it
6246 // can talk to 'listener' without checking its validity first.
6247 // However, in order to implement dummy listeners efficiently,
6248 // listener->stream() may be NULL.
6249 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
6250
6251 // Inherits these methods from MatcherDescriberInterface:
6252 // virtual void DescribeTo(::std::ostream* os) const = 0;
6253 // virtual void DescribeNegationTo(::std::ostream* os) const;
6254};
6255
6256namespace internal {
6257
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006258struct AnyEq {
6259 template <typename A, typename B>
6260 bool operator()(const A& a, const B& b) const { return a == b; }
6261};
6262struct AnyNe {
6263 template <typename A, typename B>
6264 bool operator()(const A& a, const B& b) const { return a != b; }
6265};
6266struct AnyLt {
6267 template <typename A, typename B>
6268 bool operator()(const A& a, const B& b) const { return a < b; }
6269};
6270struct AnyGt {
6271 template <typename A, typename B>
6272 bool operator()(const A& a, const B& b) const { return a > b; }
6273};
6274struct AnyLe {
6275 template <typename A, typename B>
6276 bool operator()(const A& a, const B& b) const { return a <= b; }
6277};
6278struct AnyGe {
6279 template <typename A, typename B>
6280 bool operator()(const A& a, const B& b) const { return a >= b; }
6281};
6282
6283// A match result listener that ignores the explanation.
6284class DummyMatchResultListener : public MatchResultListener {
6285 public:
6286 DummyMatchResultListener() : MatchResultListener(nullptr) {}
6287
6288 private:
6289 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
6290};
6291
6292// A match result listener that forwards the explanation to a given
6293// ostream. The difference between this and MatchResultListener is
6294// that the former is concrete.
6295class StreamMatchResultListener : public MatchResultListener {
6296 public:
6297 explicit StreamMatchResultListener(::std::ostream* os)
6298 : MatchResultListener(os) {}
6299
6300 private:
6301 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
6302};
6303
Austin Schuh3de38b02024-06-25 18:25:10 -07006304struct SharedPayloadBase {
6305 std::atomic<int> ref{1};
6306 void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
6307 bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
6308};
6309
6310template <typename T>
6311struct SharedPayload : SharedPayloadBase {
6312 explicit SharedPayload(const T& v) : value(v) {}
6313 explicit SharedPayload(T&& v) : value(std::move(v)) {}
6314
6315 static void Destroy(SharedPayloadBase* shared) {
6316 delete static_cast<SharedPayload*>(shared);
6317 }
6318
6319 T value;
6320};
6321
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006322// An internal class for implementing Matcher<T>, which will derive
6323// from it. We put functionalities common to all Matcher<T>
6324// specializations here to avoid code duplication.
6325template <typename T>
Austin Schuh3de38b02024-06-25 18:25:10 -07006326class MatcherBase : private MatcherDescriberInterface {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006327 public:
Austin Schuh3de38b02024-06-25 18:25:10 -07006328 // Returns true if and only if the matcher matches x; also explains the
6329 // match result to 'listener'.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006330 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
Austin Schuh3de38b02024-06-25 18:25:10 -07006331 GTEST_CHECK_(vtable_ != nullptr);
6332 return vtable_->match_and_explain(*this, x, listener);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006333 }
6334
Austin Schuh3de38b02024-06-25 18:25:10 -07006335 // Returns true if and only if this matcher matches x.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006336 bool Matches(const T& x) const {
6337 DummyMatchResultListener dummy;
6338 return MatchAndExplain(x, &dummy);
6339 }
6340
6341 // Describes this matcher to an ostream.
Austin Schuh3de38b02024-06-25 18:25:10 -07006342 void DescribeTo(::std::ostream* os) const final {
6343 GTEST_CHECK_(vtable_ != nullptr);
6344 vtable_->describe(*this, os, false);
6345 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006346
6347 // Describes the negation of this matcher to an ostream.
Austin Schuh3de38b02024-06-25 18:25:10 -07006348 void DescribeNegationTo(::std::ostream* os) const final {
6349 GTEST_CHECK_(vtable_ != nullptr);
6350 vtable_->describe(*this, os, true);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006351 }
6352
6353 // Explains why x matches, or doesn't match, the matcher.
6354 void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
6355 StreamMatchResultListener listener(os);
6356 MatchAndExplain(x, &listener);
6357 }
6358
6359 // Returns the describer for this matcher object; retains ownership
6360 // of the describer, which is only guaranteed to be alive when
6361 // this matcher object is alive.
6362 const MatcherDescriberInterface* GetDescriber() const {
Austin Schuh3de38b02024-06-25 18:25:10 -07006363 if (vtable_ == nullptr) return nullptr;
6364 return vtable_->get_describer(*this);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006365 }
6366
6367 protected:
Austin Schuh3de38b02024-06-25 18:25:10 -07006368 MatcherBase() : vtable_(nullptr) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006369
6370 // Constructs a matcher from its implementation.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006371 template <typename U>
Austin Schuh3de38b02024-06-25 18:25:10 -07006372 explicit MatcherBase(const MatcherInterface<U>* impl) {
6373 Init(impl);
6374 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006375
Austin Schuh3de38b02024-06-25 18:25:10 -07006376 template <typename M, typename = typename std::remove_reference<
6377 M>::type::is_gtest_matcher>
6378 MatcherBase(M&& m) { // NOLINT
6379 Init(std::forward<M>(m));
6380 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006381
Austin Schuh3de38b02024-06-25 18:25:10 -07006382 MatcherBase(const MatcherBase& other)
6383 : vtable_(other.vtable_), buffer_(other.buffer_) {
6384 if (IsShared()) buffer_.shared->Ref();
6385 }
6386
6387 MatcherBase& operator=(const MatcherBase& other) {
6388 if (this == &other) return *this;
6389 Destroy();
6390 vtable_ = other.vtable_;
6391 buffer_ = other.buffer_;
6392 if (IsShared()) buffer_.shared->Ref();
6393 return *this;
6394 }
6395
6396 MatcherBase(MatcherBase&& other)
6397 : vtable_(other.vtable_), buffer_(other.buffer_) {
6398 other.vtable_ = nullptr;
6399 }
6400
6401 MatcherBase& operator=(MatcherBase&& other) {
6402 if (this == &other) return *this;
6403 Destroy();
6404 vtable_ = other.vtable_;
6405 buffer_ = other.buffer_;
6406 other.vtable_ = nullptr;
6407 return *this;
6408 }
6409
6410 ~MatcherBase() override { Destroy(); }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006411
6412 private:
Austin Schuh3de38b02024-06-25 18:25:10 -07006413 struct VTable {
6414 bool (*match_and_explain)(const MatcherBase&, const T&,
6415 MatchResultListener*);
6416 void (*describe)(const MatcherBase&, std::ostream*, bool negation);
6417 // Returns the captured object if it implements the interface, otherwise
6418 // returns the MatcherBase itself.
6419 const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
6420 // Called on shared instances when the reference count reaches 0.
6421 void (*shared_destroy)(SharedPayloadBase*);
6422 };
6423
6424 bool IsShared() const {
6425 return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
6426 }
6427
6428 // If the implementation uses a listener, call that.
6429 template <typename P>
6430 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
6431 MatchResultListener* listener)
6432 -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
6433 return P::Get(m).MatchAndExplain(value, listener->stream());
6434 }
6435
6436 template <typename P>
6437 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
6438 MatchResultListener* listener)
6439 -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
6440 return P::Get(m).MatchAndExplain(value, listener);
6441 }
6442
6443 template <typename P>
6444 static void DescribeImpl(const MatcherBase& m, std::ostream* os,
6445 bool negation) {
6446 if (negation) {
6447 P::Get(m).DescribeNegationTo(os);
6448 } else {
6449 P::Get(m).DescribeTo(os);
6450 }
6451 }
6452
6453 template <typename P>
6454 static const MatcherDescriberInterface* GetDescriberImpl(
6455 const MatcherBase& m) {
6456 // If the impl is a MatcherDescriberInterface, then return it.
6457 // Otherwise use MatcherBase itself.
6458 // This allows us to implement the GetDescriber() function without support
6459 // from the impl, but some users really want to get their impl back when
6460 // they call GetDescriber().
6461 // We use std::get on a tuple as a workaround of not having `if constexpr`.
6462 return std::get<(
6463 std::is_convertible<decltype(&P::Get(m)),
6464 const MatcherDescriberInterface*>::value
6465 ? 1
6466 : 0)>(std::make_tuple(&m, &P::Get(m)));
6467 }
6468
6469 template <typename P>
6470 const VTable* GetVTable() {
6471 static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
6472 &DescribeImpl<P>, &GetDescriberImpl<P>,
6473 P::shared_destroy};
6474 return &kVTable;
6475 }
6476
6477 union Buffer {
6478 // Add some types to give Buffer some common alignment/size use cases.
6479 void* ptr;
6480 double d;
6481 int64_t i;
6482 // And add one for the out-of-line cases.
6483 SharedPayloadBase* shared;
6484 };
6485
6486 void Destroy() {
6487 if (IsShared() && buffer_.shared->Unref()) {
6488 vtable_->shared_destroy(buffer_.shared);
6489 }
6490 }
6491
6492 template <typename M>
6493 static constexpr bool IsInlined() {
6494 return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
6495 std::is_trivially_copy_constructible<M>::value &&
6496 std::is_trivially_destructible<M>::value;
6497 }
6498
6499 template <typename M, bool = MatcherBase::IsInlined<M>()>
6500 struct ValuePolicy {
6501 static const M& Get(const MatcherBase& m) {
6502 // When inlined along with Init, need to be explicit to avoid violating
6503 // strict aliasing rules.
6504 const M *ptr = static_cast<const M*>(
6505 static_cast<const void*>(&m.buffer_));
6506 return *ptr;
6507 }
6508 static void Init(MatcherBase& m, M impl) {
6509 ::new (static_cast<void*>(&m.buffer_)) M(impl);
6510 }
6511 static constexpr auto shared_destroy = nullptr;
6512 };
6513
6514 template <typename M>
6515 struct ValuePolicy<M, false> {
6516 using Shared = SharedPayload<M>;
6517 static const M& Get(const MatcherBase& m) {
6518 return static_cast<Shared*>(m.buffer_.shared)->value;
6519 }
6520 template <typename Arg>
6521 static void Init(MatcherBase& m, Arg&& arg) {
6522 m.buffer_.shared = new Shared(std::forward<Arg>(arg));
6523 }
6524 static constexpr auto shared_destroy = &Shared::Destroy;
6525 };
6526
6527 template <typename U, bool B>
6528 struct ValuePolicy<const MatcherInterface<U>*, B> {
6529 using M = const MatcherInterface<U>;
6530 using Shared = SharedPayload<std::unique_ptr<M>>;
6531 static const M& Get(const MatcherBase& m) {
6532 return *static_cast<Shared*>(m.buffer_.shared)->value;
6533 }
6534 static void Init(MatcherBase& m, M* impl) {
6535 m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
6536 }
6537
6538 static constexpr auto shared_destroy = &Shared::Destroy;
6539 };
6540
6541 template <typename M>
6542 void Init(M&& m) {
6543 using MM = typename std::decay<M>::type;
6544 using Policy = ValuePolicy<MM>;
6545 vtable_ = GetVTable<Policy>();
6546 Policy::Init(*this, std::forward<M>(m));
6547 }
6548
6549 const VTable* vtable_;
6550 Buffer buffer_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006551};
6552
6553} // namespace internal
6554
6555// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
6556// object that can check whether a value of type T matches. The
6557// implementation of Matcher<T> is just a std::shared_ptr to const
6558// MatcherInterface<T>. Don't inherit from Matcher!
6559template <typename T>
6560class Matcher : public internal::MatcherBase<T> {
6561 public:
6562 // Constructs a null matcher. Needed for storing Matcher objects in STL
6563 // containers. A default-constructed matcher is not yet initialized. You
6564 // cannot use it until a valid value has been assigned to it.
6565 explicit Matcher() {} // NOLINT
6566
6567 // Constructs a matcher from its implementation.
6568 explicit Matcher(const MatcherInterface<const T&>* impl)
6569 : internal::MatcherBase<T>(impl) {}
6570
6571 template <typename U>
Austin Schuh3de38b02024-06-25 18:25:10 -07006572 explicit Matcher(
6573 const MatcherInterface<U>* impl,
6574 typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
6575 nullptr)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006576 : internal::MatcherBase<T>(impl) {}
6577
Austin Schuh3de38b02024-06-25 18:25:10 -07006578 template <typename M, typename = typename std::remove_reference<
6579 M>::type::is_gtest_matcher>
6580 Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
6581
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006582 // Implicit constructor here allows people to write
6583 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
6584 Matcher(T value); // NOLINT
6585};
6586
6587// The following two specializations allow the user to write str
6588// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
6589// matcher is expected.
6590template <>
6591class GTEST_API_ Matcher<const std::string&>
6592 : public internal::MatcherBase<const std::string&> {
6593 public:
6594 Matcher() {}
6595
6596 explicit Matcher(const MatcherInterface<const std::string&>* impl)
6597 : internal::MatcherBase<const std::string&>(impl) {}
6598
Austin Schuh3de38b02024-06-25 18:25:10 -07006599 template <typename M, typename = typename std::remove_reference<
6600 M>::type::is_gtest_matcher>
6601 Matcher(M&& m) // NOLINT
6602 : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
6603
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006604 // Allows the user to write str instead of Eq(str) sometimes, where
6605 // str is a std::string object.
6606 Matcher(const std::string& s); // NOLINT
6607
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006608 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6609 Matcher(const char* s); // NOLINT
6610};
6611
6612template <>
6613class GTEST_API_ Matcher<std::string>
6614 : public internal::MatcherBase<std::string> {
6615 public:
6616 Matcher() {}
6617
6618 explicit Matcher(const MatcherInterface<const std::string&>* impl)
6619 : internal::MatcherBase<std::string>(impl) {}
6620 explicit Matcher(const MatcherInterface<std::string>* impl)
6621 : internal::MatcherBase<std::string>(impl) {}
6622
Austin Schuh3de38b02024-06-25 18:25:10 -07006623 template <typename M, typename = typename std::remove_reference<
6624 M>::type::is_gtest_matcher>
6625 Matcher(M&& m) // NOLINT
6626 : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
6627
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006628 // Allows the user to write str instead of Eq(str) sometimes, where
6629 // str is a string object.
6630 Matcher(const std::string& s); // NOLINT
6631
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006632 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6633 Matcher(const char* s); // NOLINT
6634};
6635
Austin Schuh3de38b02024-06-25 18:25:10 -07006636#if GTEST_INTERNAL_HAS_STRING_VIEW
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006637// The following two specializations allow the user to write str
6638// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
6639// matcher is expected.
6640template <>
Austin Schuh3de38b02024-06-25 18:25:10 -07006641class GTEST_API_ Matcher<const internal::StringView&>
6642 : public internal::MatcherBase<const internal::StringView&> {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006643 public:
6644 Matcher() {}
6645
Austin Schuh3de38b02024-06-25 18:25:10 -07006646 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
6647 : internal::MatcherBase<const internal::StringView&>(impl) {}
6648
6649 template <typename M, typename = typename std::remove_reference<
6650 M>::type::is_gtest_matcher>
6651 Matcher(M&& m) // NOLINT
6652 : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
6653 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006654
6655 // Allows the user to write str instead of Eq(str) sometimes, where
6656 // str is a std::string object.
6657 Matcher(const std::string& s); // NOLINT
6658
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006659 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6660 Matcher(const char* s); // NOLINT
6661
Austin Schuh3de38b02024-06-25 18:25:10 -07006662 // Allows the user to pass absl::string_views or std::string_views directly.
6663 Matcher(internal::StringView s); // NOLINT
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006664};
6665
6666template <>
Austin Schuh3de38b02024-06-25 18:25:10 -07006667class GTEST_API_ Matcher<internal::StringView>
6668 : public internal::MatcherBase<internal::StringView> {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006669 public:
6670 Matcher() {}
6671
Austin Schuh3de38b02024-06-25 18:25:10 -07006672 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
6673 : internal::MatcherBase<internal::StringView>(impl) {}
6674 explicit Matcher(const MatcherInterface<internal::StringView>* impl)
6675 : internal::MatcherBase<internal::StringView>(impl) {}
6676
6677 template <typename M, typename = typename std::remove_reference<
6678 M>::type::is_gtest_matcher>
6679 Matcher(M&& m) // NOLINT
6680 : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006681
6682 // Allows the user to write str instead of Eq(str) sometimes, where
6683 // str is a std::string object.
6684 Matcher(const std::string& s); // NOLINT
6685
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006686 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6687 Matcher(const char* s); // NOLINT
6688
Austin Schuh3de38b02024-06-25 18:25:10 -07006689 // Allows the user to pass absl::string_views or std::string_views directly.
6690 Matcher(internal::StringView s); // NOLINT
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006691};
Austin Schuh3de38b02024-06-25 18:25:10 -07006692#endif // GTEST_INTERNAL_HAS_STRING_VIEW
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006693
6694// Prints a matcher in a human-readable format.
6695template <typename T>
6696std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
6697 matcher.DescribeTo(&os);
6698 return os;
6699}
6700
6701// The PolymorphicMatcher class template makes it easy to implement a
6702// polymorphic matcher (i.e. a matcher that can match values of more
6703// than one type, e.g. Eq(n) and NotNull()).
6704//
6705// To define a polymorphic matcher, a user should provide an Impl
6706// class that has a DescribeTo() method and a DescribeNegationTo()
6707// method, and define a member function (or member function template)
6708//
6709// bool MatchAndExplain(const Value& value,
6710// MatchResultListener* listener) const;
6711//
6712// See the definition of NotNull() for a complete example.
6713template <class Impl>
6714class PolymorphicMatcher {
6715 public:
6716 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
6717
6718 // Returns a mutable reference to the underlying matcher
6719 // implementation object.
6720 Impl& mutable_impl() { return impl_; }
6721
6722 // Returns an immutable reference to the underlying matcher
6723 // implementation object.
6724 const Impl& impl() const { return impl_; }
6725
6726 template <typename T>
6727 operator Matcher<T>() const {
6728 return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
6729 }
6730
6731 private:
6732 template <typename T>
6733 class MonomorphicImpl : public MatcherInterface<T> {
6734 public:
6735 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
6736
Austin Schuh3de38b02024-06-25 18:25:10 -07006737 void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006738
Austin Schuh3de38b02024-06-25 18:25:10 -07006739 void DescribeNegationTo(::std::ostream* os) const override {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006740 impl_.DescribeNegationTo(os);
6741 }
6742
Austin Schuh3de38b02024-06-25 18:25:10 -07006743 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006744 return impl_.MatchAndExplain(x, listener);
6745 }
6746
6747 private:
6748 const Impl impl_;
6749 };
6750
6751 Impl impl_;
6752};
6753
6754// Creates a matcher from its implementation.
6755// DEPRECATED: Especially in the generic code, prefer:
6756// Matcher<T>(new MyMatcherImpl<const T&>(...));
6757//
6758// MakeMatcher may create a Matcher that accepts its argument by value, which
6759// leads to unnecessary copies & lack of support for non-copyable types.
6760template <typename T>
6761inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
6762 return Matcher<T>(impl);
6763}
6764
6765// Creates a polymorphic matcher from its implementation. This is
6766// easier to use than the PolymorphicMatcher<Impl> constructor as it
6767// doesn't require you to explicitly write the template argument, e.g.
6768//
6769// MakePolymorphicMatcher(foo);
6770// vs
6771// PolymorphicMatcher<TypeOfFoo>(foo);
6772template <class Impl>
6773inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
6774 return PolymorphicMatcher<Impl>(impl);
6775}
6776
6777namespace internal {
6778// Implements a matcher that compares a given value with a
6779// pre-supplied value using one of the ==, <=, <, etc, operators. The
6780// two values being compared don't have to have the same type.
6781//
6782// The matcher defined here is polymorphic (for example, Eq(5) can be
6783// used to match an int, a short, a double, etc). Therefore we use
6784// a template type conversion operator in the implementation.
6785//
6786// The following template definition assumes that the Rhs parameter is
6787// a "bare" type (i.e. neither 'const T' nor 'T&').
6788template <typename D, typename Rhs, typename Op>
6789class ComparisonBase {
6790 public:
6791 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
Austin Schuh3de38b02024-06-25 18:25:10 -07006792
6793 using is_gtest_matcher = void;
6794
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006795 template <typename Lhs>
Austin Schuh3de38b02024-06-25 18:25:10 -07006796 bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
6797 return Op()(lhs, Unwrap(rhs_));
6798 }
6799 void DescribeTo(std::ostream* os) const {
6800 *os << D::Desc() << " ";
6801 UniversalPrint(Unwrap(rhs_), os);
6802 }
6803 void DescribeNegationTo(std::ostream* os) const {
6804 *os << D::NegatedDesc() << " ";
6805 UniversalPrint(Unwrap(rhs_), os);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006806 }
6807
6808 private:
6809 template <typename T>
Austin Schuh3de38b02024-06-25 18:25:10 -07006810 static const T& Unwrap(const T& v) {
6811 return v;
6812 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006813 template <typename T>
Austin Schuh3de38b02024-06-25 18:25:10 -07006814 static const T& Unwrap(std::reference_wrapper<T> v) {
6815 return v;
6816 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006817
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006818 Rhs rhs_;
6819};
6820
6821template <typename Rhs>
6822class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
6823 public:
6824 explicit EqMatcher(const Rhs& rhs)
6825 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
6826 static const char* Desc() { return "is equal to"; }
6827 static const char* NegatedDesc() { return "isn't equal to"; }
6828};
6829template <typename Rhs>
6830class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
6831 public:
6832 explicit NeMatcher(const Rhs& rhs)
6833 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
6834 static const char* Desc() { return "isn't equal to"; }
6835 static const char* NegatedDesc() { return "is equal to"; }
6836};
6837template <typename Rhs>
6838class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
6839 public:
6840 explicit LtMatcher(const Rhs& rhs)
6841 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
6842 static const char* Desc() { return "is <"; }
6843 static const char* NegatedDesc() { return "isn't <"; }
6844};
6845template <typename Rhs>
6846class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
6847 public:
6848 explicit GtMatcher(const Rhs& rhs)
6849 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
6850 static const char* Desc() { return "is >"; }
6851 static const char* NegatedDesc() { return "isn't >"; }
6852};
6853template <typename Rhs>
6854class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
6855 public:
6856 explicit LeMatcher(const Rhs& rhs)
6857 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
6858 static const char* Desc() { return "is <="; }
6859 static const char* NegatedDesc() { return "isn't <="; }
6860};
6861template <typename Rhs>
6862class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
6863 public:
6864 explicit GeMatcher(const Rhs& rhs)
6865 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
6866 static const char* Desc() { return "is >="; }
6867 static const char* NegatedDesc() { return "isn't >="; }
6868};
6869
Austin Schuh3de38b02024-06-25 18:25:10 -07006870template <typename T, typename = typename std::enable_if<
6871 std::is_constructible<std::string, T>::value>::type>
6872using StringLike = T;
6873
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006874// Implements polymorphic matchers MatchesRegex(regex) and
6875// ContainsRegex(regex), which can be used as a Matcher<T> as long as
6876// T can be converted to a string.
6877class MatchesRegexMatcher {
6878 public:
6879 MatchesRegexMatcher(const RE* regex, bool full_match)
6880 : regex_(regex), full_match_(full_match) {}
6881
Austin Schuh3de38b02024-06-25 18:25:10 -07006882#if GTEST_INTERNAL_HAS_STRING_VIEW
6883 bool MatchAndExplain(const internal::StringView& s,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006884 MatchResultListener* listener) const {
Austin Schuh3de38b02024-06-25 18:25:10 -07006885 return MatchAndExplain(std::string(s), listener);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006886 }
Austin Schuh3de38b02024-06-25 18:25:10 -07006887#endif // GTEST_INTERNAL_HAS_STRING_VIEW
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006888
6889 // Accepts pointer types, particularly:
6890 // const char*
6891 // char*
6892 // const wchar_t*
6893 // wchar_t*
6894 template <typename CharType>
6895 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
6896 return s != nullptr && MatchAndExplain(std::string(s), listener);
6897 }
6898
6899 // Matches anything that can convert to std::string.
6900 //
6901 // This is a template, not just a plain function with const std::string&,
6902 // because absl::string_view has some interfering non-explicit constructors.
6903 template <class MatcheeStringType>
6904 bool MatchAndExplain(const MatcheeStringType& s,
6905 MatchResultListener* /* listener */) const {
6906 const std::string& s2(s);
6907 return full_match_ ? RE::FullMatch(s2, *regex_)
6908 : RE::PartialMatch(s2, *regex_);
6909 }
6910
6911 void DescribeTo(::std::ostream* os) const {
6912 *os << (full_match_ ? "matches" : "contains") << " regular expression ";
6913 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
6914 }
6915
6916 void DescribeNegationTo(::std::ostream* os) const {
6917 *os << "doesn't " << (full_match_ ? "match" : "contain")
6918 << " regular expression ";
6919 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
6920 }
6921
6922 private:
6923 const std::shared_ptr<const RE> regex_;
6924 const bool full_match_;
6925};
6926} // namespace internal
6927
6928// Matches a string that fully matches regular expression 'regex'.
6929// The matcher takes ownership of 'regex'.
6930inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
6931 const internal::RE* regex) {
6932 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
6933}
Austin Schuh3de38b02024-06-25 18:25:10 -07006934template <typename T = std::string>
6935PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
6936 const internal::StringLike<T>& regex) {
6937 return MatchesRegex(new internal::RE(std::string(regex)));
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006938}
6939
6940// Matches a string that contains regular expression 'regex'.
6941// The matcher takes ownership of 'regex'.
6942inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
6943 const internal::RE* regex) {
6944 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
6945}
Austin Schuh3de38b02024-06-25 18:25:10 -07006946template <typename T = std::string>
6947PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
6948 const internal::StringLike<T>& regex) {
6949 return ContainsRegex(new internal::RE(std::string(regex)));
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08006950}
6951
6952// Creates a polymorphic matcher that matches anything equal to x.
6953// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
6954// wouldn't compile.
6955template <typename T>
6956inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
6957
6958// Constructs a Matcher<T> from a 'value' of type T. The constructed
6959// matcher matches any value that's equal to 'value'.
6960template <typename T>
6961Matcher<T>::Matcher(T value) { *this = Eq(value); }
6962
6963// Creates a monomorphic matcher that matches anything with type Lhs
6964// and equal to rhs. A user may need to use this instead of Eq(...)
6965// in order to resolve an overloading ambiguity.
6966//
6967// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
6968// or Matcher<T>(x), but more readable than the latter.
6969//
6970// We could define similar monomorphic matchers for other comparison
6971// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
6972// it yet as those are used much less than Eq() in practice. A user
6973// can always write Matcher<T>(Lt(5)) to be explicit about the type,
6974// for example.
6975template <typename Lhs, typename Rhs>
6976inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
6977
6978// Creates a polymorphic matcher that matches anything >= x.
6979template <typename Rhs>
6980inline internal::GeMatcher<Rhs> Ge(Rhs x) {
6981 return internal::GeMatcher<Rhs>(x);
6982}
6983
6984// Creates a polymorphic matcher that matches anything > x.
6985template <typename Rhs>
6986inline internal::GtMatcher<Rhs> Gt(Rhs x) {
6987 return internal::GtMatcher<Rhs>(x);
6988}
6989
6990// Creates a polymorphic matcher that matches anything <= x.
6991template <typename Rhs>
6992inline internal::LeMatcher<Rhs> Le(Rhs x) {
6993 return internal::LeMatcher<Rhs>(x);
6994}
6995
6996// Creates a polymorphic matcher that matches anything < x.
6997template <typename Rhs>
6998inline internal::LtMatcher<Rhs> Lt(Rhs x) {
6999 return internal::LtMatcher<Rhs>(x);
7000}
7001
7002// Creates a polymorphic matcher that matches anything != x.
7003template <typename Rhs>
7004inline internal::NeMatcher<Rhs> Ne(Rhs x) {
7005 return internal::NeMatcher<Rhs>(x);
7006}
7007} // namespace testing
7008
7009GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
7010
Austin Schuh3de38b02024-06-25 18:25:10 -07007011#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007012
7013#include <stdio.h>
7014#include <memory>
7015
7016namespace testing {
7017namespace internal {
7018
7019GTEST_DECLARE_string_(internal_run_death_test);
7020
7021// Names of the flags (needed for parsing Google Test flags).
7022const char kDeathTestStyleFlag[] = "death_test_style";
7023const char kDeathTestUseFork[] = "death_test_use_fork";
7024const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
7025
7026#if GTEST_HAS_DEATH_TEST
7027
7028GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
7029/* class A needs to have dll-interface to be used by clients of class B */)
7030
7031// DeathTest is a class that hides much of the complexity of the
7032// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
7033// returns a concrete class that depends on the prevailing death test
7034// style, as defined by the --gtest_death_test_style and/or
7035// --gtest_internal_run_death_test flags.
7036
7037// In describing the results of death tests, these terms are used with
7038// the corresponding definitions:
7039//
7040// exit status: The integer exit information in the format specified
7041// by wait(2)
7042// exit code: The integer code passed to exit(3), _exit(2), or
7043// returned from main()
7044class GTEST_API_ DeathTest {
7045 public:
7046 // Create returns false if there was an error determining the
7047 // appropriate action to take for the current death test; for example,
7048 // if the gtest_death_test_style flag is set to an invalid value.
7049 // The LastMessage method will return a more detailed message in that
7050 // case. Otherwise, the DeathTest pointer pointed to by the "test"
7051 // argument is set. If the death test should be skipped, the pointer
7052 // is set to NULL; otherwise, it is set to the address of a new concrete
7053 // DeathTest object that controls the execution of the current test.
7054 static bool Create(const char* statement, Matcher<const std::string&> matcher,
7055 const char* file, int line, DeathTest** test);
7056 DeathTest();
7057 virtual ~DeathTest() { }
7058
7059 // A helper class that aborts a death test when it's deleted.
7060 class ReturnSentinel {
7061 public:
7062 explicit ReturnSentinel(DeathTest* test) : test_(test) { }
7063 ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
7064 private:
7065 DeathTest* const test_;
7066 GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
7067 } GTEST_ATTRIBUTE_UNUSED_;
7068
7069 // An enumeration of possible roles that may be taken when a death
7070 // test is encountered. EXECUTE means that the death test logic should
7071 // be executed immediately. OVERSEE means that the program should prepare
7072 // the appropriate environment for a child process to execute the death
7073 // test, then wait for it to complete.
7074 enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
7075
7076 // An enumeration of the three reasons that a test might be aborted.
7077 enum AbortReason {
7078 TEST_ENCOUNTERED_RETURN_STATEMENT,
7079 TEST_THREW_EXCEPTION,
7080 TEST_DID_NOT_DIE
7081 };
7082
7083 // Assumes one of the above roles.
7084 virtual TestRole AssumeRole() = 0;
7085
7086 // Waits for the death test to finish and returns its status.
7087 virtual int Wait() = 0;
7088
7089 // Returns true if the death test passed; that is, the test process
7090 // exited during the test, its exit status matches a user-supplied
7091 // predicate, and its stderr output matches a user-supplied regular
7092 // expression.
7093 // The user-supplied predicate may be a macro expression rather
7094 // than a function pointer or functor, or else Wait and Passed could
7095 // be combined.
7096 virtual bool Passed(bool exit_status_ok) = 0;
7097
7098 // Signals that the death test did not die as expected.
7099 virtual void Abort(AbortReason reason) = 0;
7100
7101 // Returns a human-readable outcome message regarding the outcome of
7102 // the last death test.
7103 static const char* LastMessage();
7104
7105 static void set_last_death_test_message(const std::string& message);
7106
7107 private:
7108 // A string containing a description of the outcome of the last death test.
7109 static std::string last_death_test_message_;
7110
7111 GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
7112};
7113
7114GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
7115
7116// Factory interface for death tests. May be mocked out for testing.
7117class DeathTestFactory {
7118 public:
7119 virtual ~DeathTestFactory() { }
7120 virtual bool Create(const char* statement,
7121 Matcher<const std::string&> matcher, const char* file,
7122 int line, DeathTest** test) = 0;
7123};
7124
7125// A concrete DeathTestFactory implementation for normal use.
7126class DefaultDeathTestFactory : public DeathTestFactory {
7127 public:
7128 bool Create(const char* statement, Matcher<const std::string&> matcher,
7129 const char* file, int line, DeathTest** test) override;
7130};
7131
7132// Returns true if exit_status describes a process that was terminated
7133// by a signal, or exited normally with a nonzero exit code.
7134GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
7135
7136// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
7137// and interpreted as a regex (rather than an Eq matcher) for legacy
7138// compatibility.
7139inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7140 ::testing::internal::RE regex) {
7141 return ContainsRegex(regex.pattern());
7142}
7143inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
7144 return ContainsRegex(regex);
7145}
7146inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7147 const ::std::string& regex) {
7148 return ContainsRegex(regex);
7149}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007150
7151// If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
7152// used directly.
7153inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7154 Matcher<const ::std::string&> matcher) {
7155 return matcher;
7156}
7157
7158// Traps C++ exceptions escaping statement and reports them as test
7159// failures. Note that trapping SEH exceptions is not implemented here.
7160# if GTEST_HAS_EXCEPTIONS
7161# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
7162 try { \
7163 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7164 } catch (const ::std::exception& gtest_exception) { \
7165 fprintf(\
7166 stderr, \
7167 "\n%s: Caught std::exception-derived exception escaping the " \
7168 "death test statement. Exception message: %s\n", \
7169 ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
7170 gtest_exception.what()); \
7171 fflush(stderr); \
7172 death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
7173 } catch (...) { \
7174 death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
7175 }
7176
7177# else
7178# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
7179 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
7180
7181# endif
7182
7183// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
7184// ASSERT_EXIT*, and EXPECT_EXIT*.
7185#define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \
7186 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7187 if (::testing::internal::AlwaysTrue()) { \
7188 ::testing::internal::DeathTest* gtest_dt; \
7189 if (!::testing::internal::DeathTest::Create( \
7190 #statement, \
7191 ::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \
7192 __FILE__, __LINE__, &gtest_dt)) { \
7193 goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
7194 } \
7195 if (gtest_dt != nullptr) { \
7196 std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
7197 switch (gtest_dt->AssumeRole()) { \
7198 case ::testing::internal::DeathTest::OVERSEE_TEST: \
7199 if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
7200 goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
7201 } \
7202 break; \
7203 case ::testing::internal::DeathTest::EXECUTE_TEST: { \
7204 ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
7205 gtest_dt); \
7206 GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
7207 gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
7208 break; \
7209 } \
7210 default: \
7211 break; \
7212 } \
7213 } \
7214 } else \
7215 GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
7216 : fail(::testing::internal::DeathTest::LastMessage())
7217// The symbol "fail" here expands to something into which a message
7218// can be streamed.
7219
7220// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
7221// NDEBUG mode. In this case we need the statements to be executed and the macro
7222// must accept a streamed message even though the message is never printed.
7223// The regex object is not evaluated, but it is used to prevent "unused"
7224// warnings and to avoid an expression that doesn't compile in debug mode.
7225#define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
7226 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7227 if (::testing::internal::AlwaysTrue()) { \
7228 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7229 } else if (!::testing::internal::AlwaysTrue()) { \
7230 ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
7231 } else \
7232 ::testing::Message()
7233
7234// A class representing the parsed contents of the
7235// --gtest_internal_run_death_test flag, as it existed when
7236// RUN_ALL_TESTS was called.
7237class InternalRunDeathTestFlag {
7238 public:
7239 InternalRunDeathTestFlag(const std::string& a_file,
7240 int a_line,
7241 int an_index,
7242 int a_write_fd)
7243 : file_(a_file), line_(a_line), index_(an_index),
7244 write_fd_(a_write_fd) {}
7245
7246 ~InternalRunDeathTestFlag() {
7247 if (write_fd_ >= 0)
7248 posix::Close(write_fd_);
7249 }
7250
7251 const std::string& file() const { return file_; }
7252 int line() const { return line_; }
7253 int index() const { return index_; }
7254 int write_fd() const { return write_fd_; }
7255
7256 private:
7257 std::string file_;
7258 int line_;
7259 int index_;
7260 int write_fd_;
7261
7262 GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
7263};
7264
7265// Returns a newly created InternalRunDeathTestFlag object with fields
7266// initialized from the GTEST_FLAG(internal_run_death_test) flag if
7267// the flag is specified; otherwise returns NULL.
7268InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
7269
7270#endif // GTEST_HAS_DEATH_TEST
7271
7272} // namespace internal
7273} // namespace testing
7274
Austin Schuh3de38b02024-06-25 18:25:10 -07007275#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007276
7277namespace testing {
7278
7279// This flag controls the style of death tests. Valid values are "threadsafe",
7280// meaning that the death test child process will re-execute the test binary
7281// from the start, running only a single death test, or "fast",
7282// meaning that the child process will execute the test logic immediately
7283// after forking.
7284GTEST_DECLARE_string_(death_test_style);
7285
7286#if GTEST_HAS_DEATH_TEST
7287
7288namespace internal {
7289
7290// Returns a Boolean value indicating whether the caller is currently
7291// executing in the context of the death test child process. Tools such as
7292// Valgrind heap checkers may need this to modify their behavior in death
7293// tests. IMPORTANT: This is an internal utility. Using it may break the
7294// implementation of death tests. User code MUST NOT use it.
7295GTEST_API_ bool InDeathTestChild();
7296
7297} // namespace internal
7298
7299// The following macros are useful for writing death tests.
7300
7301// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
7302// executed:
7303//
7304// 1. It generates a warning if there is more than one active
7305// thread. This is because it's safe to fork() or clone() only
7306// when there is a single thread.
7307//
7308// 2. The parent process clone()s a sub-process and runs the death
7309// test in it; the sub-process exits with code 0 at the end of the
7310// death test, if it hasn't exited already.
7311//
7312// 3. The parent process waits for the sub-process to terminate.
7313//
7314// 4. The parent process checks the exit code and error message of
7315// the sub-process.
7316//
7317// Examples:
7318//
7319// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
7320// for (int i = 0; i < 5; i++) {
7321// EXPECT_DEATH(server.ProcessRequest(i),
7322// "Invalid request .* in ProcessRequest()")
7323// << "Failed to die on request " << i;
7324// }
7325//
7326// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
7327//
7328// bool KilledBySIGHUP(int exit_code) {
7329// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
7330// }
7331//
7332// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
7333//
Austin Schuh3de38b02024-06-25 18:25:10 -07007334// The final parameter to each of these macros is a matcher applied to any data
7335// the sub-process wrote to stderr. For compatibility with existing tests, a
7336// bare string is interpreted as a regular expression matcher.
7337//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007338// On the regular expressions used in death tests:
7339//
7340// GOOGLETEST_CM0005 DO NOT DELETE
7341// On POSIX-compliant systems (*nix), we use the <regex.h> library,
7342// which uses the POSIX extended regex syntax.
7343//
7344// On other platforms (e.g. Windows or Mac), we only support a simple regex
7345// syntax implemented as part of Google Test. This limited
7346// implementation should be enough most of the time when writing
7347// death tests; though it lacks many features you can find in PCRE
7348// or POSIX extended regex syntax. For example, we don't support
7349// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
7350// repetition count ("x{5,7}"), among others.
7351//
7352// Below is the syntax that we do support. We chose it to be a
7353// subset of both PCRE and POSIX extended regex, so it's easy to
7354// learn wherever you come from. In the following: 'A' denotes a
7355// literal character, period (.), or a single \\ escape sequence;
7356// 'x' and 'y' denote regular expressions; 'm' and 'n' are for
7357// natural numbers.
7358//
7359// c matches any literal character c
7360// \\d matches any decimal digit
7361// \\D matches any character that's not a decimal digit
7362// \\f matches \f
7363// \\n matches \n
7364// \\r matches \r
7365// \\s matches any ASCII whitespace, including \n
7366// \\S matches any character that's not a whitespace
7367// \\t matches \t
7368// \\v matches \v
7369// \\w matches any letter, _, or decimal digit
7370// \\W matches any character that \\w doesn't match
7371// \\c matches any literal character c, which must be a punctuation
7372// . matches any single character except \n
7373// A? matches 0 or 1 occurrences of A
7374// A* matches 0 or many occurrences of A
7375// A+ matches 1 or many occurrences of A
7376// ^ matches the beginning of a string (not that of each line)
7377// $ matches the end of a string (not that of each line)
7378// xy matches x followed by y
7379//
7380// If you accidentally use PCRE or POSIX extended regex features
7381// not implemented by us, you will get a run-time failure. In that
7382// case, please try to rewrite your regular expression within the
7383// above syntax.
7384//
7385// This implementation is *not* meant to be as highly tuned or robust
7386// as a compiled regex library, but should perform well enough for a
7387// death test, which already incurs significant overhead by launching
7388// a child process.
7389//
7390// Known caveats:
7391//
7392// A "threadsafe" style death test obtains the path to the test
7393// program from argv[0] and re-executes it in the sub-process. For
7394// simplicity, the current implementation doesn't search the PATH
7395// when launching the sub-process. This means that the user must
7396// invoke the test program via a path that contains at least one
7397// path separator (e.g. path/to/foo_test and
7398// /absolute/path/to/bar_test are fine, but foo_test is not). This
7399// is rarely a problem as people usually don't put the test binary
7400// directory in PATH.
7401//
7402
Austin Schuh3de38b02024-06-25 18:25:10 -07007403// Asserts that a given `statement` causes the program to exit, with an
7404// integer exit status that satisfies `predicate`, and emitting error output
7405// that matches `matcher`.
7406# define ASSERT_EXIT(statement, predicate, matcher) \
7407 GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007408
Austin Schuh3de38b02024-06-25 18:25:10 -07007409// Like `ASSERT_EXIT`, but continues on to successive tests in the
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007410// test suite, if any:
Austin Schuh3de38b02024-06-25 18:25:10 -07007411# define EXPECT_EXIT(statement, predicate, matcher) \
7412 GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007413
Austin Schuh3de38b02024-06-25 18:25:10 -07007414// Asserts that a given `statement` causes the program to exit, either by
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007415// explicitly exiting with a nonzero exit code or being killed by a
Austin Schuh3de38b02024-06-25 18:25:10 -07007416// signal, and emitting error output that matches `matcher`.
7417# define ASSERT_DEATH(statement, matcher) \
7418 ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007419
Austin Schuh3de38b02024-06-25 18:25:10 -07007420// Like `ASSERT_DEATH`, but continues on to successive tests in the
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007421// test suite, if any:
Austin Schuh3de38b02024-06-25 18:25:10 -07007422# define EXPECT_DEATH(statement, matcher) \
7423 EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007424
7425// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
7426
7427// Tests that an exit code describes a normal exit with a given exit code.
7428class GTEST_API_ ExitedWithCode {
7429 public:
7430 explicit ExitedWithCode(int exit_code);
Austin Schuh3de38b02024-06-25 18:25:10 -07007431 ExitedWithCode(const ExitedWithCode&) = default;
7432 void operator=(const ExitedWithCode& other) = delete;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007433 bool operator()(int exit_status) const;
7434 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007435 const int exit_code_;
7436};
7437
7438# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7439// Tests that an exit code describes an exit due to termination by a
7440// given signal.
7441// GOOGLETEST_CM0006 DO NOT DELETE
7442class GTEST_API_ KilledBySignal {
7443 public:
7444 explicit KilledBySignal(int signum);
7445 bool operator()(int exit_status) const;
7446 private:
7447 const int signum_;
7448};
7449# endif // !GTEST_OS_WINDOWS
7450
7451// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
7452// The death testing framework causes this to have interesting semantics,
7453// since the sideeffects of the call are only visible in opt mode, and not
7454// in debug mode.
7455//
7456// In practice, this can be used to test functions that utilize the
7457// LOG(DFATAL) macro using the following style:
7458//
7459// int DieInDebugOr12(int* sideeffect) {
7460// if (sideeffect) {
7461// *sideeffect = 12;
7462// }
7463// LOG(DFATAL) << "death";
7464// return 12;
7465// }
7466//
7467// TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
7468// int sideeffect = 0;
7469// // Only asserts in dbg.
7470// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
7471//
7472// #ifdef NDEBUG
7473// // opt-mode has sideeffect visible.
7474// EXPECT_EQ(12, sideeffect);
7475// #else
7476// // dbg-mode no visible sideeffect.
7477// EXPECT_EQ(0, sideeffect);
7478// #endif
7479// }
7480//
7481// This will assert that DieInDebugReturn12InOpt() crashes in debug
7482// mode, usually due to a DCHECK or LOG(DFATAL), but returns the
7483// appropriate fallback value (12 in this case) in opt mode. If you
7484// need to test that a function has appropriate side-effects in opt
7485// mode, include assertions against the side-effects. A general
7486// pattern for this is:
7487//
7488// EXPECT_DEBUG_DEATH({
7489// // Side-effects here will have an effect after this statement in
7490// // opt mode, but none in debug mode.
7491// EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
7492// }, "death");
7493//
7494# ifdef NDEBUG
7495
7496# define EXPECT_DEBUG_DEATH(statement, regex) \
7497 GTEST_EXECUTE_STATEMENT_(statement, regex)
7498
7499# define ASSERT_DEBUG_DEATH(statement, regex) \
7500 GTEST_EXECUTE_STATEMENT_(statement, regex)
7501
7502# else
7503
7504# define EXPECT_DEBUG_DEATH(statement, regex) \
7505 EXPECT_DEATH(statement, regex)
7506
7507# define ASSERT_DEBUG_DEATH(statement, regex) \
7508 ASSERT_DEATH(statement, regex)
7509
7510# endif // NDEBUG for EXPECT_DEBUG_DEATH
7511#endif // GTEST_HAS_DEATH_TEST
7512
7513// This macro is used for implementing macros such as
7514// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
7515// death tests are not supported. Those macros must compile on such systems
Austin Schuh3de38b02024-06-25 18:25:10 -07007516// if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
7517// on systems that support death tests. This allows one to write such a macro on
7518// a system that does not support death tests and be sure that it will compile
7519// on a death-test supporting system. It is exposed publicly so that systems
7520// that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
7521// can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
7522// ASSERT_DEATH_IF_SUPPORTED.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007523//
7524// Parameters:
7525// statement - A statement that a macro such as EXPECT_DEATH would test
7526// for program termination. This macro has to make sure this
7527// statement is compiled but not executed, to ensure that
7528// EXPECT_DEATH_IF_SUPPORTED compiles with a certain
Austin Schuh3de38b02024-06-25 18:25:10 -07007529// parameter if and only if EXPECT_DEATH compiles with it.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007530// regex - A regex that a macro such as EXPECT_DEATH would use to test
7531// the output of statement. This parameter has to be
7532// compiled but not evaluated by this macro, to ensure that
7533// this macro only accepts expressions that a macro such as
7534// EXPECT_DEATH would accept.
7535// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
7536// and a return statement for ASSERT_DEATH_IF_SUPPORTED.
7537// This ensures that ASSERT_DEATH_IF_SUPPORTED will not
7538// compile inside functions where ASSERT_DEATH doesn't
7539// compile.
7540//
7541// The branch that has an always false condition is used to ensure that
7542// statement and regex are compiled (and thus syntactically correct) but
7543// never executed. The unreachable code macro protects the terminator
7544// statement from generating an 'unreachable code' warning in case
7545// statement unconditionally returns or throws. The Message constructor at
7546// the end allows the syntax of streaming additional messages into the
7547// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
7548# define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
7549 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7550 if (::testing::internal::AlwaysTrue()) { \
7551 GTEST_LOG_(WARNING) \
7552 << "Death tests are not supported on this platform.\n" \
7553 << "Statement '" #statement "' cannot be verified."; \
7554 } else if (::testing::internal::AlwaysFalse()) { \
7555 ::testing::internal::RE::PartialMatch(".*", (regex)); \
7556 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7557 terminator; \
7558 } else \
7559 ::testing::Message()
7560
7561// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
7562// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
7563// death tests are supported; otherwise they just issue a warning. This is
7564// useful when you are combining death test assertions with normal test
7565// assertions in one test.
7566#if GTEST_HAS_DEATH_TEST
7567# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
7568 EXPECT_DEATH(statement, regex)
7569# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
7570 ASSERT_DEATH(statement, regex)
7571#else
7572# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
7573 GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
7574# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
7575 GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
7576#endif
7577
7578} // namespace testing
7579
Austin Schuh3de38b02024-06-25 18:25:10 -07007580#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007581// Copyright 2008, Google Inc.
7582// All rights reserved.
7583//
7584// Redistribution and use in source and binary forms, with or without
7585// modification, are permitted provided that the following conditions are
7586// met:
7587//
7588// * Redistributions of source code must retain the above copyright
7589// notice, this list of conditions and the following disclaimer.
7590// * Redistributions in binary form must reproduce the above
7591// copyright notice, this list of conditions and the following disclaimer
7592// in the documentation and/or other materials provided with the
7593// distribution.
7594// * Neither the name of Google Inc. nor the names of its
7595// contributors may be used to endorse or promote products derived from
7596// this software without specific prior written permission.
7597//
7598// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7599// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7600// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7601// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7602// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7603// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7604// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7605// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7606// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7607// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7608// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7609//
7610// Macros and functions for implementing parameterized tests
7611// in Google C++ Testing and Mocking Framework (Google Test)
7612//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007613// GOOGLETEST_CM0001 DO NOT DELETE
Austin Schuh3de38b02024-06-25 18:25:10 -07007614#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
7615#define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007616
7617// Value-parameterized tests allow you to test your code with different
7618// parameters without writing multiple copies of the same test.
7619//
7620// Here is how you use value-parameterized tests:
7621
7622#if 0
7623
7624// To write value-parameterized tests, first you should define a fixture
7625// class. It is usually derived from testing::TestWithParam<T> (see below for
7626// another inheritance scheme that's sometimes useful in more complicated
7627// class hierarchies), where the type of your parameter values.
7628// TestWithParam<T> is itself derived from testing::Test. T can be any
7629// copyable type. If it's a raw pointer, you are responsible for managing the
7630// lifespan of the pointed values.
7631
7632class FooTest : public ::testing::TestWithParam<const char*> {
7633 // You can implement all the usual class fixture members here.
7634};
7635
7636// Then, use the TEST_P macro to define as many parameterized tests
7637// for this fixture as you want. The _P suffix is for "parameterized"
7638// or "pattern", whichever you prefer to think.
7639
7640TEST_P(FooTest, DoesBlah) {
7641 // Inside a test, access the test parameter with the GetParam() method
7642 // of the TestWithParam<T> class:
7643 EXPECT_TRUE(foo.Blah(GetParam()));
7644 ...
7645}
7646
7647TEST_P(FooTest, HasBlahBlah) {
7648 ...
7649}
7650
7651// Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test
7652// case with any set of parameters you want. Google Test defines a number
7653// of functions for generating test parameters. They return what we call
7654// (surprise!) parameter generators. Here is a summary of them, which
7655// are all in the testing namespace:
7656//
7657//
7658// Range(begin, end [, step]) - Yields values {begin, begin+step,
7659// begin+step+step, ...}. The values do not
7660// include end. step defaults to 1.
7661// Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}.
7662// ValuesIn(container) - Yields values from a C-style array, an STL
7663// ValuesIn(begin,end) container, or an iterator range [begin, end).
7664// Bool() - Yields sequence {false, true}.
7665// Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product
7666// for the math savvy) of the values generated
7667// by the N generators.
7668//
7669// For more details, see comments at the definitions of these functions below
7670// in this file.
7671//
7672// The following statement will instantiate tests from the FooTest test suite
7673// each with parameter values "meeny", "miny", and "moe".
7674
7675INSTANTIATE_TEST_SUITE_P(InstantiationName,
7676 FooTest,
7677 Values("meeny", "miny", "moe"));
7678
7679// To distinguish different instances of the pattern, (yes, you
Austin Schuh3de38b02024-06-25 18:25:10 -07007680// can instantiate it more than once) the first argument to the
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007681// INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
7682// actual test suite name. Remember to pick unique prefixes for different
7683// instantiations. The tests from the instantiation above will have
7684// these names:
7685//
7686// * InstantiationName/FooTest.DoesBlah/0 for "meeny"
7687// * InstantiationName/FooTest.DoesBlah/1 for "miny"
7688// * InstantiationName/FooTest.DoesBlah/2 for "moe"
7689// * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
7690// * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
7691// * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
7692//
7693// You can use these names in --gtest_filter.
7694//
7695// This statement will instantiate all tests from FooTest again, each
7696// with parameter values "cat" and "dog":
7697
7698const char* pets[] = {"cat", "dog"};
7699INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
7700
7701// The tests from the instantiation above will have these names:
7702//
7703// * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
7704// * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
7705// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
7706// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
7707//
7708// Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests
7709// in the given test suite, whether their definitions come before or
7710// AFTER the INSTANTIATE_TEST_SUITE_P statement.
7711//
7712// Please also note that generator expressions (including parameters to the
7713// generators) are evaluated in InitGoogleTest(), after main() has started.
7714// This allows the user on one hand, to adjust generator parameters in order
7715// to dynamically determine a set of tests to run and on the other hand,
7716// give the user a chance to inspect the generated tests with Google Test
7717// reflection API before RUN_ALL_TESTS() is executed.
7718//
7719// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
7720// for more examples.
7721//
7722// In the future, we plan to publish the API for defining new parameter
7723// generators. But for now this interface remains part of the internal
7724// implementation and is subject to change.
7725//
7726//
7727// A parameterized test fixture must be derived from testing::Test and from
7728// testing::WithParamInterface<T>, where T is the type of the parameter
7729// values. Inheriting from TestWithParam<T> satisfies that requirement because
7730// TestWithParam<T> inherits from both Test and WithParamInterface. In more
7731// complicated hierarchies, however, it is occasionally useful to inherit
7732// separately from Test and WithParamInterface. For example:
7733
7734class BaseTest : public ::testing::Test {
7735 // You can inherit all the usual members for a non-parameterized test
7736 // fixture here.
7737};
7738
7739class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
7740 // The usual test fixture members go here too.
7741};
7742
7743TEST_F(BaseTest, HasFoo) {
7744 // This is an ordinary non-parameterized test.
7745}
7746
7747TEST_P(DerivedTest, DoesBlah) {
7748 // GetParam works just the same here as if you inherit from TestWithParam.
7749 EXPECT_TRUE(foo.Blah(GetParam()));
7750}
7751
7752#endif // 0
7753
Austin Schuh3de38b02024-06-25 18:25:10 -07007754#include <iterator>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007755#include <utility>
7756
7757// Copyright 2008 Google Inc.
7758// All Rights Reserved.
7759//
7760// Redistribution and use in source and binary forms, with or without
7761// modification, are permitted provided that the following conditions are
7762// met:
7763//
7764// * Redistributions of source code must retain the above copyright
7765// notice, this list of conditions and the following disclaimer.
7766// * Redistributions in binary form must reproduce the above
7767// copyright notice, this list of conditions and the following disclaimer
7768// in the documentation and/or other materials provided with the
7769// distribution.
7770// * Neither the name of Google Inc. nor the names of its
7771// contributors may be used to endorse or promote products derived from
7772// this software without specific prior written permission.
7773//
7774// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7775// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7776// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7777// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7778// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7779// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7780// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7781// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7782// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7783// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7784// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7785
7786
7787// Type and function utilities for implementing parameterized tests.
7788
7789// GOOGLETEST_CM0001 DO NOT DELETE
7790
Austin Schuh3de38b02024-06-25 18:25:10 -07007791#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
7792#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007793
7794#include <ctype.h>
7795
7796#include <cassert>
7797#include <iterator>
7798#include <memory>
7799#include <set>
7800#include <tuple>
Austin Schuh3de38b02024-06-25 18:25:10 -07007801#include <type_traits>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007802#include <utility>
7803#include <vector>
7804
Austin Schuh3de38b02024-06-25 18:25:10 -07007805// Copyright 2008, Google Inc.
7806// All rights reserved.
7807//
7808// Redistribution and use in source and binary forms, with or without
7809// modification, are permitted provided that the following conditions are
7810// met:
7811//
7812// * Redistributions of source code must retain the above copyright
7813// notice, this list of conditions and the following disclaimer.
7814// * Redistributions in binary form must reproduce the above
7815// copyright notice, this list of conditions and the following disclaimer
7816// in the documentation and/or other materials provided with the
7817// distribution.
7818// * Neither the name of Google Inc. nor the names of its
7819// contributors may be used to endorse or promote products derived from
7820// this software without specific prior written permission.
7821//
7822// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7823// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7824// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7825// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7826// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7827// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7828// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7829// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7830// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7831// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7832// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7833//
7834// GOOGLETEST_CM0001 DO NOT DELETE
7835
7836#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7837#define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7838
7839#include <iosfwd>
7840#include <vector>
7841
7842GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
7843/* class A needs to have dll-interface to be used by clients of class B */)
7844
7845namespace testing {
7846
7847// A copyable object representing the result of a test part (i.e. an
7848// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
7849//
7850// Don't inherit from TestPartResult as its destructor is not virtual.
7851class GTEST_API_ TestPartResult {
7852 public:
7853 // The possible outcomes of a test part (i.e. an assertion or an
7854 // explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
7855 enum Type {
7856 kSuccess, // Succeeded.
7857 kNonFatalFailure, // Failed but the test can continue.
7858 kFatalFailure, // Failed and the test should be terminated.
7859 kSkip // Skipped.
7860 };
7861
7862 // C'tor. TestPartResult does NOT have a default constructor.
7863 // Always use this constructor (with parameters) to create a
7864 // TestPartResult object.
7865 TestPartResult(Type a_type, const char* a_file_name, int a_line_number,
7866 const char* a_message)
7867 : type_(a_type),
7868 file_name_(a_file_name == nullptr ? "" : a_file_name),
7869 line_number_(a_line_number),
7870 summary_(ExtractSummary(a_message)),
7871 message_(a_message) {}
7872
7873 // Gets the outcome of the test part.
7874 Type type() const { return type_; }
7875
7876 // Gets the name of the source file where the test part took place, or
7877 // NULL if it's unknown.
7878 const char* file_name() const {
7879 return file_name_.empty() ? nullptr : file_name_.c_str();
7880 }
7881
7882 // Gets the line in the source file where the test part took place,
7883 // or -1 if it's unknown.
7884 int line_number() const { return line_number_; }
7885
7886 // Gets the summary of the failure message.
7887 const char* summary() const { return summary_.c_str(); }
7888
7889 // Gets the message associated with the test part.
7890 const char* message() const { return message_.c_str(); }
7891
7892 // Returns true if and only if the test part was skipped.
7893 bool skipped() const { return type_ == kSkip; }
7894
7895 // Returns true if and only if the test part passed.
7896 bool passed() const { return type_ == kSuccess; }
7897
7898 // Returns true if and only if the test part non-fatally failed.
7899 bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
7900
7901 // Returns true if and only if the test part fatally failed.
7902 bool fatally_failed() const { return type_ == kFatalFailure; }
7903
7904 // Returns true if and only if the test part failed.
7905 bool failed() const { return fatally_failed() || nonfatally_failed(); }
7906
7907 private:
7908 Type type_;
7909
7910 // Gets the summary of the failure message by omitting the stack
7911 // trace in it.
7912 static std::string ExtractSummary(const char* message);
7913
7914 // The name of the source file where the test part took place, or
7915 // "" if the source file is unknown.
7916 std::string file_name_;
7917 // The line in the source file where the test part took place, or -1
7918 // if the line number is unknown.
7919 int line_number_;
7920 std::string summary_; // The test failure summary.
7921 std::string message_; // The test failure message.
7922};
7923
7924// Prints a TestPartResult object.
7925std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
7926
7927// An array of TestPartResult objects.
7928//
7929// Don't inherit from TestPartResultArray as its destructor is not
7930// virtual.
7931class GTEST_API_ TestPartResultArray {
7932 public:
7933 TestPartResultArray() {}
7934
7935 // Appends the given TestPartResult to the array.
7936 void Append(const TestPartResult& result);
7937
7938 // Returns the TestPartResult at the given index (0-based).
7939 const TestPartResult& GetTestPartResult(int index) const;
7940
7941 // Returns the number of TestPartResult objects in the array.
7942 int size() const;
7943
7944 private:
7945 std::vector<TestPartResult> array_;
7946
7947 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
7948};
7949
7950// This interface knows how to report a test part result.
7951class GTEST_API_ TestPartResultReporterInterface {
7952 public:
7953 virtual ~TestPartResultReporterInterface() {}
7954
7955 virtual void ReportTestPartResult(const TestPartResult& result) = 0;
7956};
7957
7958namespace internal {
7959
7960// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
7961// statement generates new fatal failures. To do so it registers itself as the
7962// current test part result reporter. Besides checking if fatal failures were
7963// reported, it only delegates the reporting to the former result reporter.
7964// The original result reporter is restored in the destructor.
7965// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
7966class GTEST_API_ HasNewFatalFailureHelper
7967 : public TestPartResultReporterInterface {
7968 public:
7969 HasNewFatalFailureHelper();
7970 ~HasNewFatalFailureHelper() override;
7971 void ReportTestPartResult(const TestPartResult& result) override;
7972 bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
7973 private:
7974 bool has_new_fatal_failure_;
7975 TestPartResultReporterInterface* original_reporter_;
7976
7977 GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
7978};
7979
7980} // namespace internal
7981
7982} // namespace testing
7983
7984GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
7985
7986#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08007987
7988namespace testing {
Austin Schuh70cc9552019-01-21 19:46:48 -08007989// Input to a parameterized test name generator, describing a test parameter.
7990// Consists of the parameter value and the integer parameter index.
7991template <class ParamType>
7992struct TestParamInfo {
7993 TestParamInfo(const ParamType& a_param, size_t an_index) :
7994 param(a_param),
7995 index(an_index) {}
7996 ParamType param;
7997 size_t index;
7998};
7999
8000// A builtin parameterized test name generator which returns the result of
8001// testing::PrintToString.
8002struct PrintToStringParamName {
8003 template <class ParamType>
8004 std::string operator()(const TestParamInfo<ParamType>& info) const {
8005 return PrintToString(info.param);
8006 }
8007};
8008
8009namespace internal {
8010
8011// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008012// Utility Functions
8013
Austin Schuh70cc9552019-01-21 19:46:48 -08008014// Outputs a message explaining invalid registration of different
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008015// fixture class for the same test suite. This may happen when
Austin Schuh70cc9552019-01-21 19:46:48 -08008016// TEST_P macro is used to define two tests with the same name
8017// but in different namespaces.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008018GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
8019 CodeLocation code_location);
Austin Schuh70cc9552019-01-21 19:46:48 -08008020
8021template <typename> class ParamGeneratorInterface;
8022template <typename> class ParamGenerator;
8023
8024// Interface for iterating over elements provided by an implementation
8025// of ParamGeneratorInterface<T>.
8026template <typename T>
8027class ParamIteratorInterface {
8028 public:
8029 virtual ~ParamIteratorInterface() {}
8030 // A pointer to the base generator instance.
8031 // Used only for the purposes of iterator comparison
8032 // to make sure that two iterators belong to the same generator.
8033 virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
8034 // Advances iterator to point to the next element
8035 // provided by the generator. The caller is responsible
8036 // for not calling Advance() on an iterator equal to
8037 // BaseGenerator()->End().
8038 virtual void Advance() = 0;
8039 // Clones the iterator object. Used for implementing copy semantics
8040 // of ParamIterator<T>.
8041 virtual ParamIteratorInterface* Clone() const = 0;
8042 // Dereferences the current iterator and provides (read-only) access
8043 // to the pointed value. It is the caller's responsibility not to call
8044 // Current() on an iterator equal to BaseGenerator()->End().
8045 // Used for implementing ParamGenerator<T>::operator*().
8046 virtual const T* Current() const = 0;
8047 // Determines whether the given iterator and other point to the same
8048 // element in the sequence generated by the generator.
8049 // Used for implementing ParamGenerator<T>::operator==().
8050 virtual bool Equals(const ParamIteratorInterface& other) const = 0;
8051};
8052
8053// Class iterating over elements provided by an implementation of
8054// ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
8055// and implements the const forward iterator concept.
8056template <typename T>
8057class ParamIterator {
8058 public:
8059 typedef T value_type;
8060 typedef const T& reference;
8061 typedef ptrdiff_t difference_type;
8062
8063 // ParamIterator assumes ownership of the impl_ pointer.
8064 ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
8065 ParamIterator& operator=(const ParamIterator& other) {
8066 if (this != &other)
8067 impl_.reset(other.impl_->Clone());
8068 return *this;
8069 }
8070
8071 const T& operator*() const { return *impl_->Current(); }
8072 const T* operator->() const { return impl_->Current(); }
8073 // Prefix version of operator++.
8074 ParamIterator& operator++() {
8075 impl_->Advance();
8076 return *this;
8077 }
8078 // Postfix version of operator++.
8079 ParamIterator operator++(int /*unused*/) {
8080 ParamIteratorInterface<T>* clone = impl_->Clone();
8081 impl_->Advance();
8082 return ParamIterator(clone);
8083 }
8084 bool operator==(const ParamIterator& other) const {
8085 return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
8086 }
8087 bool operator!=(const ParamIterator& other) const {
8088 return !(*this == other);
8089 }
8090
8091 private:
8092 friend class ParamGenerator<T>;
8093 explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008094 std::unique_ptr<ParamIteratorInterface<T> > impl_;
Austin Schuh70cc9552019-01-21 19:46:48 -08008095};
8096
8097// ParamGeneratorInterface<T> is the binary interface to access generators
8098// defined in other translation units.
8099template <typename T>
8100class ParamGeneratorInterface {
8101 public:
8102 typedef T ParamType;
8103
8104 virtual ~ParamGeneratorInterface() {}
8105
8106 // Generator interface definition
8107 virtual ParamIteratorInterface<T>* Begin() const = 0;
8108 virtual ParamIteratorInterface<T>* End() const = 0;
8109};
8110
8111// Wraps ParamGeneratorInterface<T> and provides general generator syntax
8112// compatible with the STL Container concept.
8113// This class implements copy initialization semantics and the contained
8114// ParamGeneratorInterface<T> instance is shared among all copies
8115// of the original object. This is possible because that instance is immutable.
8116template<typename T>
8117class ParamGenerator {
8118 public:
8119 typedef ParamIterator<T> iterator;
8120
8121 explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
8122 ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
8123
8124 ParamGenerator& operator=(const ParamGenerator& other) {
8125 impl_ = other.impl_;
8126 return *this;
8127 }
8128
8129 iterator begin() const { return iterator(impl_->Begin()); }
8130 iterator end() const { return iterator(impl_->End()); }
8131
8132 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008133 std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
Austin Schuh70cc9552019-01-21 19:46:48 -08008134};
8135
8136// Generates values from a range of two comparable values. Can be used to
8137// generate sequences of user-defined types that implement operator+() and
8138// operator<().
8139// This class is used in the Range() function.
8140template <typename T, typename IncrementT>
8141class RangeGenerator : public ParamGeneratorInterface<T> {
8142 public:
8143 RangeGenerator(T begin, T end, IncrementT step)
8144 : begin_(begin), end_(end),
8145 step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008146 ~RangeGenerator() override {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008147
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008148 ParamIteratorInterface<T>* Begin() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008149 return new Iterator(this, begin_, 0, step_);
8150 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008151 ParamIteratorInterface<T>* End() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008152 return new Iterator(this, end_, end_index_, step_);
8153 }
8154
8155 private:
8156 class Iterator : public ParamIteratorInterface<T> {
8157 public:
8158 Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
8159 IncrementT step)
8160 : base_(base), value_(value), index_(index), step_(step) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008161 ~Iterator() override {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008162
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008163 const ParamGeneratorInterface<T>* BaseGenerator() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008164 return base_;
8165 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008166 void Advance() override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008167 value_ = static_cast<T>(value_ + step_);
8168 index_++;
8169 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008170 ParamIteratorInterface<T>* Clone() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008171 return new Iterator(*this);
8172 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008173 const T* Current() const override { return &value_; }
8174 bool Equals(const ParamIteratorInterface<T>& other) const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008175 // Having the same base generator guarantees that the other
8176 // iterator is of the same type and we can downcast.
8177 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8178 << "The program attempted to compare iterators "
8179 << "from different generators." << std::endl;
8180 const int other_index =
8181 CheckedDowncastToActualType<const Iterator>(&other)->index_;
8182 return index_ == other_index;
8183 }
8184
8185 private:
8186 Iterator(const Iterator& other)
8187 : ParamIteratorInterface<T>(),
8188 base_(other.base_), value_(other.value_), index_(other.index_),
8189 step_(other.step_) {}
8190
8191 // No implementation - assignment is unsupported.
8192 void operator=(const Iterator& other);
8193
8194 const ParamGeneratorInterface<T>* const base_;
8195 T value_;
8196 int index_;
8197 const IncrementT step_;
8198 }; // class RangeGenerator::Iterator
8199
8200 static int CalculateEndIndex(const T& begin,
8201 const T& end,
8202 const IncrementT& step) {
8203 int end_index = 0;
8204 for (T i = begin; i < end; i = static_cast<T>(i + step))
8205 end_index++;
8206 return end_index;
8207 }
8208
8209 // No implementation - assignment is unsupported.
8210 void operator=(const RangeGenerator& other);
8211
8212 const T begin_;
8213 const T end_;
8214 const IncrementT step_;
8215 // The index for the end() iterator. All the elements in the generated
8216 // sequence are indexed (0-based) to aid iterator comparison.
8217 const int end_index_;
8218}; // class RangeGenerator
8219
8220
8221// Generates values from a pair of STL-style iterators. Used in the
8222// ValuesIn() function. The elements are copied from the source range
8223// since the source can be located on the stack, and the generator
8224// is likely to persist beyond that stack frame.
8225template <typename T>
8226class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
8227 public:
8228 template <typename ForwardIterator>
8229 ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
8230 : container_(begin, end) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008231 ~ValuesInIteratorRangeGenerator() override {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008232
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008233 ParamIteratorInterface<T>* Begin() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008234 return new Iterator(this, container_.begin());
8235 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008236 ParamIteratorInterface<T>* End() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008237 return new Iterator(this, container_.end());
8238 }
8239
8240 private:
8241 typedef typename ::std::vector<T> ContainerType;
8242
8243 class Iterator : public ParamIteratorInterface<T> {
8244 public:
8245 Iterator(const ParamGeneratorInterface<T>* base,
8246 typename ContainerType::const_iterator iterator)
8247 : base_(base), iterator_(iterator) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008248 ~Iterator() override {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008249
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008250 const ParamGeneratorInterface<T>* BaseGenerator() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008251 return base_;
8252 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008253 void Advance() override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008254 ++iterator_;
8255 value_.reset();
8256 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008257 ParamIteratorInterface<T>* Clone() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008258 return new Iterator(*this);
8259 }
8260 // We need to use cached value referenced by iterator_ because *iterator_
8261 // can return a temporary object (and of type other then T), so just
8262 // having "return &*iterator_;" doesn't work.
8263 // value_ is updated here and not in Advance() because Advance()
8264 // can advance iterator_ beyond the end of the range, and we cannot
8265 // detect that fact. The client code, on the other hand, is
8266 // responsible for not calling Current() on an out-of-range iterator.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008267 const T* Current() const override {
8268 if (value_.get() == nullptr) value_.reset(new T(*iterator_));
Austin Schuh70cc9552019-01-21 19:46:48 -08008269 return value_.get();
8270 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008271 bool Equals(const ParamIteratorInterface<T>& other) const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008272 // Having the same base generator guarantees that the other
8273 // iterator is of the same type and we can downcast.
8274 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8275 << "The program attempted to compare iterators "
8276 << "from different generators." << std::endl;
8277 return iterator_ ==
8278 CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
8279 }
8280
8281 private:
8282 Iterator(const Iterator& other)
8283 // The explicit constructor call suppresses a false warning
8284 // emitted by gcc when supplied with the -Wextra option.
8285 : ParamIteratorInterface<T>(),
8286 base_(other.base_),
8287 iterator_(other.iterator_) {}
8288
8289 const ParamGeneratorInterface<T>* const base_;
8290 typename ContainerType::const_iterator iterator_;
8291 // A cached value of *iterator_. We keep it here to allow access by
8292 // pointer in the wrapping iterator's operator->().
8293 // value_ needs to be mutable to be accessed in Current().
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008294 // Use of std::unique_ptr helps manage cached value's lifetime,
Austin Schuh70cc9552019-01-21 19:46:48 -08008295 // which is bound by the lifespan of the iterator itself.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008296 mutable std::unique_ptr<const T> value_;
Austin Schuh70cc9552019-01-21 19:46:48 -08008297 }; // class ValuesInIteratorRangeGenerator::Iterator
8298
8299 // No implementation - assignment is unsupported.
8300 void operator=(const ValuesInIteratorRangeGenerator& other);
8301
8302 const ContainerType container_;
8303}; // class ValuesInIteratorRangeGenerator
8304
8305// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8306//
8307// Default parameterized test name generator, returns a string containing the
8308// integer test parameter index.
8309template <class ParamType>
8310std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
8311 Message name_stream;
8312 name_stream << info.index;
8313 return name_stream.GetString();
8314}
8315
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008316template <typename T = int>
8317void TestNotEmpty() {
8318 static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");
Austin Schuh70cc9552019-01-21 19:46:48 -08008319}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008320template <typename T = int>
8321void TestNotEmpty(const T&) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008322
8323// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8324//
8325// Stores a parameter value and later creates tests parameterized with that
8326// value.
8327template <class TestClass>
8328class ParameterizedTestFactory : public TestFactoryBase {
8329 public:
8330 typedef typename TestClass::ParamType ParamType;
8331 explicit ParameterizedTestFactory(ParamType parameter) :
8332 parameter_(parameter) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008333 Test* CreateTest() override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008334 TestClass::SetParam(&parameter_);
8335 return new TestClass();
8336 }
8337
8338 private:
8339 const ParamType parameter_;
8340
8341 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
8342};
8343
8344// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8345//
8346// TestMetaFactoryBase is a base class for meta-factories that create
8347// test factories for passing into MakeAndRegisterTestInfo function.
8348template <class ParamType>
8349class TestMetaFactoryBase {
8350 public:
8351 virtual ~TestMetaFactoryBase() {}
8352
8353 virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
8354};
8355
8356// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8357//
8358// TestMetaFactory creates test factories for passing into
8359// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
8360// ownership of test factory pointer, same factory object cannot be passed
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008361// into that method twice. But ParameterizedTestSuiteInfo is going to call
Austin Schuh70cc9552019-01-21 19:46:48 -08008362// it for each Test/Parameter value combination. Thus it needs meta factory
8363// creator class.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008364template <class TestSuite>
Austin Schuh70cc9552019-01-21 19:46:48 -08008365class TestMetaFactory
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008366 : public TestMetaFactoryBase<typename TestSuite::ParamType> {
Austin Schuh70cc9552019-01-21 19:46:48 -08008367 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008368 using ParamType = typename TestSuite::ParamType;
Austin Schuh70cc9552019-01-21 19:46:48 -08008369
8370 TestMetaFactory() {}
8371
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008372 TestFactoryBase* CreateTestFactory(ParamType parameter) override {
8373 return new ParameterizedTestFactory<TestSuite>(parameter);
Austin Schuh70cc9552019-01-21 19:46:48 -08008374 }
8375
8376 private:
8377 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
8378};
8379
8380// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8381//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008382// ParameterizedTestSuiteInfoBase is a generic interface
8383// to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase
Austin Schuh70cc9552019-01-21 19:46:48 -08008384// accumulates test information provided by TEST_P macro invocations
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008385// and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations
Austin Schuh70cc9552019-01-21 19:46:48 -08008386// and uses that information to register all resulting test instances
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008387// in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
8388// a collection of pointers to the ParameterizedTestSuiteInfo objects
Austin Schuh70cc9552019-01-21 19:46:48 -08008389// and calls RegisterTests() on each of them when asked.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008390class ParameterizedTestSuiteInfoBase {
Austin Schuh70cc9552019-01-21 19:46:48 -08008391 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008392 virtual ~ParameterizedTestSuiteInfoBase() {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008393
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008394 // Base part of test suite name for display purposes.
8395 virtual const std::string& GetTestSuiteName() const = 0;
Austin Schuh3de38b02024-06-25 18:25:10 -07008396 // Test suite id to verify identity.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008397 virtual TypeId GetTestSuiteTypeId() const = 0;
Austin Schuh70cc9552019-01-21 19:46:48 -08008398 // UnitTest class invokes this method to register tests in this
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008399 // test suite right before running them in RUN_ALL_TESTS macro.
Austin Schuh3de38b02024-06-25 18:25:10 -07008400 // This method should not be called more than once on any single
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008401 // instance of a ParameterizedTestSuiteInfoBase derived class.
Austin Schuh70cc9552019-01-21 19:46:48 -08008402 virtual void RegisterTests() = 0;
8403
8404 protected:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008405 ParameterizedTestSuiteInfoBase() {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008406
8407 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008408 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
Austin Schuh70cc9552019-01-21 19:46:48 -08008409};
8410
8411// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8412//
Austin Schuh3de38b02024-06-25 18:25:10 -07008413// Report a the name of a test_suit as safe to ignore
8414// as the side effect of construction of this type.
8415struct GTEST_API_ MarkAsIgnored {
8416 explicit MarkAsIgnored(const char* test_suite);
8417};
8418
8419GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
8420 CodeLocation location, bool has_test_p);
8421
8422// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8423//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008424// ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
8425// macro invocations for a particular test suite and generators
8426// obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that
8427// test suite. It registers tests with all values generated by all
Austin Schuh70cc9552019-01-21 19:46:48 -08008428// generators when asked.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008429template <class TestSuite>
8430class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
Austin Schuh70cc9552019-01-21 19:46:48 -08008431 public:
8432 // ParamType and GeneratorCreationFunc are private types but are required
8433 // for declarations of public methods AddTestPattern() and
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008434 // AddTestSuiteInstantiation().
8435 using ParamType = typename TestSuite::ParamType;
Austin Schuh70cc9552019-01-21 19:46:48 -08008436 // A function that returns an instance of appropriate generator type.
8437 typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008438 using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
Austin Schuh70cc9552019-01-21 19:46:48 -08008439
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008440 explicit ParameterizedTestSuiteInfo(const char* name,
8441 CodeLocation code_location)
8442 : test_suite_name_(name), code_location_(code_location) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008443
Austin Schuh3de38b02024-06-25 18:25:10 -07008444 // Test suite base name for display purposes.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008445 const std::string& GetTestSuiteName() const override {
8446 return test_suite_name_;
8447 }
Austin Schuh3de38b02024-06-25 18:25:10 -07008448 // Test suite id to verify identity.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008449 TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
Austin Schuh70cc9552019-01-21 19:46:48 -08008450 // TEST_P macro uses AddTestPattern() to record information
8451 // about a single test in a LocalTestInfo structure.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008452 // test_suite_name is the base name of the test suite (without invocation
Austin Schuh70cc9552019-01-21 19:46:48 -08008453 // prefix). test_base_name is the name of an individual test without
8454 // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008455 // test suite base name and DoBar is test base name.
8456 void AddTestPattern(const char* test_suite_name, const char* test_base_name,
Austin Schuh3de38b02024-06-25 18:25:10 -07008457 TestMetaFactoryBase<ParamType>* meta_factory,
8458 CodeLocation code_location) {
8459 tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
8460 test_suite_name, test_base_name, meta_factory, code_location)));
Austin Schuh70cc9552019-01-21 19:46:48 -08008461 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008462 // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
Austin Schuh70cc9552019-01-21 19:46:48 -08008463 // about a generator.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008464 int AddTestSuiteInstantiation(const std::string& instantiation_name,
8465 GeneratorCreationFunc* func,
8466 ParamNameGeneratorFunc* name_func,
8467 const char* file, int line) {
Austin Schuh70cc9552019-01-21 19:46:48 -08008468 instantiations_.push_back(
8469 InstantiationInfo(instantiation_name, func, name_func, file, line));
8470 return 0; // Return value used only to run this method in namespace scope.
8471 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008472 // UnitTest class invokes this method to register tests in this test suite
Austin Schuh3de38b02024-06-25 18:25:10 -07008473 // right before running tests in RUN_ALL_TESTS macro.
8474 // This method should not be called more than once on any single
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008475 // instance of a ParameterizedTestSuiteInfoBase derived class.
Austin Schuh3de38b02024-06-25 18:25:10 -07008476 // UnitTest has a guard to prevent from calling this method more than once.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008477 void RegisterTests() override {
Austin Schuh3de38b02024-06-25 18:25:10 -07008478 bool generated_instantiations = false;
8479
Austin Schuh70cc9552019-01-21 19:46:48 -08008480 for (typename TestInfoContainer::iterator test_it = tests_.begin();
8481 test_it != tests_.end(); ++test_it) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008482 std::shared_ptr<TestInfo> test_info = *test_it;
Austin Schuh70cc9552019-01-21 19:46:48 -08008483 for (typename InstantiationContainer::iterator gen_it =
8484 instantiations_.begin(); gen_it != instantiations_.end();
8485 ++gen_it) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008486 const std::string& instantiation_name = gen_it->name;
Austin Schuh70cc9552019-01-21 19:46:48 -08008487 ParamGenerator<ParamType> generator((*gen_it->generator)());
8488 ParamNameGeneratorFunc* name_func = gen_it->name_func;
8489 const char* file = gen_it->file;
8490 int line = gen_it->line;
8491
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008492 std::string test_suite_name;
Austin Schuh70cc9552019-01-21 19:46:48 -08008493 if ( !instantiation_name.empty() )
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008494 test_suite_name = instantiation_name + "/";
8495 test_suite_name += test_info->test_suite_base_name;
Austin Schuh70cc9552019-01-21 19:46:48 -08008496
8497 size_t i = 0;
8498 std::set<std::string> test_param_names;
8499 for (typename ParamGenerator<ParamType>::iterator param_it =
8500 generator.begin();
8501 param_it != generator.end(); ++param_it, ++i) {
Austin Schuh3de38b02024-06-25 18:25:10 -07008502 generated_instantiations = true;
8503
Austin Schuh70cc9552019-01-21 19:46:48 -08008504 Message test_name_stream;
8505
8506 std::string param_name = name_func(
8507 TestParamInfo<ParamType>(*param_it, i));
8508
8509 GTEST_CHECK_(IsValidParamName(param_name))
8510 << "Parameterized test name '" << param_name
8511 << "' is invalid, in " << file
8512 << " line " << line << std::endl;
8513
8514 GTEST_CHECK_(test_param_names.count(param_name) == 0)
8515 << "Duplicate parameterized test name '" << param_name
8516 << "', in " << file << " line " << line << std::endl;
8517
8518 test_param_names.insert(param_name);
8519
Austin Schuh3de38b02024-06-25 18:25:10 -07008520 if (!test_info->test_base_name.empty()) {
8521 test_name_stream << test_info->test_base_name << "/";
8522 }
8523 test_name_stream << param_name;
Austin Schuh70cc9552019-01-21 19:46:48 -08008524 MakeAndRegisterTestInfo(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008525 test_suite_name.c_str(), test_name_stream.GetString().c_str(),
8526 nullptr, // No type parameter.
Austin Schuh3de38b02024-06-25 18:25:10 -07008527 PrintToString(*param_it).c_str(), test_info->code_location,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008528 GetTestSuiteTypeId(),
Austin Schuh3de38b02024-06-25 18:25:10 -07008529 SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
8530 SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
Austin Schuh70cc9552019-01-21 19:46:48 -08008531 test_info->test_meta_factory->CreateTestFactory(*param_it));
8532 } // for param_it
8533 } // for gen_it
8534 } // for test_it
Austin Schuh3de38b02024-06-25 18:25:10 -07008535
8536 if (!generated_instantiations) {
8537 // There are no generaotrs, or they all generate nothing ...
8538 InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
8539 !tests_.empty());
8540 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008541 } // RegisterTests
Austin Schuh70cc9552019-01-21 19:46:48 -08008542
8543 private:
8544 // LocalTestInfo structure keeps information about a single test registered
8545 // with TEST_P macro.
8546 struct TestInfo {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008547 TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
Austin Schuh3de38b02024-06-25 18:25:10 -07008548 TestMetaFactoryBase<ParamType>* a_test_meta_factory,
8549 CodeLocation a_code_location)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008550 : test_suite_base_name(a_test_suite_base_name),
8551 test_base_name(a_test_base_name),
Austin Schuh3de38b02024-06-25 18:25:10 -07008552 test_meta_factory(a_test_meta_factory),
8553 code_location(a_code_location) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008554
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008555 const std::string test_suite_base_name;
8556 const std::string test_base_name;
8557 const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
Austin Schuh3de38b02024-06-25 18:25:10 -07008558 const CodeLocation code_location;
Austin Schuh70cc9552019-01-21 19:46:48 -08008559 };
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008560 using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
8561 // Records data received from INSTANTIATE_TEST_SUITE_P macros:
Austin Schuh70cc9552019-01-21 19:46:48 -08008562 // <Instantiation name, Sequence generator creation function,
8563 // Name generator function, Source file, Source line>
8564 struct InstantiationInfo {
8565 InstantiationInfo(const std::string &name_in,
8566 GeneratorCreationFunc* generator_in,
8567 ParamNameGeneratorFunc* name_func_in,
8568 const char* file_in,
8569 int line_in)
8570 : name(name_in),
8571 generator(generator_in),
8572 name_func(name_func_in),
8573 file(file_in),
8574 line(line_in) {}
8575
8576 std::string name;
8577 GeneratorCreationFunc* generator;
8578 ParamNameGeneratorFunc* name_func;
8579 const char* file;
8580 int line;
8581 };
8582 typedef ::std::vector<InstantiationInfo> InstantiationContainer;
8583
8584 static bool IsValidParamName(const std::string& name) {
8585 // Check for empty string
8586 if (name.empty())
8587 return false;
8588
8589 // Check for invalid characters
8590 for (std::string::size_type index = 0; index < name.size(); ++index) {
Austin Schuh3de38b02024-06-25 18:25:10 -07008591 if (!IsAlNum(name[index]) && name[index] != '_')
Austin Schuh70cc9552019-01-21 19:46:48 -08008592 return false;
8593 }
8594
8595 return true;
8596 }
8597
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008598 const std::string test_suite_name_;
Austin Schuh70cc9552019-01-21 19:46:48 -08008599 CodeLocation code_location_;
8600 TestInfoContainer tests_;
8601 InstantiationContainer instantiations_;
8602
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008603 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
8604}; // class ParameterizedTestSuiteInfo
8605
8606// Legacy API is deprecated but still available
8607#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8608template <class TestCase>
8609using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
8610#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -08008611
8612// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8613//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008614// ParameterizedTestSuiteRegistry contains a map of
8615// ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
8616// and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
8617// ParameterizedTestSuiteInfo descriptors.
8618class ParameterizedTestSuiteRegistry {
Austin Schuh70cc9552019-01-21 19:46:48 -08008619 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008620 ParameterizedTestSuiteRegistry() {}
8621 ~ParameterizedTestSuiteRegistry() {
8622 for (auto& test_suite_info : test_suite_infos_) {
8623 delete test_suite_info;
Austin Schuh70cc9552019-01-21 19:46:48 -08008624 }
8625 }
8626
8627 // Looks up or creates and returns a structure containing information about
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008628 // tests and instantiations of a particular test suite.
8629 template <class TestSuite>
8630 ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
8631 const char* test_suite_name, CodeLocation code_location) {
8632 ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
8633 for (auto& test_suite_info : test_suite_infos_) {
8634 if (test_suite_info->GetTestSuiteName() == test_suite_name) {
8635 if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
Austin Schuh70cc9552019-01-21 19:46:48 -08008636 // Complain about incorrect usage of Google Test facilities
8637 // and terminate the program since we cannot guaranty correct
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008638 // test suite setup and tear-down in this case.
8639 ReportInvalidTestSuiteType(test_suite_name, code_location);
Austin Schuh70cc9552019-01-21 19:46:48 -08008640 posix::Abort();
8641 } else {
8642 // At this point we are sure that the object we found is of the same
8643 // type we are looking for, so we downcast it to that type
8644 // without further checks.
8645 typed_test_info = CheckedDowncastToActualType<
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008646 ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
Austin Schuh70cc9552019-01-21 19:46:48 -08008647 }
8648 break;
8649 }
8650 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008651 if (typed_test_info == nullptr) {
8652 typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
8653 test_suite_name, code_location);
8654 test_suite_infos_.push_back(typed_test_info);
Austin Schuh70cc9552019-01-21 19:46:48 -08008655 }
8656 return typed_test_info;
8657 }
8658 void RegisterTests() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008659 for (auto& test_suite_info : test_suite_infos_) {
8660 test_suite_info->RegisterTests();
Austin Schuh70cc9552019-01-21 19:46:48 -08008661 }
8662 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008663// Legacy API is deprecated but still available
8664#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8665 template <class TestCase>
8666 ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
8667 const char* test_case_name, CodeLocation code_location) {
8668 return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
8669 }
8670
8671#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -08008672
8673 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008674 using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
Austin Schuh70cc9552019-01-21 19:46:48 -08008675
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008676 TestSuiteInfoContainer test_suite_infos_;
Austin Schuh70cc9552019-01-21 19:46:48 -08008677
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008678 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
Austin Schuh70cc9552019-01-21 19:46:48 -08008679};
8680
Austin Schuh3de38b02024-06-25 18:25:10 -07008681// Keep track of what type-parameterized test suite are defined and
8682// where as well as which are intatiated. This allows susequently
8683// identifying suits that are defined but never used.
8684class TypeParameterizedTestSuiteRegistry {
8685 public:
8686 // Add a suite definition
8687 void RegisterTestSuite(const char* test_suite_name,
8688 CodeLocation code_location);
8689
8690 // Add an instantiation of a suit.
8691 void RegisterInstantiation(const char* test_suite_name);
8692
8693 // For each suit repored as defined but not reported as instantiation,
8694 // emit a test that reports that fact (configurably, as an error).
8695 void CheckForInstantiations();
8696
8697 private:
8698 struct TypeParameterizedTestSuiteInfo {
8699 explicit TypeParameterizedTestSuiteInfo(CodeLocation c)
8700 : code_location(c), instantiated(false) {}
8701
8702 CodeLocation code_location;
8703 bool instantiated;
8704 };
8705
8706 std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;
8707};
8708
Austin Schuh70cc9552019-01-21 19:46:48 -08008709} // namespace internal
Austin Schuh70cc9552019-01-21 19:46:48 -08008710
8711// Forward declarations of ValuesIn(), which is implemented in
8712// include/gtest/gtest-param-test.h.
Austin Schuh70cc9552019-01-21 19:46:48 -08008713template <class Container>
8714internal::ParamGenerator<typename Container::value_type> ValuesIn(
8715 const Container& container);
8716
8717namespace internal {
Austin Schuh70cc9552019-01-21 19:46:48 -08008718// Used in the Values() function to provide polymorphic capabilities.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008719
Austin Schuh3de38b02024-06-25 18:25:10 -07008720#ifdef _MSC_VER
8721#pragma warning(push)
8722#pragma warning(disable : 4100)
8723#endif
8724
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008725template <typename... Ts>
8726class ValueArray {
Austin Schuh70cc9552019-01-21 19:46:48 -08008727 public:
Austin Schuh3de38b02024-06-25 18:25:10 -07008728 explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008729
8730 template <typename T>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008731 operator ParamGenerator<T>() const { // NOLINT
8732 return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
Austin Schuh70cc9552019-01-21 19:46:48 -08008733 }
8734
8735 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008736 template <typename T, size_t... I>
8737 std::vector<T> MakeVector(IndexSequence<I...>) const {
8738 return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
8739 }
Austin Schuh70cc9552019-01-21 19:46:48 -08008740
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008741 FlatTuple<Ts...> v_;
Austin Schuh70cc9552019-01-21 19:46:48 -08008742};
8743
Austin Schuh3de38b02024-06-25 18:25:10 -07008744#ifdef _MSC_VER
8745#pragma warning(pop)
8746#endif
8747
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008748template <typename... T>
8749class CartesianProductGenerator
8750 : public ParamGeneratorInterface<::std::tuple<T...>> {
Austin Schuh70cc9552019-01-21 19:46:48 -08008751 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008752 typedef ::std::tuple<T...> ParamType;
Austin Schuh70cc9552019-01-21 19:46:48 -08008753
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008754 CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
8755 : generators_(g) {}
8756 ~CartesianProductGenerator() override {}
8757
8758 ParamIteratorInterface<ParamType>* Begin() const override {
8759 return new Iterator(this, generators_, false);
8760 }
8761 ParamIteratorInterface<ParamType>* End() const override {
8762 return new Iterator(this, generators_, true);
Austin Schuh70cc9552019-01-21 19:46:48 -08008763 }
8764
8765 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008766 template <class I>
8767 class IteratorImpl;
8768 template <size_t... I>
8769 class IteratorImpl<IndexSequence<I...>>
8770 : public ParamIteratorInterface<ParamType> {
Austin Schuh70cc9552019-01-21 19:46:48 -08008771 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008772 IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
8773 const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
Austin Schuh70cc9552019-01-21 19:46:48 -08008774 : base_(base),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008775 begin_(std::get<I>(generators).begin()...),
8776 end_(std::get<I>(generators).end()...),
8777 current_(is_end ? end_ : begin_) {
Austin Schuh70cc9552019-01-21 19:46:48 -08008778 ComputeCurrentValue();
8779 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008780 ~IteratorImpl() override {}
Austin Schuh70cc9552019-01-21 19:46:48 -08008781
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008782 const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008783 return base_;
8784 }
8785 // Advance should not be called on beyond-of-range iterators
8786 // so no component iterators must be beyond end of range, either.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008787 void Advance() override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008788 assert(!AtEnd());
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008789 // Advance the last iterator.
8790 ++std::get<sizeof...(T) - 1>(current_);
8791 // if that reaches end, propagate that up.
8792 AdvanceIfEnd<sizeof...(T) - 1>();
Austin Schuh70cc9552019-01-21 19:46:48 -08008793 ComputeCurrentValue();
8794 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008795 ParamIteratorInterface<ParamType>* Clone() const override {
8796 return new IteratorImpl(*this);
Austin Schuh70cc9552019-01-21 19:46:48 -08008797 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008798
8799 const ParamType* Current() const override { return current_value_.get(); }
8800
8801 bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
Austin Schuh70cc9552019-01-21 19:46:48 -08008802 // Having the same base generator guarantees that the other
8803 // iterator is of the same type and we can downcast.
8804 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8805 << "The program attempted to compare iterators "
8806 << "from different generators." << std::endl;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008807 const IteratorImpl* typed_other =
8808 CheckedDowncastToActualType<const IteratorImpl>(&other);
8809
Austin Schuh70cc9552019-01-21 19:46:48 -08008810 // We must report iterators equal if they both point beyond their
8811 // respective ranges. That can happen in a variety of fashions,
8812 // so we have to consult AtEnd().
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008813 if (AtEnd() && typed_other->AtEnd()) return true;
8814
8815 bool same = true;
8816 bool dummy[] = {
8817 (same = same && std::get<I>(current_) ==
8818 std::get<I>(typed_other->current_))...};
8819 (void)dummy;
8820 return same;
Austin Schuh70cc9552019-01-21 19:46:48 -08008821 }
8822
8823 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008824 template <size_t ThisI>
8825 void AdvanceIfEnd() {
8826 if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
8827
8828 bool last = ThisI == 0;
8829 if (last) {
8830 // We are done. Nothing else to propagate.
8831 return;
8832 }
8833
8834 constexpr size_t NextI = ThisI - (ThisI != 0);
8835 std::get<ThisI>(current_) = std::get<ThisI>(begin_);
8836 ++std::get<NextI>(current_);
8837 AdvanceIfEnd<NextI>();
Austin Schuh70cc9552019-01-21 19:46:48 -08008838 }
8839
8840 void ComputeCurrentValue() {
8841 if (!AtEnd())
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008842 current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
Austin Schuh70cc9552019-01-21 19:46:48 -08008843 }
8844 bool AtEnd() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008845 bool at_end = false;
8846 bool dummy[] = {
8847 (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
8848 (void)dummy;
8849 return at_end;
Austin Schuh70cc9552019-01-21 19:46:48 -08008850 }
8851
Austin Schuh70cc9552019-01-21 19:46:48 -08008852 const ParamGeneratorInterface<ParamType>* const base_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008853 std::tuple<typename ParamGenerator<T>::iterator...> begin_;
8854 std::tuple<typename ParamGenerator<T>::iterator...> end_;
8855 std::tuple<typename ParamGenerator<T>::iterator...> current_;
8856 std::shared_ptr<ParamType> current_value_;
8857 };
Austin Schuh70cc9552019-01-21 19:46:48 -08008858
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008859 using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
Austin Schuh70cc9552019-01-21 19:46:48 -08008860
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008861 std::tuple<ParamGenerator<T>...> generators_;
8862};
Austin Schuh70cc9552019-01-21 19:46:48 -08008863
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008864template <class... Gen>
8865class CartesianProductHolder {
Austin Schuh70cc9552019-01-21 19:46:48 -08008866 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008867 CartesianProductHolder(const Gen&... g) : generators_(g...) {}
8868 template <typename... T>
8869 operator ParamGenerator<::std::tuple<T...>>() const {
8870 return ParamGenerator<::std::tuple<T...>>(
8871 new CartesianProductGenerator<T...>(generators_));
Austin Schuh70cc9552019-01-21 19:46:48 -08008872 }
8873
8874 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008875 std::tuple<Gen...> generators_;
8876};
Austin Schuh70cc9552019-01-21 19:46:48 -08008877
8878} // namespace internal
8879} // namespace testing
8880
Austin Schuh3de38b02024-06-25 18:25:10 -07008881#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08008882
8883namespace testing {
8884
8885// Functions producing parameter generators.
8886//
8887// Google Test uses these generators to produce parameters for value-
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008888// parameterized tests. When a parameterized test suite is instantiated
Austin Schuh70cc9552019-01-21 19:46:48 -08008889// with a particular generator, Google Test creates and runs tests
8890// for each element in the sequence produced by the generator.
8891//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008892// In the following sample, tests from test suite FooTest are instantiated
Austin Schuh70cc9552019-01-21 19:46:48 -08008893// each three times with parameter values 3, 5, and 8:
8894//
8895// class FooTest : public TestWithParam<int> { ... };
8896//
8897// TEST_P(FooTest, TestThis) {
8898// }
8899// TEST_P(FooTest, TestThat) {
8900// }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008901// INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));
Austin Schuh70cc9552019-01-21 19:46:48 -08008902//
8903
8904// Range() returns generators providing sequences of values in a range.
8905//
8906// Synopsis:
8907// Range(start, end)
8908// - returns a generator producing a sequence of values {start, start+1,
8909// start+2, ..., }.
8910// Range(start, end, step)
8911// - returns a generator producing a sequence of values {start, start+step,
8912// start+step+step, ..., }.
8913// Notes:
8914// * The generated sequences never include end. For example, Range(1, 5)
8915// returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
8916// returns a generator producing {1, 3, 5, 7}.
8917// * start and end must have the same type. That type may be any integral or
8918// floating-point type or a user defined type satisfying these conditions:
8919// * It must be assignable (have operator=() defined).
8920// * It must have operator+() (operator+(int-compatible type) for
8921// two-operand version).
8922// * It must have operator<() defined.
8923// Elements in the resulting sequences will also have that type.
8924// * Condition start < end must be satisfied in order for resulting sequences
8925// to contain any elements.
8926//
8927template <typename T, typename IncrementT>
8928internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
8929 return internal::ParamGenerator<T>(
8930 new internal::RangeGenerator<T, IncrementT>(start, end, step));
8931}
8932
8933template <typename T>
8934internal::ParamGenerator<T> Range(T start, T end) {
8935 return Range(start, end, 1);
8936}
8937
8938// ValuesIn() function allows generation of tests with parameters coming from
8939// a container.
8940//
8941// Synopsis:
8942// ValuesIn(const T (&array)[N])
8943// - returns a generator producing sequences with elements from
8944// a C-style array.
8945// ValuesIn(const Container& container)
8946// - returns a generator producing sequences with elements from
8947// an STL-style container.
8948// ValuesIn(Iterator begin, Iterator end)
8949// - returns a generator producing sequences with elements from
8950// a range [begin, end) defined by a pair of STL-style iterators. These
8951// iterators can also be plain C pointers.
8952//
8953// Please note that ValuesIn copies the values from the containers
8954// passed in and keeps them to generate tests in RUN_ALL_TESTS().
8955//
8956// Examples:
8957//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008958// This instantiates tests from test suite StringTest
Austin Schuh70cc9552019-01-21 19:46:48 -08008959// each with C-string values of "foo", "bar", and "baz":
8960//
8961// const char* strings[] = {"foo", "bar", "baz"};
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008962// INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));
Austin Schuh70cc9552019-01-21 19:46:48 -08008963//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008964// This instantiates tests from test suite StlStringTest
Austin Schuh70cc9552019-01-21 19:46:48 -08008965// each with STL strings with values "a" and "b":
8966//
8967// ::std::vector< ::std::string> GetParameterStrings() {
8968// ::std::vector< ::std::string> v;
8969// v.push_back("a");
8970// v.push_back("b");
8971// return v;
8972// }
8973//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008974// INSTANTIATE_TEST_SUITE_P(CharSequence,
8975// StlStringTest,
8976// ValuesIn(GetParameterStrings()));
Austin Schuh70cc9552019-01-21 19:46:48 -08008977//
8978//
8979// This will also instantiate tests from CharTest
8980// each with parameter values 'a' and 'b':
8981//
8982// ::std::list<char> GetParameterChars() {
8983// ::std::list<char> list;
8984// list.push_back('a');
8985// list.push_back('b');
8986// return list;
8987// }
8988// ::std::list<char> l = GetParameterChars();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08008989// INSTANTIATE_TEST_SUITE_P(CharSequence2,
8990// CharTest,
8991// ValuesIn(l.begin(), l.end()));
Austin Schuh70cc9552019-01-21 19:46:48 -08008992//
8993template <typename ForwardIterator>
8994internal::ParamGenerator<
Austin Schuh3de38b02024-06-25 18:25:10 -07008995 typename std::iterator_traits<ForwardIterator>::value_type>
Austin Schuh70cc9552019-01-21 19:46:48 -08008996ValuesIn(ForwardIterator begin, ForwardIterator end) {
Austin Schuh3de38b02024-06-25 18:25:10 -07008997 typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;
Austin Schuh70cc9552019-01-21 19:46:48 -08008998 return internal::ParamGenerator<ParamType>(
8999 new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
9000}
9001
9002template <typename T, size_t N>
9003internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
9004 return ValuesIn(array, array + N);
9005}
9006
9007template <class Container>
9008internal::ParamGenerator<typename Container::value_type> ValuesIn(
9009 const Container& container) {
9010 return ValuesIn(container.begin(), container.end());
9011}
9012
9013// Values() allows generating tests from explicitly specified list of
9014// parameters.
9015//
9016// Synopsis:
9017// Values(T v1, T v2, ..., T vN)
9018// - returns a generator producing sequences with elements v1, v2, ..., vN.
9019//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009020// For example, this instantiates tests from test suite BarTest each
Austin Schuh70cc9552019-01-21 19:46:48 -08009021// with values "one", "two", and "three":
9022//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009023// INSTANTIATE_TEST_SUITE_P(NumSequence,
9024// BarTest,
9025// Values("one", "two", "three"));
Austin Schuh70cc9552019-01-21 19:46:48 -08009026//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009027// This instantiates tests from test suite BazTest each with values 1, 2, 3.5.
Austin Schuh70cc9552019-01-21 19:46:48 -08009028// The exact type of values will depend on the type of parameter in BazTest.
9029//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009030// INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
Austin Schuh70cc9552019-01-21 19:46:48 -08009031//
Austin Schuh70cc9552019-01-21 19:46:48 -08009032//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009033template <typename... T>
9034internal::ValueArray<T...> Values(T... v) {
9035 return internal::ValueArray<T...>(std::move(v)...);
Austin Schuh70cc9552019-01-21 19:46:48 -08009036}
9037
9038// Bool() allows generating tests with parameters in a set of (false, true).
9039//
9040// Synopsis:
9041// Bool()
9042// - returns a generator producing sequences with elements {false, true}.
9043//
9044// It is useful when testing code that depends on Boolean flags. Combinations
9045// of multiple flags can be tested when several Bool()'s are combined using
9046// Combine() function.
9047//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009048// In the following example all tests in the test suite FlagDependentTest
Austin Schuh70cc9552019-01-21 19:46:48 -08009049// will be instantiated twice with parameters false and true.
9050//
9051// class FlagDependentTest : public testing::TestWithParam<bool> {
9052// virtual void SetUp() {
9053// external_flag = GetParam();
9054// }
9055// }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009056// INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
Austin Schuh70cc9552019-01-21 19:46:48 -08009057//
9058inline internal::ParamGenerator<bool> Bool() {
9059 return Values(false, true);
9060}
9061
Austin Schuh70cc9552019-01-21 19:46:48 -08009062// Combine() allows the user to combine two or more sequences to produce
9063// values of a Cartesian product of those sequences' elements.
9064//
9065// Synopsis:
9066// Combine(gen1, gen2, ..., genN)
9067// - returns a generator producing sequences with elements coming from
9068// the Cartesian product of elements from the sequences generated by
9069// gen1, gen2, ..., genN. The sequence elements will have a type of
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009070// std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
Austin Schuh70cc9552019-01-21 19:46:48 -08009071// of elements from sequences produces by gen1, gen2, ..., genN.
9072//
Austin Schuh70cc9552019-01-21 19:46:48 -08009073// Example:
9074//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009075// This will instantiate tests in test suite AnimalTest each one with
Austin Schuh70cc9552019-01-21 19:46:48 -08009076// the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
9077// tuple("dog", BLACK), and tuple("dog", WHITE):
9078//
9079// enum Color { BLACK, GRAY, WHITE };
9080// class AnimalTest
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009081// : public testing::TestWithParam<std::tuple<const char*, Color> > {...};
Austin Schuh70cc9552019-01-21 19:46:48 -08009082//
9083// TEST_P(AnimalTest, AnimalLooksNice) {...}
9084//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009085// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
9086// Combine(Values("cat", "dog"),
9087// Values(BLACK, WHITE)));
Austin Schuh70cc9552019-01-21 19:46:48 -08009088//
9089// This will instantiate tests in FlagDependentTest with all variations of two
9090// Boolean flags:
9091//
9092// class FlagDependentTest
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009093// : public testing::TestWithParam<std::tuple<bool, bool> > {
Austin Schuh70cc9552019-01-21 19:46:48 -08009094// virtual void SetUp() {
9095// // Assigns external_flag_1 and external_flag_2 values from the tuple.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009096// std::tie(external_flag_1, external_flag_2) = GetParam();
Austin Schuh70cc9552019-01-21 19:46:48 -08009097// }
9098// };
9099//
9100// TEST_P(FlagDependentTest, TestFeature1) {
9101// // Test your code using external_flag_1 and external_flag_2 here.
9102// }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009103// INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,
9104// Combine(Bool(), Bool()));
Austin Schuh70cc9552019-01-21 19:46:48 -08009105//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009106template <typename... Generator>
9107internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
9108 return internal::CartesianProductHolder<Generator...>(g...);
Austin Schuh70cc9552019-01-21 19:46:48 -08009109}
9110
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009111#define TEST_P(test_suite_name, test_name) \
9112 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
9113 : public test_suite_name { \
9114 public: \
9115 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
Austin Schuh3de38b02024-06-25 18:25:10 -07009116 void TestBody() override; \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009117 \
9118 private: \
9119 static int AddToRegistry() { \
9120 ::testing::UnitTest::GetInstance() \
9121 ->parameterized_test_registry() \
9122 .GetTestSuitePatternHolder<test_suite_name>( \
Austin Schuh3de38b02024-06-25 18:25:10 -07009123 GTEST_STRINGIFY_(test_suite_name), \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009124 ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
9125 ->AddTestPattern( \
9126 GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
9127 new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
Austin Schuh3de38b02024-06-25 18:25:10 -07009128 test_suite_name, test_name)>(), \
9129 ::testing::internal::CodeLocation(__FILE__, __LINE__)); \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009130 return 0; \
9131 } \
9132 static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
9133 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
9134 test_name)); \
9135 }; \
9136 int GTEST_TEST_CLASS_NAME_(test_suite_name, \
9137 test_name)::gtest_registering_dummy_ = \
9138 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \
9139 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
Austin Schuh70cc9552019-01-21 19:46:48 -08009140
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009141// The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify
9142// generator and an optional function or functor that generates custom test name
9143// suffixes based on the test parameters. Such a function or functor should
9144// accept one argument of type testing::TestParamInfo<class ParamType>, and
9145// return std::string.
Austin Schuh70cc9552019-01-21 19:46:48 -08009146//
9147// testing::PrintToStringParamName is a builtin test suffix generator that
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009148// returns the value of testing::PrintToString(GetParam()).
Austin Schuh70cc9552019-01-21 19:46:48 -08009149//
9150// Note: test names must be non-empty, unique, and may only contain ASCII
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009151// alphanumeric characters or underscore. Because PrintToString adds quotes
9152// to std::string and C strings, it won't work for these types.
Austin Schuh70cc9552019-01-21 19:46:48 -08009153
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009154#define GTEST_EXPAND_(arg) arg
9155#define GTEST_GET_FIRST_(first, ...) first
9156#define GTEST_GET_SECOND_(first, second, ...) second
9157
9158#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
9159 static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
9160 gtest_##prefix##test_suite_name##_EvalGenerator_() { \
9161 return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
9162 } \
9163 static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
9164 const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
9165 if (::testing::internal::AlwaysFalse()) { \
9166 ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
9167 __VA_ARGS__, \
9168 ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
9169 DUMMY_PARAM_))); \
9170 auto t = std::make_tuple(__VA_ARGS__); \
9171 static_assert(std::tuple_size<decltype(t)>::value <= 2, \
9172 "Too Many Args!"); \
9173 } \
9174 return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
9175 __VA_ARGS__, \
9176 ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
9177 DUMMY_PARAM_))))(info); \
9178 } \
9179 static int gtest_##prefix##test_suite_name##_dummy_ \
9180 GTEST_ATTRIBUTE_UNUSED_ = \
9181 ::testing::UnitTest::GetInstance() \
9182 ->parameterized_test_registry() \
9183 .GetTestSuitePatternHolder<test_suite_name>( \
Austin Schuh3de38b02024-06-25 18:25:10 -07009184 GTEST_STRINGIFY_(test_suite_name), \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009185 ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
9186 ->AddTestSuiteInstantiation( \
Austin Schuh3de38b02024-06-25 18:25:10 -07009187 GTEST_STRINGIFY_(prefix), \
9188 &gtest_##prefix##test_suite_name##_EvalGenerator_, \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009189 &gtest_##prefix##test_suite_name##_EvalGenerateName_, \
9190 __FILE__, __LINE__)
9191
Austin Schuh3de38b02024-06-25 18:25:10 -07009192
9193// Allow Marking a Parameterized test class as not needing to be instantiated.
9194#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
9195 namespace gtest_do_not_use_outside_namespace_scope {} \
9196 static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
9197 GTEST_STRINGIFY_(T))
9198
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009199// Legacy API is deprecated but still available
9200#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9201#define INSTANTIATE_TEST_CASE_P \
9202 static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \
9203 ""); \
9204 INSTANTIATE_TEST_SUITE_P
9205#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -08009206
9207} // namespace testing
9208
Austin Schuh3de38b02024-06-25 18:25:10 -07009209#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08009210// Copyright 2006, Google Inc.
9211// All rights reserved.
9212//
9213// Redistribution and use in source and binary forms, with or without
9214// modification, are permitted provided that the following conditions are
9215// met:
9216//
9217// * Redistributions of source code must retain the above copyright
9218// notice, this list of conditions and the following disclaimer.
9219// * Redistributions in binary form must reproduce the above
9220// copyright notice, this list of conditions and the following disclaimer
9221// in the documentation and/or other materials provided with the
9222// distribution.
9223// * Neither the name of Google Inc. nor the names of its
9224// contributors may be used to endorse or promote products derived from
9225// this software without specific prior written permission.
9226//
9227// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9228// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9229// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9230// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9231// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9232// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9233// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9234// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9235// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9236// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9237// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009238
Austin Schuh70cc9552019-01-21 19:46:48 -08009239//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009240// Google C++ Testing and Mocking Framework definitions useful in production code.
9241// GOOGLETEST_CM0003 DO NOT DELETE
Austin Schuh70cc9552019-01-21 19:46:48 -08009242
Austin Schuh3de38b02024-06-25 18:25:10 -07009243#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9244#define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08009245
9246// When you need to test the private or protected members of a class,
9247// use the FRIEND_TEST macro to declare your tests as friends of the
9248// class. For example:
9249//
9250// class MyClass {
9251// private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009252// void PrivateMethod();
9253// FRIEND_TEST(MyClassTest, PrivateMethodWorks);
Austin Schuh70cc9552019-01-21 19:46:48 -08009254// };
9255//
9256// class MyClassTest : public testing::Test {
9257// // ...
9258// };
9259//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009260// TEST_F(MyClassTest, PrivateMethodWorks) {
9261// // Can call MyClass::PrivateMethod() here.
Austin Schuh70cc9552019-01-21 19:46:48 -08009262// }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009263//
9264// Note: The test class must be in the same namespace as the class being tested.
9265// For example, putting MyClassTest in an anonymous namespace will not work.
Austin Schuh70cc9552019-01-21 19:46:48 -08009266
9267#define FRIEND_TEST(test_case_name, test_name)\
9268friend class test_case_name##_##test_name##_Test
9269
Austin Schuh3de38b02024-06-25 18:25:10 -07009270#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08009271// Copyright 2008 Google Inc.
9272// All Rights Reserved.
9273//
9274// Redistribution and use in source and binary forms, with or without
9275// modification, are permitted provided that the following conditions are
9276// met:
9277//
9278// * Redistributions of source code must retain the above copyright
9279// notice, this list of conditions and the following disclaimer.
9280// * Redistributions in binary form must reproduce the above
9281// copyright notice, this list of conditions and the following disclaimer
9282// in the documentation and/or other materials provided with the
9283// distribution.
9284// * Neither the name of Google Inc. nor the names of its
9285// contributors may be used to endorse or promote products derived from
9286// this software without specific prior written permission.
9287//
9288// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9289// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9290// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9291// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9292// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9293// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9294// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9295// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9296// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9297// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9298// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009299
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009300// GOOGLETEST_CM0001 DO NOT DELETE
Austin Schuh70cc9552019-01-21 19:46:48 -08009301
Austin Schuh3de38b02024-06-25 18:25:10 -07009302#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9303#define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08009304
9305// This header implements typed tests and type-parameterized tests.
9306
9307// Typed (aka type-driven) tests repeat the same test for types in a
9308// list. You must know which types you want to test with when writing
9309// typed tests. Here's how you do it:
9310
9311#if 0
9312
9313// First, define a fixture class template. It should be parameterized
9314// by a type. Remember to derive it from testing::Test.
9315template <typename T>
9316class FooTest : public testing::Test {
9317 public:
9318 ...
9319 typedef std::list<T> List;
9320 static T shared_;
9321 T value_;
9322};
9323
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009324// Next, associate a list of types with the test suite, which will be
Austin Schuh70cc9552019-01-21 19:46:48 -08009325// repeated for each type in the list. The typedef is necessary for
9326// the macro to parse correctly.
9327typedef testing::Types<char, int, unsigned int> MyTypes;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009328TYPED_TEST_SUITE(FooTest, MyTypes);
Austin Schuh70cc9552019-01-21 19:46:48 -08009329
9330// If the type list contains only one type, you can write that type
9331// directly without Types<...>:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009332// TYPED_TEST_SUITE(FooTest, int);
Austin Schuh70cc9552019-01-21 19:46:48 -08009333
9334// Then, use TYPED_TEST() instead of TEST_F() to define as many typed
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009335// tests for this test suite as you want.
Austin Schuh70cc9552019-01-21 19:46:48 -08009336TYPED_TEST(FooTest, DoesBlah) {
Austin Schuh3de38b02024-06-25 18:25:10 -07009337 // Inside a test, refer to the special name TypeParam to get the type
9338 // parameter. Since we are inside a derived class template, C++ requires
9339 // us to visit the members of FooTest via 'this'.
Austin Schuh70cc9552019-01-21 19:46:48 -08009340 TypeParam n = this->value_;
9341
9342 // To visit static members of the fixture, add the TestFixture::
9343 // prefix.
9344 n += TestFixture::shared_;
9345
9346 // To refer to typedefs in the fixture, add the "typename
9347 // TestFixture::" prefix.
9348 typename TestFixture::List values;
9349 values.push_back(n);
9350 ...
9351}
9352
9353TYPED_TEST(FooTest, HasPropertyA) { ... }
9354
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009355// TYPED_TEST_SUITE takes an optional third argument which allows to specify a
9356// class that generates custom test name suffixes based on the type. This should
9357// be a class which has a static template function GetName(int index) returning
9358// a string for each type. The provided integer index equals the index of the
9359// type in the provided type list. In many cases the index can be ignored.
9360//
9361// For example:
9362// class MyTypeNames {
9363// public:
9364// template <typename T>
9365// static std::string GetName(int) {
9366// if (std::is_same<T, char>()) return "char";
9367// if (std::is_same<T, int>()) return "int";
9368// if (std::is_same<T, unsigned int>()) return "unsignedInt";
9369// }
9370// };
9371// TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);
9372
Austin Schuh70cc9552019-01-21 19:46:48 -08009373#endif // 0
9374
9375// Type-parameterized tests are abstract test patterns parameterized
9376// by a type. Compared with typed tests, type-parameterized tests
9377// allow you to define the test pattern without knowing what the type
9378// parameters are. The defined pattern can be instantiated with
9379// different types any number of times, in any number of translation
9380// units.
9381//
9382// If you are designing an interface or concept, you can define a
9383// suite of type-parameterized tests to verify properties that any
9384// valid implementation of the interface/concept should have. Then,
9385// each implementation can easily instantiate the test suite to verify
9386// that it conforms to the requirements, without having to write
9387// similar tests repeatedly. Here's an example:
9388
9389#if 0
9390
9391// First, define a fixture class template. It should be parameterized
9392// by a type. Remember to derive it from testing::Test.
9393template <typename T>
9394class FooTest : public testing::Test {
9395 ...
9396};
9397
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009398// Next, declare that you will define a type-parameterized test suite
Austin Schuh70cc9552019-01-21 19:46:48 -08009399// (the _P suffix is for "parameterized" or "pattern", whichever you
9400// prefer):
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009401TYPED_TEST_SUITE_P(FooTest);
Austin Schuh70cc9552019-01-21 19:46:48 -08009402
9403// Then, use TYPED_TEST_P() to define as many type-parameterized tests
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009404// for this type-parameterized test suite as you want.
Austin Schuh70cc9552019-01-21 19:46:48 -08009405TYPED_TEST_P(FooTest, DoesBlah) {
9406 // Inside a test, refer to TypeParam to get the type parameter.
9407 TypeParam n = 0;
9408 ...
9409}
9410
9411TYPED_TEST_P(FooTest, HasPropertyA) { ... }
9412
9413// Now the tricky part: you need to register all test patterns before
9414// you can instantiate them. The first argument of the macro is the
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009415// test suite name; the rest are the names of the tests in this test
Austin Schuh70cc9552019-01-21 19:46:48 -08009416// case.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009417REGISTER_TYPED_TEST_SUITE_P(FooTest,
9418 DoesBlah, HasPropertyA);
Austin Schuh70cc9552019-01-21 19:46:48 -08009419
9420// Finally, you are free to instantiate the pattern with the types you
9421// want. If you put the above code in a header file, you can #include
9422// it in multiple C++ source files and instantiate it multiple times.
9423//
9424// To distinguish different instances of the pattern, the first
9425// argument to the INSTANTIATE_* macro is a prefix that will be added
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009426// to the actual test suite name. Remember to pick unique prefixes for
Austin Schuh70cc9552019-01-21 19:46:48 -08009427// different instances.
9428typedef testing::Types<char, int, unsigned int> MyTypes;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009429INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
Austin Schuh70cc9552019-01-21 19:46:48 -08009430
9431// If the type list contains only one type, you can write that type
9432// directly without Types<...>:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009433// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
9434//
9435// Similar to the optional argument of TYPED_TEST_SUITE above,
9436// INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to
9437// generate custom names.
9438// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);
Austin Schuh70cc9552019-01-21 19:46:48 -08009439
9440#endif // 0
9441
9442
9443// Implements typed tests.
9444
Austin Schuh70cc9552019-01-21 19:46:48 -08009445// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9446//
9447// Expands to the name of the typedef for the type parameters of the
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009448// given test suite.
9449#define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_
9450
9451// Expands to the name of the typedef for the NameGenerator, responsible for
9452// creating the suffixes of the name.
9453#define GTEST_NAME_GENERATOR_(TestSuiteName) \
9454 gtest_type_params_##TestSuiteName##_NameGenerator
Austin Schuh70cc9552019-01-21 19:46:48 -08009455
Austin Schuh3de38b02024-06-25 18:25:10 -07009456#define TYPED_TEST_SUITE(CaseName, Types, ...) \
9457 typedef ::testing::internal::GenerateTypeList<Types>::type \
9458 GTEST_TYPE_PARAMS_(CaseName); \
9459 typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009460 GTEST_NAME_GENERATOR_(CaseName)
Austin Schuh70cc9552019-01-21 19:46:48 -08009461
Austin Schuh3de38b02024-06-25 18:25:10 -07009462#define TYPED_TEST(CaseName, TestName) \
9463 static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \
9464 "test-name must not be empty"); \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009465 template <typename gtest_TypeParam_> \
9466 class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
9467 : public CaseName<gtest_TypeParam_> { \
9468 private: \
9469 typedef CaseName<gtest_TypeParam_> TestFixture; \
9470 typedef gtest_TypeParam_ TypeParam; \
Austin Schuh3de38b02024-06-25 18:25:10 -07009471 void TestBody() override; \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009472 }; \
9473 static bool gtest_##CaseName##_##TestName##_registered_ \
Austin Schuh3de38b02024-06-25 18:25:10 -07009474 GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009475 CaseName, \
9476 ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
9477 TestName)>, \
9478 GTEST_TYPE_PARAMS_( \
9479 CaseName)>::Register("", \
9480 ::testing::internal::CodeLocation( \
9481 __FILE__, __LINE__), \
Austin Schuh3de38b02024-06-25 18:25:10 -07009482 GTEST_STRINGIFY_(CaseName), \
9483 GTEST_STRINGIFY_(TestName), 0, \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009484 ::testing::internal::GenerateNames< \
9485 GTEST_NAME_GENERATOR_(CaseName), \
9486 GTEST_TYPE_PARAMS_(CaseName)>()); \
9487 template <typename gtest_TypeParam_> \
9488 void GTEST_TEST_CLASS_NAME_(CaseName, \
9489 TestName)<gtest_TypeParam_>::TestBody()
9490
9491// Legacy API is deprecated but still available
9492#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9493#define TYPED_TEST_CASE \
9494 static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \
9495 TYPED_TEST_SUITE
9496#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -08009497
Austin Schuh70cc9552019-01-21 19:46:48 -08009498// Implements type-parameterized tests.
9499
Austin Schuh70cc9552019-01-21 19:46:48 -08009500// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9501//
9502// Expands to the namespace name that the type-parameterized tests for
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009503// the given type-parameterized test suite are defined in. The exact
Austin Schuh70cc9552019-01-21 19:46:48 -08009504// name of the namespace is subject to change without notice.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009505#define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_
Austin Schuh70cc9552019-01-21 19:46:48 -08009506
9507// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9508//
9509// Expands to the name of the variable used to remember the names of
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009510// the defined tests in the given test suite.
9511#define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \
9512 gtest_typed_test_suite_p_state_##TestSuiteName##_
Austin Schuh70cc9552019-01-21 19:46:48 -08009513
9514// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
9515//
9516// Expands to the name of the variable used to remember the names of
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009517// the registered tests in the given test suite.
9518#define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \
9519 gtest_registered_test_names_##TestSuiteName##_
Austin Schuh70cc9552019-01-21 19:46:48 -08009520
9521// The variables defined in the type-parameterized test macros are
9522// static as typically these macros are used in a .h file that can be
9523// #included in multiple translation units linked together.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009524#define TYPED_TEST_SUITE_P(SuiteName) \
9525 static ::testing::internal::TypedTestSuitePState \
9526 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
Austin Schuh70cc9552019-01-21 19:46:48 -08009527
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009528// Legacy API is deprecated but still available
9529#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9530#define TYPED_TEST_CASE_P \
9531 static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \
9532 TYPED_TEST_SUITE_P
9533#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -08009534
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009535#define TYPED_TEST_P(SuiteName, TestName) \
9536 namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
9537 template <typename gtest_TypeParam_> \
9538 class TestName : public SuiteName<gtest_TypeParam_> { \
9539 private: \
9540 typedef SuiteName<gtest_TypeParam_> TestFixture; \
9541 typedef gtest_TypeParam_ TypeParam; \
Austin Schuh3de38b02024-06-25 18:25:10 -07009542 void TestBody() override; \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009543 }; \
9544 static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
9545 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
Austin Schuh3de38b02024-06-25 18:25:10 -07009546 __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
9547 GTEST_STRINGIFY_(TestName)); \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009548 } \
9549 template <typename gtest_TypeParam_> \
9550 void GTEST_SUITE_NAMESPACE_( \
9551 SuiteName)::TestName<gtest_TypeParam_>::TestBody()
9552
Austin Schuh3de38b02024-06-25 18:25:10 -07009553// Note: this won't work correctly if the trailing arguments are macros.
9554#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
9555 namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
9556 typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
9557 } \
9558 static const char* const GTEST_REGISTERED_TEST_NAMES_( \
9559 SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
9560 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
9561 GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
Austin Schuh70cc9552019-01-21 19:46:48 -08009562
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009563// Legacy API is deprecated but still available
9564#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9565#define REGISTER_TYPED_TEST_CASE_P \
9566 static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \
9567 ""); \
9568 REGISTER_TYPED_TEST_SUITE_P
9569#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9570
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009571#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
Austin Schuh3de38b02024-06-25 18:25:10 -07009572 static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \
9573 "test-suit-prefix must not be empty"); \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009574 static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
9575 ::testing::internal::TypeParameterizedTestSuite< \
9576 SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
Austin Schuh3de38b02024-06-25 18:25:10 -07009577 ::testing::internal::GenerateTypeList<Types>::type>:: \
9578 Register(GTEST_STRINGIFY_(Prefix), \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009579 ::testing::internal::CodeLocation(__FILE__, __LINE__), \
Austin Schuh3de38b02024-06-25 18:25:10 -07009580 &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \
9581 GTEST_STRINGIFY_(SuiteName), \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009582 GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
9583 ::testing::internal::GenerateNames< \
9584 ::testing::internal::NameGeneratorSelector< \
9585 __VA_ARGS__>::type, \
Austin Schuh3de38b02024-06-25 18:25:10 -07009586 ::testing::internal::GenerateTypeList<Types>::type>())
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009587
9588// Legacy API is deprecated but still available
9589#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9590#define INSTANTIATE_TYPED_TEST_CASE_P \
9591 static_assert( \
9592 ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \
9593 INSTANTIATE_TYPED_TEST_SUITE_P
9594#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -08009595
Austin Schuh3de38b02024-06-25 18:25:10 -07009596#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
Austin Schuh70cc9552019-01-21 19:46:48 -08009597
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009598GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
9599/* class A needs to have dll-interface to be used by clients of class B */)
9600
Austin Schuh70cc9552019-01-21 19:46:48 -08009601namespace testing {
9602
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009603// Silence C4100 (unreferenced formal parameter) and 4805
9604// unsafe mix of type 'const int' and type 'const bool'
9605#ifdef _MSC_VER
9606# pragma warning(push)
9607# pragma warning(disable:4805)
9608# pragma warning(disable:4100)
9609#endif
9610
9611
Austin Schuh70cc9552019-01-21 19:46:48 -08009612// Declares the flags.
9613
9614// This flag temporary enables the disabled tests.
9615GTEST_DECLARE_bool_(also_run_disabled_tests);
9616
9617// This flag brings the debugger on an assertion failure.
9618GTEST_DECLARE_bool_(break_on_failure);
9619
9620// This flag controls whether Google Test catches all test-thrown exceptions
9621// and logs them as failures.
9622GTEST_DECLARE_bool_(catch_exceptions);
9623
9624// This flag enables using colors in terminal output. Available values are
9625// "yes" to enable colors, "no" (disable colors), or "auto" (the default)
9626// to let Google Test decide.
9627GTEST_DECLARE_string_(color);
9628
Austin Schuh3de38b02024-06-25 18:25:10 -07009629// This flag controls whether the test runner should continue execution past
9630// first failure.
9631GTEST_DECLARE_bool_(fail_fast);
9632
Austin Schuh70cc9552019-01-21 19:46:48 -08009633// This flag sets up the filter to select by name using a glob pattern
9634// the tests to run. If the filter is not given all tests are executed.
9635GTEST_DECLARE_string_(filter);
9636
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009637// This flag controls whether Google Test installs a signal handler that dumps
9638// debugging information when fatal signals are raised.
9639GTEST_DECLARE_bool_(install_failure_signal_handler);
9640
Austin Schuh70cc9552019-01-21 19:46:48 -08009641// This flag causes the Google Test to list tests. None of the tests listed
9642// are actually run if the flag is provided.
9643GTEST_DECLARE_bool_(list_tests);
9644
9645// This flag controls whether Google Test emits a detailed XML report to a file
9646// in addition to its normal textual output.
9647GTEST_DECLARE_string_(output);
9648
Austin Schuh3de38b02024-06-25 18:25:10 -07009649// This flags control whether Google Test prints only test failures.
9650GTEST_DECLARE_bool_(brief);
9651
Austin Schuh70cc9552019-01-21 19:46:48 -08009652// This flags control whether Google Test prints the elapsed time for each
9653// test.
9654GTEST_DECLARE_bool_(print_time);
9655
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009656// This flags control whether Google Test prints UTF8 characters as text.
9657GTEST_DECLARE_bool_(print_utf8);
9658
Austin Schuh70cc9552019-01-21 19:46:48 -08009659// This flag specifies the random number seed.
9660GTEST_DECLARE_int32_(random_seed);
9661
9662// This flag sets how many times the tests are repeated. The default value
9663// is 1. If the value is -1 the tests are repeating forever.
9664GTEST_DECLARE_int32_(repeat);
9665
9666// This flag controls whether Google Test includes Google Test internal
9667// stack frames in failure stack traces.
9668GTEST_DECLARE_bool_(show_internal_stack_frames);
9669
9670// When this flag is specified, tests' order is randomized on every iteration.
9671GTEST_DECLARE_bool_(shuffle);
9672
9673// This flag specifies the maximum number of stack frames to be
9674// printed in a failure message.
9675GTEST_DECLARE_int32_(stack_trace_depth);
9676
9677// When this flag is specified, a failed assertion will throw an
9678// exception if exceptions are enabled, or exit the program with a
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009679// non-zero code otherwise. For use with an external test framework.
Austin Schuh70cc9552019-01-21 19:46:48 -08009680GTEST_DECLARE_bool_(throw_on_failure);
9681
9682// When this flag is set with a "host:port" string, on supported
9683// platforms test results are streamed to the specified port on
9684// the specified host machine.
9685GTEST_DECLARE_string_(stream_result_to);
9686
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009687#if GTEST_USE_OWN_FLAGFILE_FLAG_
9688GTEST_DECLARE_string_(flagfile);
9689#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
9690
Austin Schuh70cc9552019-01-21 19:46:48 -08009691// The upper limit for valid stack trace depths.
9692const int kMaxStackTraceDepth = 100;
9693
9694namespace internal {
9695
9696class AssertHelper;
9697class DefaultGlobalTestPartResultReporter;
9698class ExecDeathTest;
9699class NoExecDeathTest;
9700class FinalSuccessChecker;
9701class GTestFlagSaver;
9702class StreamingListenerTest;
9703class TestResultAccessor;
9704class TestEventListenersAccessor;
9705class TestEventRepeater;
9706class UnitTestRecordPropertyTestHelper;
9707class WindowsDeathTest;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009708class FuchsiaDeathTest;
Austin Schuh70cc9552019-01-21 19:46:48 -08009709class UnitTestImpl* GetUnitTestImpl();
9710void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
9711 const std::string& message);
Austin Schuh3de38b02024-06-25 18:25:10 -07009712std::set<std::string>* GetIgnoredParameterizedTestSuites();
Austin Schuh70cc9552019-01-21 19:46:48 -08009713
9714} // namespace internal
9715
9716// The friend relationship of some of these classes is cyclic.
9717// If we don't forward declare them the compiler might confuse the classes
9718// in friendship clauses with same named classes on the scope.
9719class Test;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009720class TestSuite;
9721
9722// Old API is still available but deprecated
9723#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9724using TestCase = TestSuite;
9725#endif
Austin Schuh70cc9552019-01-21 19:46:48 -08009726class TestInfo;
9727class UnitTest;
9728
9729// A class for indicating whether an assertion was successful. When
9730// the assertion wasn't successful, the AssertionResult object
9731// remembers a non-empty message that describes how it failed.
9732//
9733// To create an instance of this class, use one of the factory functions
9734// (AssertionSuccess() and AssertionFailure()).
9735//
9736// This class is useful for two purposes:
9737// 1. Defining predicate functions to be used with Boolean test assertions
9738// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
9739// 2. Defining predicate-format functions to be
9740// used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
9741//
9742// For example, if you define IsEven predicate:
9743//
9744// testing::AssertionResult IsEven(int n) {
9745// if ((n % 2) == 0)
9746// return testing::AssertionSuccess();
9747// else
9748// return testing::AssertionFailure() << n << " is odd";
9749// }
9750//
9751// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
9752// will print the message
9753//
9754// Value of: IsEven(Fib(5))
9755// Actual: false (5 is odd)
9756// Expected: true
9757//
9758// instead of a more opaque
9759//
9760// Value of: IsEven(Fib(5))
9761// Actual: false
9762// Expected: true
9763//
9764// in case IsEven is a simple Boolean predicate.
9765//
9766// If you expect your predicate to be reused and want to support informative
9767// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
9768// about half as often as positive ones in our tests), supply messages for
9769// both success and failure cases:
9770//
9771// testing::AssertionResult IsEven(int n) {
9772// if ((n % 2) == 0)
9773// return testing::AssertionSuccess() << n << " is even";
9774// else
9775// return testing::AssertionFailure() << n << " is odd";
9776// }
9777//
9778// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
9779//
9780// Value of: IsEven(Fib(6))
9781// Actual: true (8 is even)
9782// Expected: false
9783//
9784// NB: Predicates that support negative Boolean assertions have reduced
9785// performance in positive ones so be careful not to use them in tests
9786// that have lots (tens of thousands) of positive Boolean assertions.
9787//
9788// To use this class with EXPECT_PRED_FORMAT assertions such as:
9789//
9790// // Verifies that Foo() returns an even number.
9791// EXPECT_PRED_FORMAT1(IsEven, Foo());
9792//
9793// you need to define:
9794//
9795// testing::AssertionResult IsEven(const char* expr, int n) {
9796// if ((n % 2) == 0)
9797// return testing::AssertionSuccess();
9798// else
9799// return testing::AssertionFailure()
9800// << "Expected: " << expr << " is even\n Actual: it's " << n;
9801// }
9802//
9803// If Foo() returns 5, you will see the following message:
9804//
9805// Expected: Foo() is even
9806// Actual: it's 5
9807//
9808class GTEST_API_ AssertionResult {
9809 public:
9810 // Copy constructor.
9811 // Used in EXPECT_TRUE/FALSE(assertion_result).
9812 AssertionResult(const AssertionResult& other);
9813
Austin Schuh3de38b02024-06-25 18:25:10 -07009814// C4800 is a level 3 warning in Visual Studio 2015 and earlier.
9815// This warning is not emitted in Visual Studio 2017.
9816// This warning is off by default starting in Visual Studio 2019 but can be
9817// enabled with command-line options.
9818#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
Austin Schuh70cc9552019-01-21 19:46:48 -08009819 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009820#endif
Austin Schuh70cc9552019-01-21 19:46:48 -08009821
9822 // Used in the EXPECT_TRUE/FALSE(bool_expression).
9823 //
9824 // T must be contextually convertible to bool.
9825 //
9826 // The second parameter prevents this overload from being considered if
9827 // the argument is implicitly convertible to AssertionResult. In that case
9828 // we want AssertionResult's copy constructor to be used.
9829 template <typename T>
9830 explicit AssertionResult(
9831 const T& success,
Austin Schuh3de38b02024-06-25 18:25:10 -07009832 typename std::enable_if<
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009833 !std::is_convertible<T, AssertionResult>::value>::type*
9834 /*enabler*/
9835 = nullptr)
Austin Schuh70cc9552019-01-21 19:46:48 -08009836 : success_(success) {}
9837
Austin Schuh3de38b02024-06-25 18:25:10 -07009838#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
Austin Schuh70cc9552019-01-21 19:46:48 -08009839 GTEST_DISABLE_MSC_WARNINGS_POP_()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009840#endif
Austin Schuh70cc9552019-01-21 19:46:48 -08009841
9842 // Assignment operator.
9843 AssertionResult& operator=(AssertionResult other) {
9844 swap(other);
9845 return *this;
9846 }
9847
Austin Schuh3de38b02024-06-25 18:25:10 -07009848 // Returns true if and only if the assertion succeeded.
Austin Schuh70cc9552019-01-21 19:46:48 -08009849 operator bool() const { return success_; } // NOLINT
9850
9851 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
9852 AssertionResult operator!() const;
9853
9854 // Returns the text streamed into this AssertionResult. Test assertions
9855 // use it when they fail (i.e., the predicate's outcome doesn't match the
9856 // assertion's expectation). When nothing has been streamed into the
9857 // object, returns an empty string.
9858 const char* message() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009859 return message_.get() != nullptr ? message_->c_str() : "";
Austin Schuh70cc9552019-01-21 19:46:48 -08009860 }
Austin Schuh70cc9552019-01-21 19:46:48 -08009861 // Deprecated; please use message() instead.
9862 const char* failure_message() const { return message(); }
9863
9864 // Streams a custom failure message into this object.
9865 template <typename T> AssertionResult& operator<<(const T& value) {
9866 AppendMessage(Message() << value);
9867 return *this;
9868 }
9869
9870 // Allows streaming basic output manipulators such as endl or flush into
9871 // this object.
9872 AssertionResult& operator<<(
9873 ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
9874 AppendMessage(Message() << basic_manipulator);
9875 return *this;
9876 }
9877
9878 private:
9879 // Appends the contents of message to message_.
9880 void AppendMessage(const Message& a_message) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009881 if (message_.get() == nullptr) message_.reset(new ::std::string);
Austin Schuh70cc9552019-01-21 19:46:48 -08009882 message_->append(a_message.GetString().c_str());
9883 }
9884
9885 // Swap the contents of this AssertionResult with other.
9886 void swap(AssertionResult& other);
9887
9888 // Stores result of the assertion predicate.
9889 bool success_;
9890 // Stores the message describing the condition in case the expectation
9891 // construct is not satisfied with the predicate's outcome.
9892 // Referenced via a pointer to avoid taking too much stack frame space
9893 // with test assertions.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009894 std::unique_ptr< ::std::string> message_;
Austin Schuh70cc9552019-01-21 19:46:48 -08009895};
9896
9897// Makes a successful assertion result.
9898GTEST_API_ AssertionResult AssertionSuccess();
9899
9900// Makes a failed assertion result.
9901GTEST_API_ AssertionResult AssertionFailure();
9902
9903// Makes a failed assertion result with the given failure message.
9904// Deprecated; use AssertionFailure() << msg.
9905GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
9906
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009907} // namespace testing
9908
9909// Includes the auto-generated header that implements a family of generic
9910// predicate assertion macros. This include comes late because it relies on
9911// APIs declared above.
9912// Copyright 2006, Google Inc.
9913// All rights reserved.
9914//
9915// Redistribution and use in source and binary forms, with or without
9916// modification, are permitted provided that the following conditions are
9917// met:
9918//
9919// * Redistributions of source code must retain the above copyright
9920// notice, this list of conditions and the following disclaimer.
9921// * Redistributions in binary form must reproduce the above
9922// copyright notice, this list of conditions and the following disclaimer
9923// in the documentation and/or other materials provided with the
9924// distribution.
9925// * Neither the name of Google Inc. nor the names of its
9926// contributors may be used to endorse or promote products derived from
9927// this software without specific prior written permission.
9928//
9929// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9930// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9931// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9932// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9933// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9934// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9935// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9936// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9937// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9938// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9939// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9940
9941// This file is AUTOMATICALLY GENERATED on 01/02/2019 by command
9942// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
9943//
9944// Implements a family of generic predicate assertion macros.
9945// GOOGLETEST_CM0001 DO NOT DELETE
9946
Austin Schuh3de38b02024-06-25 18:25:10 -07009947#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
9948#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -08009949
9950
9951namespace testing {
9952
9953// This header implements a family of generic predicate assertion
9954// macros:
9955//
9956// ASSERT_PRED_FORMAT1(pred_format, v1)
9957// ASSERT_PRED_FORMAT2(pred_format, v1, v2)
9958// ...
9959//
9960// where pred_format is a function or functor that takes n (in the
9961// case of ASSERT_PRED_FORMATn) values and their source expression
9962// text, and returns a testing::AssertionResult. See the definition
9963// of ASSERT_EQ in gtest.h for an example.
9964//
9965// If you don't care about formatting, you can use the more
9966// restrictive version:
9967//
9968// ASSERT_PRED1(pred, v1)
9969// ASSERT_PRED2(pred, v1, v2)
9970// ...
9971//
9972// where pred is an n-ary function or functor that returns bool,
9973// and the values v1, v2, ..., must support the << operator for
9974// streaming to std::ostream.
9975//
9976// We also define the EXPECT_* variations.
9977//
9978// For now we only support predicates whose arity is at most 5.
9979// Please email googletestframework@googlegroups.com if you need
9980// support for higher arities.
9981
9982// GTEST_ASSERT_ is the basic statement to which all of the assertions
9983// in this file reduce. Don't use this in your code.
9984
9985#define GTEST_ASSERT_(expression, on_failure) \
9986 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
9987 if (const ::testing::AssertionResult gtest_ar = (expression)) \
9988 ; \
9989 else \
9990 on_failure(gtest_ar.failure_message())
9991
9992
9993// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
9994// this in your code.
9995template <typename Pred,
9996 typename T1>
9997AssertionResult AssertPred1Helper(const char* pred_text,
9998 const char* e1,
9999 Pred pred,
10000 const T1& v1) {
10001 if (pred(v1)) return AssertionSuccess();
10002
10003 return AssertionFailure()
10004 << pred_text << "(" << e1 << ") evaluates to false, where"
10005 << "\n"
10006 << e1 << " evaluates to " << ::testing::PrintToString(v1);
10007}
10008
10009// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
10010// Don't use this in your code.
10011#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
10012 GTEST_ASSERT_(pred_format(#v1, v1), \
10013 on_failure)
10014
10015// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
10016// this in your code.
10017#define GTEST_PRED1_(pred, v1, on_failure)\
10018 GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
10019 #v1, \
10020 pred, \
10021 v1), on_failure)
10022
10023// Unary predicate assertion macros.
10024#define EXPECT_PRED_FORMAT1(pred_format, v1) \
10025 GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
10026#define EXPECT_PRED1(pred, v1) \
10027 GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
10028#define ASSERT_PRED_FORMAT1(pred_format, v1) \
10029 GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
10030#define ASSERT_PRED1(pred, v1) \
10031 GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
10032
10033
10034
10035// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
10036// this in your code.
10037template <typename Pred,
10038 typename T1,
10039 typename T2>
10040AssertionResult AssertPred2Helper(const char* pred_text,
10041 const char* e1,
10042 const char* e2,
10043 Pred pred,
10044 const T1& v1,
10045 const T2& v2) {
10046 if (pred(v1, v2)) return AssertionSuccess();
10047
10048 return AssertionFailure()
10049 << pred_text << "(" << e1 << ", " << e2
10050 << ") evaluates to false, where"
10051 << "\n"
10052 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10053 << e2 << " evaluates to " << ::testing::PrintToString(v2);
10054}
10055
10056// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
10057// Don't use this in your code.
10058#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
10059 GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
10060 on_failure)
10061
10062// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
10063// this in your code.
10064#define GTEST_PRED2_(pred, v1, v2, on_failure)\
10065 GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
10066 #v1, \
10067 #v2, \
10068 pred, \
10069 v1, \
10070 v2), on_failure)
10071
10072// Binary predicate assertion macros.
10073#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
10074 GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
10075#define EXPECT_PRED2(pred, v1, v2) \
10076 GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
10077#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
10078 GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
10079#define ASSERT_PRED2(pred, v1, v2) \
10080 GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
10081
10082
10083
10084// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
10085// this in your code.
10086template <typename Pred,
10087 typename T1,
10088 typename T2,
10089 typename T3>
10090AssertionResult AssertPred3Helper(const char* pred_text,
10091 const char* e1,
10092 const char* e2,
10093 const char* e3,
10094 Pred pred,
10095 const T1& v1,
10096 const T2& v2,
10097 const T3& v3) {
10098 if (pred(v1, v2, v3)) return AssertionSuccess();
10099
10100 return AssertionFailure()
10101 << pred_text << "(" << e1 << ", " << e2 << ", " << e3
10102 << ") evaluates to false, where"
10103 << "\n"
10104 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10105 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10106 << e3 << " evaluates to " << ::testing::PrintToString(v3);
10107}
10108
10109// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
10110// Don't use this in your code.
10111#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
10112 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
10113 on_failure)
10114
10115// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
10116// this in your code.
10117#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
10118 GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
10119 #v1, \
10120 #v2, \
10121 #v3, \
10122 pred, \
10123 v1, \
10124 v2, \
10125 v3), on_failure)
10126
10127// Ternary predicate assertion macros.
10128#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
10129 GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
10130#define EXPECT_PRED3(pred, v1, v2, v3) \
10131 GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
10132#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
10133 GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
10134#define ASSERT_PRED3(pred, v1, v2, v3) \
10135 GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
10136
10137
10138
10139// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
10140// this in your code.
10141template <typename Pred,
10142 typename T1,
10143 typename T2,
10144 typename T3,
10145 typename T4>
10146AssertionResult AssertPred4Helper(const char* pred_text,
10147 const char* e1,
10148 const char* e2,
10149 const char* e3,
10150 const char* e4,
10151 Pred pred,
10152 const T1& v1,
10153 const T2& v2,
10154 const T3& v3,
10155 const T4& v4) {
10156 if (pred(v1, v2, v3, v4)) return AssertionSuccess();
10157
10158 return AssertionFailure()
10159 << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
10160 << ") evaluates to false, where"
10161 << "\n"
10162 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10163 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10164 << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
10165 << e4 << " evaluates to " << ::testing::PrintToString(v4);
10166}
10167
10168// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
10169// Don't use this in your code.
10170#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
10171 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
10172 on_failure)
10173
10174// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
10175// this in your code.
10176#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
10177 GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
10178 #v1, \
10179 #v2, \
10180 #v3, \
10181 #v4, \
10182 pred, \
10183 v1, \
10184 v2, \
10185 v3, \
10186 v4), on_failure)
10187
10188// 4-ary predicate assertion macros.
10189#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
10190 GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
10191#define EXPECT_PRED4(pred, v1, v2, v3, v4) \
10192 GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
10193#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
10194 GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
10195#define ASSERT_PRED4(pred, v1, v2, v3, v4) \
10196 GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
10197
10198
10199
10200// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
10201// this in your code.
10202template <typename Pred,
10203 typename T1,
10204 typename T2,
10205 typename T3,
10206 typename T4,
10207 typename T5>
10208AssertionResult AssertPred5Helper(const char* pred_text,
10209 const char* e1,
10210 const char* e2,
10211 const char* e3,
10212 const char* e4,
10213 const char* e5,
10214 Pred pred,
10215 const T1& v1,
10216 const T2& v2,
10217 const T3& v3,
10218 const T4& v4,
10219 const T5& v5) {
10220 if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
10221
10222 return AssertionFailure()
10223 << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
10224 << ", " << e5 << ") evaluates to false, where"
10225 << "\n"
10226 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10227 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10228 << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
10229 << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n"
10230 << e5 << " evaluates to " << ::testing::PrintToString(v5);
10231}
10232
10233// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
10234// Don't use this in your code.
10235#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
10236 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
10237 on_failure)
10238
10239// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
10240// this in your code.
10241#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
10242 GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
10243 #v1, \
10244 #v2, \
10245 #v3, \
10246 #v4, \
10247 #v5, \
10248 pred, \
10249 v1, \
10250 v2, \
10251 v3, \
10252 v4, \
10253 v5), on_failure)
10254
10255// 5-ary predicate assertion macros.
10256#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
10257 GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
10258#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
10259 GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
10260#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
10261 GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
10262#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
10263 GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
10264
10265
10266
10267} // namespace testing
10268
Austin Schuh3de38b02024-06-25 18:25:10 -070010269#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010270
10271namespace testing {
10272
Austin Schuh70cc9552019-01-21 19:46:48 -080010273// The abstract class that all tests inherit from.
10274//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010275// In Google Test, a unit test program contains one or many TestSuites, and
10276// each TestSuite contains one or many Tests.
Austin Schuh70cc9552019-01-21 19:46:48 -080010277//
10278// When you define a test using the TEST macro, you don't need to
10279// explicitly derive from Test - the TEST macro automatically does
10280// this for you.
10281//
10282// The only time you derive from Test is when defining a test fixture
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010283// to be used in a TEST_F. For example:
Austin Schuh70cc9552019-01-21 19:46:48 -080010284//
10285// class FooTest : public testing::Test {
10286// protected:
10287// void SetUp() override { ... }
10288// void TearDown() override { ... }
10289// ...
10290// };
10291//
10292// TEST_F(FooTest, Bar) { ... }
10293// TEST_F(FooTest, Baz) { ... }
10294//
10295// Test is not copyable.
10296class GTEST_API_ Test {
10297 public:
10298 friend class TestInfo;
10299
Austin Schuh70cc9552019-01-21 19:46:48 -080010300 // The d'tor is virtual as we intend to inherit from Test.
10301 virtual ~Test();
10302
Austin Schuh3de38b02024-06-25 18:25:10 -070010303 // Sets up the stuff shared by all tests in this test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010304 //
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010305 // Google Test will call Foo::SetUpTestSuite() before running the first
Austin Schuh3de38b02024-06-25 18:25:10 -070010306 // test in test suite Foo. Hence a sub-class can define its own
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010307 // SetUpTestSuite() method to shadow the one defined in the super
Austin Schuh70cc9552019-01-21 19:46:48 -080010308 // class.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010309 static void SetUpTestSuite() {}
Austin Schuh70cc9552019-01-21 19:46:48 -080010310
Austin Schuh3de38b02024-06-25 18:25:10 -070010311 // Tears down the stuff shared by all tests in this test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010312 //
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010313 // Google Test will call Foo::TearDownTestSuite() after running the last
Austin Schuh3de38b02024-06-25 18:25:10 -070010314 // test in test suite Foo. Hence a sub-class can define its own
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010315 // TearDownTestSuite() method to shadow the one defined in the super
Austin Schuh70cc9552019-01-21 19:46:48 -080010316 // class.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010317 static void TearDownTestSuite() {}
10318
Austin Schuh3de38b02024-06-25 18:25:10 -070010319 // Legacy API is deprecated but still available. Use SetUpTestSuite and
10320 // TearDownTestSuite instead.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010321#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -080010322 static void TearDownTestCase() {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010323 static void SetUpTestCase() {}
10324#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -080010325
Austin Schuh3de38b02024-06-25 18:25:10 -070010326 // Returns true if and only if the current test has a fatal failure.
Austin Schuh70cc9552019-01-21 19:46:48 -080010327 static bool HasFatalFailure();
10328
Austin Schuh3de38b02024-06-25 18:25:10 -070010329 // Returns true if and only if the current test has a non-fatal failure.
Austin Schuh70cc9552019-01-21 19:46:48 -080010330 static bool HasNonfatalFailure();
10331
Austin Schuh3de38b02024-06-25 18:25:10 -070010332 // Returns true if and only if the current test was skipped.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010333 static bool IsSkipped();
10334
Austin Schuh3de38b02024-06-25 18:25:10 -070010335 // Returns true if and only if the current test has a (either fatal or
Austin Schuh70cc9552019-01-21 19:46:48 -080010336 // non-fatal) failure.
10337 static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
10338
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010339 // Logs a property for the current test, test suite, or for the entire
Austin Schuh70cc9552019-01-21 19:46:48 -080010340 // invocation of the test program when used outside of the context of a
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010341 // test suite. Only the last value for a given key is remembered. These
Austin Schuh70cc9552019-01-21 19:46:48 -080010342 // are public static so they can be called from utility functions that are
10343 // not members of the test fixture. Calls to RecordProperty made during
10344 // lifespan of the test (from the moment its constructor starts to the
10345 // moment its destructor finishes) will be output in XML as attributes of
10346 // the <testcase> element. Properties recorded from fixture's
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010347 // SetUpTestSuite or TearDownTestSuite are logged as attributes of the
Austin Schuh70cc9552019-01-21 19:46:48 -080010348 // corresponding <testsuite> element. Calls to RecordProperty made in the
10349 // global context (before or after invocation of RUN_ALL_TESTS and from
10350 // SetUp/TearDown method of Environment objects registered with Google
10351 // Test) will be output as attributes of the <testsuites> element.
10352 static void RecordProperty(const std::string& key, const std::string& value);
10353 static void RecordProperty(const std::string& key, int value);
10354
10355 protected:
10356 // Creates a Test object.
10357 Test();
10358
10359 // Sets up the test fixture.
10360 virtual void SetUp();
10361
10362 // Tears down the test fixture.
10363 virtual void TearDown();
10364
10365 private:
Austin Schuh3de38b02024-06-25 18:25:10 -070010366 // Returns true if and only if the current test has the same fixture class
10367 // as the first test in the current test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010368 static bool HasSameFixtureClass();
10369
10370 // Runs the test after the test fixture has been set up.
10371 //
10372 // A sub-class must implement this to define the test logic.
10373 //
10374 // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
10375 // Instead, use the TEST or TEST_F macro.
10376 virtual void TestBody() = 0;
10377
10378 // Sets up, executes, and tears down the test.
10379 void Run();
10380
10381 // Deletes self. We deliberately pick an unusual name for this
10382 // internal method to avoid clashing with names used in user TESTs.
10383 void DeleteSelf_() { delete this; }
10384
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010385 const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;
Austin Schuh70cc9552019-01-21 19:46:48 -080010386
10387 // Often a user misspells SetUp() as Setup() and spends a long time
10388 // wondering why it is never called by Google Test. The declaration of
10389 // the following method is solely for catching such an error at
10390 // compile time:
10391 //
10392 // - The return type is deliberately chosen to be not void, so it
10393 // will be a conflict if void Setup() is declared in the user's
10394 // test fixture.
10395 //
10396 // - This method is private, so it will be another compiler error
10397 // if the method is called from the user's test fixture.
10398 //
10399 // DO NOT OVERRIDE THIS FUNCTION.
10400 //
10401 // If you see an error about overriding the following function or
10402 // about it being private, you have mis-spelled SetUp() as Setup().
10403 struct Setup_should_be_spelled_SetUp {};
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010404 virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
Austin Schuh70cc9552019-01-21 19:46:48 -080010405
10406 // We disallow copying Tests.
10407 GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
10408};
10409
10410typedef internal::TimeInMillis TimeInMillis;
10411
10412// A copyable object representing a user specified test property which can be
10413// output as a key/value string pair.
10414//
10415// Don't inherit from TestProperty as its destructor is not virtual.
10416class TestProperty {
10417 public:
10418 // C'tor. TestProperty does NOT have a default constructor.
10419 // Always use this constructor (with parameters) to create a
10420 // TestProperty object.
10421 TestProperty(const std::string& a_key, const std::string& a_value) :
10422 key_(a_key), value_(a_value) {
10423 }
10424
10425 // Gets the user supplied key.
10426 const char* key() const {
10427 return key_.c_str();
10428 }
10429
10430 // Gets the user supplied value.
10431 const char* value() const {
10432 return value_.c_str();
10433 }
10434
10435 // Sets a new value, overriding the one supplied in the constructor.
10436 void SetValue(const std::string& new_value) {
10437 value_ = new_value;
10438 }
10439
10440 private:
10441 // The key supplied by the user.
10442 std::string key_;
10443 // The value supplied by the user.
10444 std::string value_;
10445};
10446
10447// The result of a single Test. This includes a list of
10448// TestPartResults, a list of TestProperties, a count of how many
10449// death tests there are in the Test, and how much time it took to run
10450// the Test.
10451//
10452// TestResult is not copyable.
10453class GTEST_API_ TestResult {
10454 public:
10455 // Creates an empty TestResult.
10456 TestResult();
10457
10458 // D'tor. Do not inherit from TestResult.
10459 ~TestResult();
10460
10461 // Gets the number of all test parts. This is the sum of the number
10462 // of successful test parts and the number of failed test parts.
10463 int total_part_count() const;
10464
10465 // Returns the number of the test properties.
10466 int test_property_count() const;
10467
Austin Schuh3de38b02024-06-25 18:25:10 -070010468 // Returns true if and only if the test passed (i.e. no test part failed).
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010469 bool Passed() const { return !Skipped() && !Failed(); }
10470
Austin Schuh3de38b02024-06-25 18:25:10 -070010471 // Returns true if and only if the test was skipped.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010472 bool Skipped() const;
Austin Schuh70cc9552019-01-21 19:46:48 -080010473
Austin Schuh3de38b02024-06-25 18:25:10 -070010474 // Returns true if and only if the test failed.
Austin Schuh70cc9552019-01-21 19:46:48 -080010475 bool Failed() const;
10476
Austin Schuh3de38b02024-06-25 18:25:10 -070010477 // Returns true if and only if the test fatally failed.
Austin Schuh70cc9552019-01-21 19:46:48 -080010478 bool HasFatalFailure() const;
10479
Austin Schuh3de38b02024-06-25 18:25:10 -070010480 // Returns true if and only if the test has a non-fatal failure.
Austin Schuh70cc9552019-01-21 19:46:48 -080010481 bool HasNonfatalFailure() const;
10482
10483 // Returns the elapsed time, in milliseconds.
10484 TimeInMillis elapsed_time() const { return elapsed_time_; }
10485
Austin Schuh3de38b02024-06-25 18:25:10 -070010486 // Gets the time of the test case start, in ms from the start of the
10487 // UNIX epoch.
10488 TimeInMillis start_timestamp() const { return start_timestamp_; }
10489
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010490 // Returns the i-th test part result among all the results. i can range from 0
10491 // to total_part_count() - 1. If i is not in that range, aborts the program.
Austin Schuh70cc9552019-01-21 19:46:48 -080010492 const TestPartResult& GetTestPartResult(int i) const;
10493
10494 // Returns the i-th test property. i can range from 0 to
10495 // test_property_count() - 1. If i is not in that range, aborts the
10496 // program.
10497 const TestProperty& GetTestProperty(int i) const;
10498
10499 private:
10500 friend class TestInfo;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010501 friend class TestSuite;
Austin Schuh70cc9552019-01-21 19:46:48 -080010502 friend class UnitTest;
10503 friend class internal::DefaultGlobalTestPartResultReporter;
10504 friend class internal::ExecDeathTest;
10505 friend class internal::TestResultAccessor;
10506 friend class internal::UnitTestImpl;
10507 friend class internal::WindowsDeathTest;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010508 friend class internal::FuchsiaDeathTest;
Austin Schuh70cc9552019-01-21 19:46:48 -080010509
10510 // Gets the vector of TestPartResults.
10511 const std::vector<TestPartResult>& test_part_results() const {
10512 return test_part_results_;
10513 }
10514
10515 // Gets the vector of TestProperties.
10516 const std::vector<TestProperty>& test_properties() const {
10517 return test_properties_;
10518 }
10519
Austin Schuh3de38b02024-06-25 18:25:10 -070010520 // Sets the start time.
10521 void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }
10522
Austin Schuh70cc9552019-01-21 19:46:48 -080010523 // Sets the elapsed time.
10524 void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
10525
10526 // Adds a test property to the list. The property is validated and may add
10527 // a non-fatal failure if invalid (e.g., if it conflicts with reserved
10528 // key names). If a property is already recorded for the same key, the
10529 // value will be updated, rather than storing multiple values for the same
10530 // key. xml_element specifies the element for which the property is being
10531 // recorded and is used for validation.
10532 void RecordProperty(const std::string& xml_element,
10533 const TestProperty& test_property);
10534
10535 // Adds a failure if the key is a reserved attribute of Google Test
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010536 // testsuite tags. Returns true if the property is valid.
10537 // FIXME: Validate attribute names are legal and human readable.
Austin Schuh70cc9552019-01-21 19:46:48 -080010538 static bool ValidateTestProperty(const std::string& xml_element,
10539 const TestProperty& test_property);
10540
10541 // Adds a test part result to the list.
10542 void AddTestPartResult(const TestPartResult& test_part_result);
10543
10544 // Returns the death test count.
10545 int death_test_count() const { return death_test_count_; }
10546
10547 // Increments the death test count, returning the new count.
10548 int increment_death_test_count() { return ++death_test_count_; }
10549
10550 // Clears the test part results.
10551 void ClearTestPartResults();
10552
10553 // Clears the object.
10554 void Clear();
10555
10556 // Protects mutable state of the property vector and of owned
10557 // properties, whose values may be updated.
Austin Schuh3de38b02024-06-25 18:25:10 -070010558 internal::Mutex test_properties_mutex_;
Austin Schuh70cc9552019-01-21 19:46:48 -080010559
10560 // The vector of TestPartResults
10561 std::vector<TestPartResult> test_part_results_;
10562 // The vector of TestProperties
10563 std::vector<TestProperty> test_properties_;
10564 // Running count of death tests.
10565 int death_test_count_;
Austin Schuh3de38b02024-06-25 18:25:10 -070010566 // The start time, in milliseconds since UNIX Epoch.
10567 TimeInMillis start_timestamp_;
Austin Schuh70cc9552019-01-21 19:46:48 -080010568 // The elapsed time, in milliseconds.
10569 TimeInMillis elapsed_time_;
10570
10571 // We disallow copying TestResult.
10572 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
10573}; // class TestResult
10574
10575// A TestInfo object stores the following information about a test:
10576//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010577// Test suite name
Austin Schuh70cc9552019-01-21 19:46:48 -080010578// Test name
10579// Whether the test should be run
10580// A function pointer that creates the test object when invoked
10581// Test result
10582//
10583// The constructor of TestInfo registers itself with the UnitTest
10584// singleton such that the RUN_ALL_TESTS() macro knows which tests to
10585// run.
10586class GTEST_API_ TestInfo {
10587 public:
10588 // Destructs a TestInfo object. This function is not virtual, so
10589 // don't inherit from TestInfo.
10590 ~TestInfo();
10591
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010592 // Returns the test suite name.
10593 const char* test_suite_name() const { return test_suite_name_.c_str(); }
10594
10595// Legacy API is deprecated but still available
10596#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10597 const char* test_case_name() const { return test_suite_name(); }
10598#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -080010599
10600 // Returns the test name.
10601 const char* name() const { return name_.c_str(); }
10602
10603 // Returns the name of the parameter type, or NULL if this is not a typed
10604 // or a type-parameterized test.
10605 const char* type_param() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010606 if (type_param_.get() != nullptr) return type_param_->c_str();
10607 return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080010608 }
10609
10610 // Returns the text representation of the value parameter, or NULL if this
10611 // is not a value-parameterized test.
10612 const char* value_param() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010613 if (value_param_.get() != nullptr) return value_param_->c_str();
10614 return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080010615 }
10616
10617 // Returns the file name where this test is defined.
10618 const char* file() const { return location_.file.c_str(); }
10619
10620 // Returns the line where this test is defined.
10621 int line() const { return location_.line; }
10622
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010623 // Return true if this test should not be run because it's in another shard.
10624 bool is_in_another_shard() const { return is_in_another_shard_; }
10625
Austin Schuh70cc9552019-01-21 19:46:48 -080010626 // Returns true if this test should run, that is if the test is not
10627 // disabled (or it is disabled but the also_run_disabled_tests flag has
10628 // been specified) and its full name matches the user-specified filter.
10629 //
10630 // Google Test allows the user to filter the tests by their full names.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010631 // The full name of a test Bar in test suite Foo is defined as
Austin Schuh70cc9552019-01-21 19:46:48 -080010632 // "Foo.Bar". Only the tests that match the filter will run.
10633 //
10634 // A filter is a colon-separated list of glob (not regex) patterns,
10635 // optionally followed by a '-' and a colon-separated list of
10636 // negative patterns (tests to exclude). A test is run if it
10637 // matches one of the positive patterns and does not match any of
10638 // the negative patterns.
10639 //
10640 // For example, *A*:Foo.* is a filter that matches any string that
10641 // contains the character 'A' or starts with "Foo.".
10642 bool should_run() const { return should_run_; }
10643
Austin Schuh3de38b02024-06-25 18:25:10 -070010644 // Returns true if and only if this test will appear in the XML report.
Austin Schuh70cc9552019-01-21 19:46:48 -080010645 bool is_reportable() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010646 // The XML report includes tests matching the filter, excluding those
10647 // run in other shards.
10648 return matches_filter_ && !is_in_another_shard_;
Austin Schuh70cc9552019-01-21 19:46:48 -080010649 }
10650
10651 // Returns the result of the test.
10652 const TestResult* result() const { return &result_; }
10653
10654 private:
10655#if GTEST_HAS_DEATH_TEST
10656 friend class internal::DefaultDeathTestFactory;
10657#endif // GTEST_HAS_DEATH_TEST
10658 friend class Test;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010659 friend class TestSuite;
Austin Schuh70cc9552019-01-21 19:46:48 -080010660 friend class internal::UnitTestImpl;
10661 friend class internal::StreamingListenerTest;
10662 friend TestInfo* internal::MakeAndRegisterTestInfo(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010663 const char* test_suite_name, const char* name, const char* type_param,
10664 const char* value_param, internal::CodeLocation code_location,
10665 internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
10666 internal::TearDownTestSuiteFunc tear_down_tc,
Austin Schuh70cc9552019-01-21 19:46:48 -080010667 internal::TestFactoryBase* factory);
10668
10669 // Constructs a TestInfo object. The newly constructed instance assumes
10670 // ownership of the factory object.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010671 TestInfo(const std::string& test_suite_name, const std::string& name,
Austin Schuh70cc9552019-01-21 19:46:48 -080010672 const char* a_type_param, // NULL if not a type-parameterized test
10673 const char* a_value_param, // NULL if not a value-parameterized test
10674 internal::CodeLocation a_code_location,
10675 internal::TypeId fixture_class_id,
10676 internal::TestFactoryBase* factory);
10677
10678 // Increments the number of death tests encountered in this test so
10679 // far.
10680 int increment_death_test_count() {
10681 return result_.increment_death_test_count();
10682 }
10683
10684 // Creates the test object, runs it, records its result, and then
10685 // deletes it.
10686 void Run();
10687
Austin Schuh3de38b02024-06-25 18:25:10 -070010688 // Skip and records the test result for this object.
10689 void Skip();
10690
Austin Schuh70cc9552019-01-21 19:46:48 -080010691 static void ClearTestResult(TestInfo* test_info) {
10692 test_info->result_.Clear();
10693 }
10694
10695 // These fields are immutable properties of the test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010696 const std::string test_suite_name_; // test suite name
Austin Schuh70cc9552019-01-21 19:46:48 -080010697 const std::string name_; // Test name
10698 // Name of the parameter type, or NULL if this is not a typed or a
10699 // type-parameterized test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010700 const std::unique_ptr<const ::std::string> type_param_;
Austin Schuh70cc9552019-01-21 19:46:48 -080010701 // Text representation of the value parameter, or NULL if this is not a
10702 // value-parameterized test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010703 const std::unique_ptr<const ::std::string> value_param_;
Austin Schuh70cc9552019-01-21 19:46:48 -080010704 internal::CodeLocation location_;
Austin Schuh3de38b02024-06-25 18:25:10 -070010705 const internal::TypeId fixture_class_id_; // ID of the test fixture class
10706 bool should_run_; // True if and only if this test should run
10707 bool is_disabled_; // True if and only if this test is disabled
10708 bool matches_filter_; // True if this test matches the
10709 // user-specified filter.
10710 bool is_in_another_shard_; // Will be run in another shard.
Austin Schuh70cc9552019-01-21 19:46:48 -080010711 internal::TestFactoryBase* const factory_; // The factory that creates
10712 // the test object
10713
10714 // This field is mutable and needs to be reset before running the
10715 // test for the second time.
10716 TestResult result_;
10717
10718 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
10719};
10720
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010721// A test suite, which consists of a vector of TestInfos.
Austin Schuh70cc9552019-01-21 19:46:48 -080010722//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010723// TestSuite is not copyable.
10724class GTEST_API_ TestSuite {
Austin Schuh70cc9552019-01-21 19:46:48 -080010725 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010726 // Creates a TestSuite with the given name.
Austin Schuh70cc9552019-01-21 19:46:48 -080010727 //
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010728 // TestSuite does NOT have a default constructor. Always use this
10729 // constructor to create a TestSuite object.
Austin Schuh70cc9552019-01-21 19:46:48 -080010730 //
10731 // Arguments:
10732 //
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010733 // name: name of the test suite
Austin Schuh70cc9552019-01-21 19:46:48 -080010734 // a_type_param: the name of the test's type parameter, or NULL if
10735 // this is not a type-parameterized test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010736 // set_up_tc: pointer to the function that sets up the test suite
10737 // tear_down_tc: pointer to the function that tears down the test suite
10738 TestSuite(const char* name, const char* a_type_param,
10739 internal::SetUpTestSuiteFunc set_up_tc,
10740 internal::TearDownTestSuiteFunc tear_down_tc);
Austin Schuh70cc9552019-01-21 19:46:48 -080010741
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010742 // Destructor of TestSuite.
10743 virtual ~TestSuite();
Austin Schuh70cc9552019-01-21 19:46:48 -080010744
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010745 // Gets the name of the TestSuite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010746 const char* name() const { return name_.c_str(); }
10747
10748 // Returns the name of the parameter type, or NULL if this is not a
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010749 // type-parameterized test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010750 const char* type_param() const {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010751 if (type_param_.get() != nullptr) return type_param_->c_str();
10752 return nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080010753 }
10754
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010755 // Returns true if any test in this test suite should run.
Austin Schuh70cc9552019-01-21 19:46:48 -080010756 bool should_run() const { return should_run_; }
10757
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010758 // Gets the number of successful tests in this test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010759 int successful_test_count() const;
10760
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010761 // Gets the number of skipped tests in this test suite.
10762 int skipped_test_count() const;
10763
10764 // Gets the number of failed tests in this test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010765 int failed_test_count() const;
10766
10767 // Gets the number of disabled tests that will be reported in the XML report.
10768 int reportable_disabled_test_count() const;
10769
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010770 // Gets the number of disabled tests in this test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010771 int disabled_test_count() const;
10772
10773 // Gets the number of tests to be printed in the XML report.
10774 int reportable_test_count() const;
10775
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010776 // Get the number of tests in this test suite that should run.
Austin Schuh70cc9552019-01-21 19:46:48 -080010777 int test_to_run_count() const;
10778
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010779 // Gets the number of all tests in this test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010780 int total_test_count() const;
10781
Austin Schuh3de38b02024-06-25 18:25:10 -070010782 // Returns true if and only if the test suite passed.
Austin Schuh70cc9552019-01-21 19:46:48 -080010783 bool Passed() const { return !Failed(); }
10784
Austin Schuh3de38b02024-06-25 18:25:10 -070010785 // Returns true if and only if the test suite failed.
10786 bool Failed() const {
10787 return failed_test_count() > 0 || ad_hoc_test_result().Failed();
10788 }
Austin Schuh70cc9552019-01-21 19:46:48 -080010789
10790 // Returns the elapsed time, in milliseconds.
10791 TimeInMillis elapsed_time() const { return elapsed_time_; }
10792
Austin Schuh3de38b02024-06-25 18:25:10 -070010793 // Gets the time of the test suite start, in ms from the start of the
10794 // UNIX epoch.
10795 TimeInMillis start_timestamp() const { return start_timestamp_; }
10796
Austin Schuh70cc9552019-01-21 19:46:48 -080010797 // Returns the i-th test among all the tests. i can range from 0 to
10798 // total_test_count() - 1. If i is not in that range, returns NULL.
10799 const TestInfo* GetTestInfo(int i) const;
10800
10801 // Returns the TestResult that holds test properties recorded during
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010802 // execution of SetUpTestSuite and TearDownTestSuite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010803 const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
10804
10805 private:
10806 friend class Test;
10807 friend class internal::UnitTestImpl;
10808
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010809 // Gets the (mutable) vector of TestInfos in this TestSuite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010810 std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
10811
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010812 // Gets the (immutable) vector of TestInfos in this TestSuite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010813 const std::vector<TestInfo*>& test_info_list() const {
10814 return test_info_list_;
10815 }
10816
10817 // Returns the i-th test among all the tests. i can range from 0 to
10818 // total_test_count() - 1. If i is not in that range, returns NULL.
10819 TestInfo* GetMutableTestInfo(int i);
10820
10821 // Sets the should_run member.
10822 void set_should_run(bool should) { should_run_ = should; }
10823
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010824 // Adds a TestInfo to this test suite. Will delete the TestInfo upon
10825 // destruction of the TestSuite object.
Austin Schuh70cc9552019-01-21 19:46:48 -080010826 void AddTestInfo(TestInfo * test_info);
10827
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010828 // Clears the results of all tests in this test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010829 void ClearResult();
10830
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010831 // Clears the results of all tests in the given test suite.
10832 static void ClearTestSuiteResult(TestSuite* test_suite) {
10833 test_suite->ClearResult();
Austin Schuh70cc9552019-01-21 19:46:48 -080010834 }
10835
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010836 // Runs every test in this TestSuite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010837 void Run();
10838
Austin Schuh3de38b02024-06-25 18:25:10 -070010839 // Skips the execution of tests under this TestSuite
10840 void Skip();
10841
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010842 // Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
10843 // for catching exceptions thrown from SetUpTestSuite().
10844 void RunSetUpTestSuite() {
10845 if (set_up_tc_ != nullptr) {
10846 (*set_up_tc_)();
10847 }
10848 }
Austin Schuh70cc9552019-01-21 19:46:48 -080010849
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010850 // Runs TearDownTestSuite() for this TestSuite. This wrapper is
10851 // needed for catching exceptions thrown from TearDownTestSuite().
10852 void RunTearDownTestSuite() {
10853 if (tear_down_tc_ != nullptr) {
10854 (*tear_down_tc_)();
10855 }
10856 }
Austin Schuh70cc9552019-01-21 19:46:48 -080010857
Austin Schuh3de38b02024-06-25 18:25:10 -070010858 // Returns true if and only if test passed.
Austin Schuh70cc9552019-01-21 19:46:48 -080010859 static bool TestPassed(const TestInfo* test_info) {
10860 return test_info->should_run() && test_info->result()->Passed();
10861 }
10862
Austin Schuh3de38b02024-06-25 18:25:10 -070010863 // Returns true if and only if test skipped.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010864 static bool TestSkipped(const TestInfo* test_info) {
10865 return test_info->should_run() && test_info->result()->Skipped();
10866 }
10867
Austin Schuh3de38b02024-06-25 18:25:10 -070010868 // Returns true if and only if test failed.
Austin Schuh70cc9552019-01-21 19:46:48 -080010869 static bool TestFailed(const TestInfo* test_info) {
10870 return test_info->should_run() && test_info->result()->Failed();
10871 }
10872
Austin Schuh3de38b02024-06-25 18:25:10 -070010873 // Returns true if and only if the test is disabled and will be reported in
10874 // the XML report.
Austin Schuh70cc9552019-01-21 19:46:48 -080010875 static bool TestReportableDisabled(const TestInfo* test_info) {
10876 return test_info->is_reportable() && test_info->is_disabled_;
10877 }
10878
Austin Schuh3de38b02024-06-25 18:25:10 -070010879 // Returns true if and only if test is disabled.
Austin Schuh70cc9552019-01-21 19:46:48 -080010880 static bool TestDisabled(const TestInfo* test_info) {
10881 return test_info->is_disabled_;
10882 }
10883
Austin Schuh3de38b02024-06-25 18:25:10 -070010884 // Returns true if and only if this test will appear in the XML report.
Austin Schuh70cc9552019-01-21 19:46:48 -080010885 static bool TestReportable(const TestInfo* test_info) {
10886 return test_info->is_reportable();
10887 }
10888
10889 // Returns true if the given test should run.
10890 static bool ShouldRunTest(const TestInfo* test_info) {
10891 return test_info->should_run();
10892 }
10893
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010894 // Shuffles the tests in this test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010895 void ShuffleTests(internal::Random* random);
10896
10897 // Restores the test order to before the first shuffle.
10898 void UnshuffleTests();
10899
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010900 // Name of the test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010901 std::string name_;
10902 // Name of the parameter type, or NULL if this is not a typed or a
10903 // type-parameterized test.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010904 const std::unique_ptr<const ::std::string> type_param_;
Austin Schuh70cc9552019-01-21 19:46:48 -080010905 // The vector of TestInfos in their original order. It owns the
10906 // elements in the vector.
10907 std::vector<TestInfo*> test_info_list_;
10908 // Provides a level of indirection for the test list to allow easy
10909 // shuffling and restoring the test order. The i-th element in this
10910 // vector is the index of the i-th test in the shuffled test list.
10911 std::vector<int> test_indices_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010912 // Pointer to the function that sets up the test suite.
10913 internal::SetUpTestSuiteFunc set_up_tc_;
10914 // Pointer to the function that tears down the test suite.
10915 internal::TearDownTestSuiteFunc tear_down_tc_;
Austin Schuh3de38b02024-06-25 18:25:10 -070010916 // True if and only if any test in this test suite should run.
Austin Schuh70cc9552019-01-21 19:46:48 -080010917 bool should_run_;
Austin Schuh3de38b02024-06-25 18:25:10 -070010918 // The start time, in milliseconds since UNIX Epoch.
10919 TimeInMillis start_timestamp_;
Austin Schuh70cc9552019-01-21 19:46:48 -080010920 // Elapsed time, in milliseconds.
10921 TimeInMillis elapsed_time_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010922 // Holds test properties recorded during execution of SetUpTestSuite and
10923 // TearDownTestSuite.
Austin Schuh70cc9552019-01-21 19:46:48 -080010924 TestResult ad_hoc_test_result_;
10925
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010926 // We disallow copying TestSuites.
10927 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite);
Austin Schuh70cc9552019-01-21 19:46:48 -080010928};
10929
10930// An Environment object is capable of setting up and tearing down an
10931// environment. You should subclass this to define your own
10932// environment(s).
10933//
10934// An Environment object does the set-up and tear-down in virtual
10935// methods SetUp() and TearDown() instead of the constructor and the
10936// destructor, as:
10937//
10938// 1. You cannot safely throw from a destructor. This is a problem
10939// as in some cases Google Test is used where exceptions are enabled, and
10940// we may want to implement ASSERT_* using exceptions where they are
10941// available.
10942// 2. You cannot use ASSERT_* directly in a constructor or
10943// destructor.
10944class Environment {
10945 public:
10946 // The d'tor is virtual as we need to subclass Environment.
10947 virtual ~Environment() {}
10948
10949 // Override this to define how to set up the environment.
10950 virtual void SetUp() {}
10951
10952 // Override this to define how to tear down the environment.
10953 virtual void TearDown() {}
10954 private:
10955 // If you see an error about overriding the following function or
10956 // about it being private, you have mis-spelled SetUp() as Setup().
10957 struct Setup_should_be_spelled_SetUp {};
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010958 virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
Austin Schuh70cc9552019-01-21 19:46:48 -080010959};
10960
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010961#if GTEST_HAS_EXCEPTIONS
10962
10963// Exception which can be thrown from TestEventListener::OnTestPartResult.
10964class GTEST_API_ AssertionException
10965 : public internal::GoogleTestFailureException {
10966 public:
10967 explicit AssertionException(const TestPartResult& result)
10968 : GoogleTestFailureException(result) {}
10969};
10970
10971#endif // GTEST_HAS_EXCEPTIONS
10972
Austin Schuh70cc9552019-01-21 19:46:48 -080010973// The interface for tracing execution of tests. The methods are organized in
10974// the order the corresponding events are fired.
10975class TestEventListener {
10976 public:
10977 virtual ~TestEventListener() {}
10978
10979 // Fired before any test activity starts.
10980 virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
10981
10982 // Fired before each iteration of tests starts. There may be more than
10983 // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
10984 // index, starting from 0.
10985 virtual void OnTestIterationStart(const UnitTest& unit_test,
10986 int iteration) = 0;
10987
10988 // Fired before environment set-up for each iteration of tests starts.
10989 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
10990
10991 // Fired after environment set-up for each iteration of tests ends.
10992 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
10993
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080010994 // Fired before the test suite starts.
10995 virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}
10996
10997 // Legacy API is deprecated but still available
10998#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10999 virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
11000#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -080011001
11002 // Fired before the test starts.
11003 virtual void OnTestStart(const TestInfo& test_info) = 0;
11004
11005 // Fired after a failed assertion or a SUCCEED() invocation.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011006 // If you want to throw an exception from this function to skip to the next
11007 // TEST, it must be AssertionException defined above, or inherited from it.
Austin Schuh70cc9552019-01-21 19:46:48 -080011008 virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
11009
11010 // Fired after the test ends.
11011 virtual void OnTestEnd(const TestInfo& test_info) = 0;
11012
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011013 // Fired after the test suite ends.
11014 virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}
11015
11016// Legacy API is deprecated but still available
11017#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11018 virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
11019#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -080011020
11021 // Fired before environment tear-down for each iteration of tests starts.
11022 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
11023
11024 // Fired after environment tear-down for each iteration of tests ends.
11025 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
11026
11027 // Fired after each iteration of tests finishes.
11028 virtual void OnTestIterationEnd(const UnitTest& unit_test,
11029 int iteration) = 0;
11030
11031 // Fired after all test activities have ended.
11032 virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
11033};
11034
11035// The convenience class for users who need to override just one or two
11036// methods and are not concerned that a possible change to a signature of
11037// the methods they override will not be caught during the build. For
11038// comments about each method please see the definition of TestEventListener
11039// above.
11040class EmptyTestEventListener : public TestEventListener {
11041 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011042 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
11043 void OnTestIterationStart(const UnitTest& /*unit_test*/,
11044 int /*iteration*/) override {}
11045 void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
11046 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
11047 void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
11048// Legacy API is deprecated but still available
11049#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11050 void OnTestCaseStart(const TestCase& /*test_case*/) override {}
11051#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11052
11053 void OnTestStart(const TestInfo& /*test_info*/) override {}
11054 void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
11055 void OnTestEnd(const TestInfo& /*test_info*/) override {}
11056 void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
11057#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11058 void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
11059#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11060
11061 void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
11062 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
11063 void OnTestIterationEnd(const UnitTest& /*unit_test*/,
11064 int /*iteration*/) override {}
11065 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
Austin Schuh70cc9552019-01-21 19:46:48 -080011066};
11067
11068// TestEventListeners lets users add listeners to track events in Google Test.
11069class GTEST_API_ TestEventListeners {
11070 public:
11071 TestEventListeners();
11072 ~TestEventListeners();
11073
11074 // Appends an event listener to the end of the list. Google Test assumes
11075 // the ownership of the listener (i.e. it will delete the listener when
11076 // the test program finishes).
11077 void Append(TestEventListener* listener);
11078
11079 // Removes the given event listener from the list and returns it. It then
11080 // becomes the caller's responsibility to delete the listener. Returns
11081 // NULL if the listener is not found in the list.
11082 TestEventListener* Release(TestEventListener* listener);
11083
11084 // Returns the standard listener responsible for the default console
11085 // output. Can be removed from the listeners list to shut down default
11086 // console output. Note that removing this object from the listener list
11087 // with Release transfers its ownership to the caller and makes this
11088 // function return NULL the next time.
11089 TestEventListener* default_result_printer() const {
11090 return default_result_printer_;
11091 }
11092
11093 // Returns the standard listener responsible for the default XML output
11094 // controlled by the --gtest_output=xml flag. Can be removed from the
11095 // listeners list by users who want to shut down the default XML output
11096 // controlled by this flag and substitute it with custom one. Note that
11097 // removing this object from the listener list with Release transfers its
11098 // ownership to the caller and makes this function return NULL the next
11099 // time.
11100 TestEventListener* default_xml_generator() const {
11101 return default_xml_generator_;
11102 }
11103
11104 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011105 friend class TestSuite;
Austin Schuh70cc9552019-01-21 19:46:48 -080011106 friend class TestInfo;
11107 friend class internal::DefaultGlobalTestPartResultReporter;
11108 friend class internal::NoExecDeathTest;
11109 friend class internal::TestEventListenersAccessor;
11110 friend class internal::UnitTestImpl;
11111
11112 // Returns repeater that broadcasts the TestEventListener events to all
11113 // subscribers.
11114 TestEventListener* repeater();
11115
11116 // Sets the default_result_printer attribute to the provided listener.
11117 // The listener is also added to the listener list and previous
11118 // default_result_printer is removed from it and deleted. The listener can
11119 // also be NULL in which case it will not be added to the list. Does
11120 // nothing if the previous and the current listener objects are the same.
11121 void SetDefaultResultPrinter(TestEventListener* listener);
11122
11123 // Sets the default_xml_generator attribute to the provided listener. The
11124 // listener is also added to the listener list and previous
11125 // default_xml_generator is removed from it and deleted. The listener can
11126 // also be NULL in which case it will not be added to the list. Does
11127 // nothing if the previous and the current listener objects are the same.
11128 void SetDefaultXmlGenerator(TestEventListener* listener);
11129
11130 // Controls whether events will be forwarded by the repeater to the
11131 // listeners in the list.
11132 bool EventForwardingEnabled() const;
11133 void SuppressEventForwarding();
11134
11135 // The actual list of listeners.
11136 internal::TestEventRepeater* repeater_;
11137 // Listener responsible for the standard result output.
11138 TestEventListener* default_result_printer_;
11139 // Listener responsible for the creation of the XML output file.
11140 TestEventListener* default_xml_generator_;
11141
11142 // We disallow copying TestEventListeners.
11143 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
11144};
11145
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011146// A UnitTest consists of a vector of TestSuites.
Austin Schuh70cc9552019-01-21 19:46:48 -080011147//
11148// This is a singleton class. The only instance of UnitTest is
11149// created when UnitTest::GetInstance() is first called. This
11150// instance is never deleted.
11151//
11152// UnitTest is not copyable.
11153//
11154// This class is thread-safe as long as the methods are called
11155// according to their specification.
11156class GTEST_API_ UnitTest {
11157 public:
11158 // Gets the singleton UnitTest object. The first time this method
11159 // is called, a UnitTest object is constructed and returned.
11160 // Consecutive calls will return the same object.
11161 static UnitTest* GetInstance();
11162
11163 // Runs all tests in this UnitTest object and prints the result.
11164 // Returns 0 if successful, or 1 otherwise.
11165 //
11166 // This method can only be called from the main thread.
11167 //
11168 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11169 int Run() GTEST_MUST_USE_RESULT_;
11170
11171 // Returns the working directory when the first TEST() or TEST_F()
11172 // was executed. The UnitTest object owns the string.
11173 const char* original_working_dir() const;
11174
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011175 // Returns the TestSuite object for the test that's currently running,
Austin Schuh70cc9552019-01-21 19:46:48 -080011176 // or NULL if no test is running.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011177 const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);
11178
11179// Legacy API is still available but deprecated
11180#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11181 const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);
11182#endif
Austin Schuh70cc9552019-01-21 19:46:48 -080011183
11184 // Returns the TestInfo object for the test that's currently running,
11185 // or NULL if no test is running.
11186 const TestInfo* current_test_info() const
11187 GTEST_LOCK_EXCLUDED_(mutex_);
11188
11189 // Returns the random seed used at the start of the current test run.
11190 int random_seed() const;
11191
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011192 // Returns the ParameterizedTestSuiteRegistry object used to keep track of
Austin Schuh70cc9552019-01-21 19:46:48 -080011193 // value-parameterized tests and instantiate and register them.
11194 //
11195 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011196 internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()
Austin Schuh70cc9552019-01-21 19:46:48 -080011197 GTEST_LOCK_EXCLUDED_(mutex_);
Austin Schuh70cc9552019-01-21 19:46:48 -080011198
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011199 // Gets the number of successful test suites.
11200 int successful_test_suite_count() const;
Austin Schuh70cc9552019-01-21 19:46:48 -080011201
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011202 // Gets the number of failed test suites.
11203 int failed_test_suite_count() const;
Austin Schuh70cc9552019-01-21 19:46:48 -080011204
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011205 // Gets the number of all test suites.
11206 int total_test_suite_count() const;
Austin Schuh70cc9552019-01-21 19:46:48 -080011207
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011208 // Gets the number of all test suites that contain at least one test
Austin Schuh70cc9552019-01-21 19:46:48 -080011209 // that should run.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011210 int test_suite_to_run_count() const;
11211
11212 // Legacy API is deprecated but still available
11213#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11214 int successful_test_case_count() const;
11215 int failed_test_case_count() const;
11216 int total_test_case_count() const;
Austin Schuh70cc9552019-01-21 19:46:48 -080011217 int test_case_to_run_count() const;
Austin Schuh3de38b02024-06-25 18:25:10 -070011218#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -080011219
11220 // Gets the number of successful tests.
11221 int successful_test_count() const;
11222
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011223 // Gets the number of skipped tests.
11224 int skipped_test_count() const;
11225
Austin Schuh70cc9552019-01-21 19:46:48 -080011226 // Gets the number of failed tests.
11227 int failed_test_count() const;
11228
11229 // Gets the number of disabled tests that will be reported in the XML report.
11230 int reportable_disabled_test_count() const;
11231
11232 // Gets the number of disabled tests.
11233 int disabled_test_count() const;
11234
11235 // Gets the number of tests to be printed in the XML report.
11236 int reportable_test_count() const;
11237
11238 // Gets the number of all tests.
11239 int total_test_count() const;
11240
11241 // Gets the number of tests that should run.
11242 int test_to_run_count() const;
11243
11244 // Gets the time of the test program start, in ms from the start of the
11245 // UNIX epoch.
11246 TimeInMillis start_timestamp() const;
11247
11248 // Gets the elapsed time, in milliseconds.
11249 TimeInMillis elapsed_time() const;
11250
Austin Schuh3de38b02024-06-25 18:25:10 -070011251 // Returns true if and only if the unit test passed (i.e. all test suites
11252 // passed).
Austin Schuh70cc9552019-01-21 19:46:48 -080011253 bool Passed() const;
11254
Austin Schuh3de38b02024-06-25 18:25:10 -070011255 // Returns true if and only if the unit test failed (i.e. some test suite
11256 // failed or something outside of all tests failed).
Austin Schuh70cc9552019-01-21 19:46:48 -080011257 bool Failed() const;
11258
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011259 // Gets the i-th test suite among all the test suites. i can range from 0 to
11260 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
11261 const TestSuite* GetTestSuite(int i) const;
11262
11263// Legacy API is deprecated but still available
11264#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -080011265 const TestCase* GetTestCase(int i) const;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011266#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
Austin Schuh70cc9552019-01-21 19:46:48 -080011267
11268 // Returns the TestResult containing information on test failures and
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011269 // properties logged outside of individual test suites.
Austin Schuh70cc9552019-01-21 19:46:48 -080011270 const TestResult& ad_hoc_test_result() const;
11271
11272 // Returns the list of event listeners that can be used to track events
11273 // inside Google Test.
11274 TestEventListeners& listeners();
11275
11276 private:
11277 // Registers and returns a global test environment. When a test
11278 // program is run, all global test environments will be set-up in
11279 // the order they were registered. After all tests in the program
11280 // have finished, all global test environments will be torn-down in
11281 // the *reverse* order they were registered.
11282 //
11283 // The UnitTest object takes ownership of the given environment.
11284 //
11285 // This method can only be called from the main thread.
11286 Environment* AddEnvironment(Environment* env);
11287
11288 // Adds a TestPartResult to the current TestResult object. All
11289 // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
11290 // eventually call this to report their results. The user code
11291 // should use the assertion macros instead of calling this directly.
11292 void AddTestPartResult(TestPartResult::Type result_type,
11293 const char* file_name,
11294 int line_number,
11295 const std::string& message,
11296 const std::string& os_stack_trace)
11297 GTEST_LOCK_EXCLUDED_(mutex_);
11298
11299 // Adds a TestProperty to the current TestResult object when invoked from
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011300 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
11301 // from SetUpTestSuite or TearDownTestSuite, or to the global property set
Austin Schuh70cc9552019-01-21 19:46:48 -080011302 // when invoked elsewhere. If the result already contains a property with
11303 // the same key, the value will be updated.
11304 void RecordProperty(const std::string& key, const std::string& value);
11305
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011306 // Gets the i-th test suite among all the test suites. i can range from 0 to
11307 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
11308 TestSuite* GetMutableTestSuite(int i);
Austin Schuh70cc9552019-01-21 19:46:48 -080011309
11310 // Accessors for the implementation object.
11311 internal::UnitTestImpl* impl() { return impl_; }
11312 const internal::UnitTestImpl* impl() const { return impl_; }
11313
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011314 // These classes and functions are friends as they need to access private
Austin Schuh70cc9552019-01-21 19:46:48 -080011315 // members of UnitTest.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011316 friend class ScopedTrace;
Austin Schuh70cc9552019-01-21 19:46:48 -080011317 friend class Test;
11318 friend class internal::AssertHelper;
Austin Schuh70cc9552019-01-21 19:46:48 -080011319 friend class internal::StreamingListenerTest;
11320 friend class internal::UnitTestRecordPropertyTestHelper;
11321 friend Environment* AddGlobalTestEnvironment(Environment* env);
Austin Schuh3de38b02024-06-25 18:25:10 -070011322 friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
Austin Schuh70cc9552019-01-21 19:46:48 -080011323 friend internal::UnitTestImpl* internal::GetUnitTestImpl();
11324 friend void internal::ReportFailureInUnknownLocation(
11325 TestPartResult::Type result_type,
11326 const std::string& message);
11327
11328 // Creates an empty UnitTest.
11329 UnitTest();
11330
11331 // D'tor
11332 virtual ~UnitTest();
11333
11334 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
11335 // Google Test trace stack.
11336 void PushGTestTrace(const internal::TraceInfo& trace)
11337 GTEST_LOCK_EXCLUDED_(mutex_);
11338
11339 // Pops a trace from the per-thread Google Test trace stack.
11340 void PopGTestTrace()
11341 GTEST_LOCK_EXCLUDED_(mutex_);
11342
11343 // Protects mutable state in *impl_. This is mutable as some const
11344 // methods need to lock it too.
11345 mutable internal::Mutex mutex_;
11346
11347 // Opaque implementation object. This field is never changed once
11348 // the object is constructed. We don't mark it as const here, as
11349 // doing so will cause a warning in the constructor of UnitTest.
11350 // Mutable state in *impl_ is protected by mutex_.
11351 internal::UnitTestImpl* impl_;
11352
11353 // We disallow copying UnitTest.
11354 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
11355};
11356
11357// A convenient wrapper for adding an environment for the test
11358// program.
11359//
11360// You should call this before RUN_ALL_TESTS() is called, probably in
11361// main(). If you use gtest_main, you need to call this before main()
11362// starts for it to take effect. For example, you can define a global
11363// variable like this:
11364//
11365// testing::Environment* const foo_env =
11366// testing::AddGlobalTestEnvironment(new FooEnvironment);
11367//
11368// However, we strongly recommend you to write your own main() and
11369// call AddGlobalTestEnvironment() there, as relying on initialization
11370// of global variables makes the code harder to read and may cause
11371// problems when you register multiple environments from different
11372// translation units and the environments have dependencies among them
11373// (remember that the compiler doesn't guarantee the order in which
11374// global variables from different translation units are initialized).
11375inline Environment* AddGlobalTestEnvironment(Environment* env) {
11376 return UnitTest::GetInstance()->AddEnvironment(env);
11377}
11378
11379// Initializes Google Test. This must be called before calling
11380// RUN_ALL_TESTS(). In particular, it parses a command line for the
11381// flags that Google Test recognizes. Whenever a Google Test flag is
11382// seen, it is removed from argv, and *argc is decremented.
11383//
11384// No value is returned. Instead, the Google Test flag variables are
11385// updated.
11386//
11387// Calling the function for the second time has no user-visible effect.
11388GTEST_API_ void InitGoogleTest(int* argc, char** argv);
11389
11390// This overloaded version can be used in Windows programs compiled in
11391// UNICODE mode.
11392GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
11393
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011394// This overloaded version can be used on Arduino/embedded platforms where
11395// there is no argc/argv.
11396GTEST_API_ void InitGoogleTest();
11397
Austin Schuh70cc9552019-01-21 19:46:48 -080011398namespace internal {
11399
11400// Separate the error generating code from the code path to reduce the stack
11401// frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
11402// when calling EXPECT_* in a tight loop.
11403template <typename T1, typename T2>
11404AssertionResult CmpHelperEQFailure(const char* lhs_expression,
11405 const char* rhs_expression,
11406 const T1& lhs, const T2& rhs) {
11407 return EqFailure(lhs_expression,
11408 rhs_expression,
11409 FormatForComparisonFailureMessage(lhs, rhs),
11410 FormatForComparisonFailureMessage(rhs, lhs),
11411 false);
11412}
11413
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011414// This block of code defines operator==/!=
11415// to block lexical scope lookup.
11416// It prevents using invalid operator==/!= defined at namespace scope.
11417struct faketype {};
11418inline bool operator==(faketype, faketype) { return true; }
11419inline bool operator!=(faketype, faketype) { return false; }
11420
Austin Schuh70cc9552019-01-21 19:46:48 -080011421// The helper function for {ASSERT|EXPECT}_EQ.
11422template <typename T1, typename T2>
11423AssertionResult CmpHelperEQ(const char* lhs_expression,
11424 const char* rhs_expression,
11425 const T1& lhs,
11426 const T2& rhs) {
Austin Schuh70cc9552019-01-21 19:46:48 -080011427 if (lhs == rhs) {
11428 return AssertionSuccess();
11429 }
Austin Schuh70cc9552019-01-21 19:46:48 -080011430
11431 return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
11432}
11433
Austin Schuh70cc9552019-01-21 19:46:48 -080011434class EqHelper {
11435 public:
11436 // This templatized version is for the general case.
Austin Schuh3de38b02024-06-25 18:25:10 -070011437 template <
11438 typename T1, typename T2,
11439 // Disable this overload for cases where one argument is a pointer
11440 // and the other is the null pointer constant.
11441 typename std::enable_if<!std::is_integral<T1>::value ||
11442 !std::is_pointer<T2>::value>::type* = nullptr>
Austin Schuh70cc9552019-01-21 19:46:48 -080011443 static AssertionResult Compare(const char* lhs_expression,
Austin Schuh3de38b02024-06-25 18:25:10 -070011444 const char* rhs_expression, const T1& lhs,
Austin Schuh70cc9552019-01-21 19:46:48 -080011445 const T2& rhs) {
11446 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
11447 }
11448
11449 // With this overloaded version, we allow anonymous enums to be used
11450 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
11451 // enums can be implicitly cast to BiggestInt.
11452 //
11453 // Even though its body looks the same as the above version, we
11454 // cannot merge the two, as it will make anonymous enums unhappy.
11455 static AssertionResult Compare(const char* lhs_expression,
11456 const char* rhs_expression,
11457 BiggestInt lhs,
11458 BiggestInt rhs) {
11459 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
11460 }
Austin Schuh70cc9552019-01-21 19:46:48 -080011461
Austin Schuh70cc9552019-01-21 19:46:48 -080011462 template <typename T>
11463 static AssertionResult Compare(
Austin Schuh3de38b02024-06-25 18:25:10 -070011464 const char* lhs_expression, const char* rhs_expression,
11465 // Handle cases where '0' is used as a null pointer literal.
11466 std::nullptr_t /* lhs */, T* rhs) {
Austin Schuh70cc9552019-01-21 19:46:48 -080011467 // We already know that 'lhs' is a null pointer.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011468 return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),
11469 rhs);
Austin Schuh70cc9552019-01-21 19:46:48 -080011470 }
11471};
11472
11473// Separate the error generating code from the code path to reduce the stack
11474// frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
11475// when calling EXPECT_OP in a tight loop.
11476template <typename T1, typename T2>
11477AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
11478 const T1& val1, const T2& val2,
11479 const char* op) {
11480 return AssertionFailure()
11481 << "Expected: (" << expr1 << ") " << op << " (" << expr2
11482 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
11483 << " vs " << FormatForComparisonFailureMessage(val2, val1);
11484}
11485
11486// A macro for implementing the helper functions needed to implement
11487// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
11488// of similar code.
11489//
Austin Schuh70cc9552019-01-21 19:46:48 -080011490// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11491
11492#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
11493template <typename T1, typename T2>\
11494AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
11495 const T1& val1, const T2& val2) {\
11496 if (val1 op val2) {\
11497 return AssertionSuccess();\
11498 } else {\
11499 return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
11500 }\
Austin Schuh3de38b02024-06-25 18:25:10 -070011501}
Austin Schuh70cc9552019-01-21 19:46:48 -080011502
11503// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11504
11505// Implements the helper function for {ASSERT|EXPECT}_NE
Austin Schuh3de38b02024-06-25 18:25:10 -070011506GTEST_IMPL_CMP_HELPER_(NE, !=)
Austin Schuh70cc9552019-01-21 19:46:48 -080011507// Implements the helper function for {ASSERT|EXPECT}_LE
Austin Schuh3de38b02024-06-25 18:25:10 -070011508GTEST_IMPL_CMP_HELPER_(LE, <=)
Austin Schuh70cc9552019-01-21 19:46:48 -080011509// Implements the helper function for {ASSERT|EXPECT}_LT
Austin Schuh3de38b02024-06-25 18:25:10 -070011510GTEST_IMPL_CMP_HELPER_(LT, <)
Austin Schuh70cc9552019-01-21 19:46:48 -080011511// Implements the helper function for {ASSERT|EXPECT}_GE
Austin Schuh3de38b02024-06-25 18:25:10 -070011512GTEST_IMPL_CMP_HELPER_(GE, >=)
Austin Schuh70cc9552019-01-21 19:46:48 -080011513// Implements the helper function for {ASSERT|EXPECT}_GT
Austin Schuh3de38b02024-06-25 18:25:10 -070011514GTEST_IMPL_CMP_HELPER_(GT, >)
Austin Schuh70cc9552019-01-21 19:46:48 -080011515
11516#undef GTEST_IMPL_CMP_HELPER_
11517
11518// The helper function for {ASSERT|EXPECT}_STREQ.
11519//
11520// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11521GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
11522 const char* s2_expression,
11523 const char* s1,
11524 const char* s2);
11525
11526// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
11527//
11528// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11529GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
11530 const char* s2_expression,
11531 const char* s1,
11532 const char* s2);
11533
11534// The helper function for {ASSERT|EXPECT}_STRNE.
11535//
11536// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11537GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
11538 const char* s2_expression,
11539 const char* s1,
11540 const char* s2);
11541
11542// The helper function for {ASSERT|EXPECT}_STRCASENE.
11543//
11544// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11545GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
11546 const char* s2_expression,
11547 const char* s1,
11548 const char* s2);
11549
11550
11551// Helper function for *_STREQ on wide strings.
11552//
11553// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11554GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
11555 const char* s2_expression,
11556 const wchar_t* s1,
11557 const wchar_t* s2);
11558
11559// Helper function for *_STRNE on wide strings.
11560//
11561// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11562GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
11563 const char* s2_expression,
11564 const wchar_t* s1,
11565 const wchar_t* s2);
11566
11567} // namespace internal
11568
11569// IsSubstring() and IsNotSubstring() are intended to be used as the
11570// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
11571// themselves. They check whether needle is a substring of haystack
11572// (NULL is considered a substring of itself only), and return an
11573// appropriate error message when they fail.
11574//
11575// The {needle,haystack}_expr arguments are the stringified
11576// expressions that generated the two real arguments.
11577GTEST_API_ AssertionResult IsSubstring(
11578 const char* needle_expr, const char* haystack_expr,
11579 const char* needle, const char* haystack);
11580GTEST_API_ AssertionResult IsSubstring(
11581 const char* needle_expr, const char* haystack_expr,
11582 const wchar_t* needle, const wchar_t* haystack);
11583GTEST_API_ AssertionResult IsNotSubstring(
11584 const char* needle_expr, const char* haystack_expr,
11585 const char* needle, const char* haystack);
11586GTEST_API_ AssertionResult IsNotSubstring(
11587 const char* needle_expr, const char* haystack_expr,
11588 const wchar_t* needle, const wchar_t* haystack);
11589GTEST_API_ AssertionResult IsSubstring(
11590 const char* needle_expr, const char* haystack_expr,
11591 const ::std::string& needle, const ::std::string& haystack);
11592GTEST_API_ AssertionResult IsNotSubstring(
11593 const char* needle_expr, const char* haystack_expr,
11594 const ::std::string& needle, const ::std::string& haystack);
11595
11596#if GTEST_HAS_STD_WSTRING
11597GTEST_API_ AssertionResult IsSubstring(
11598 const char* needle_expr, const char* haystack_expr,
11599 const ::std::wstring& needle, const ::std::wstring& haystack);
11600GTEST_API_ AssertionResult IsNotSubstring(
11601 const char* needle_expr, const char* haystack_expr,
11602 const ::std::wstring& needle, const ::std::wstring& haystack);
11603#endif // GTEST_HAS_STD_WSTRING
11604
11605namespace internal {
11606
11607// Helper template function for comparing floating-points.
11608//
11609// Template parameter:
11610//
11611// RawType: the raw floating-point type (either float or double)
11612//
11613// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11614template <typename RawType>
11615AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
11616 const char* rhs_expression,
11617 RawType lhs_value,
11618 RawType rhs_value) {
11619 const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
11620
11621 if (lhs.AlmostEquals(rhs)) {
11622 return AssertionSuccess();
11623 }
11624
11625 ::std::stringstream lhs_ss;
11626 lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
11627 << lhs_value;
11628
11629 ::std::stringstream rhs_ss;
11630 rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
11631 << rhs_value;
11632
11633 return EqFailure(lhs_expression,
11634 rhs_expression,
11635 StringStreamToString(&lhs_ss),
11636 StringStreamToString(&rhs_ss),
11637 false);
11638}
11639
11640// Helper function for implementing ASSERT_NEAR.
11641//
11642// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11643GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
11644 const char* expr2,
11645 const char* abs_error_expr,
11646 double val1,
11647 double val2,
11648 double abs_error);
11649
11650// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
11651// A class that enables one to stream messages to assertion macros
11652class GTEST_API_ AssertHelper {
11653 public:
11654 // Constructor.
11655 AssertHelper(TestPartResult::Type type,
11656 const char* file,
11657 int line,
11658 const char* message);
11659 ~AssertHelper();
11660
11661 // Message assignment is a semantic trick to enable assertion
11662 // streaming; see the GTEST_MESSAGE_ macro below.
11663 void operator=(const Message& message) const;
11664
11665 private:
11666 // We put our data in a struct so that the size of the AssertHelper class can
11667 // be as small as possible. This is important because gcc is incapable of
11668 // re-using stack space even for temporary variables, so every EXPECT_EQ
11669 // reserves stack space for another AssertHelper.
11670 struct AssertHelperData {
11671 AssertHelperData(TestPartResult::Type t,
11672 const char* srcfile,
11673 int line_num,
11674 const char* msg)
11675 : type(t), file(srcfile), line(line_num), message(msg) { }
11676
11677 TestPartResult::Type const type;
11678 const char* const file;
11679 int const line;
11680 std::string const message;
11681
11682 private:
11683 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
11684 };
11685
11686 AssertHelperData* const data_;
11687
11688 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
11689};
11690
11691} // namespace internal
11692
Austin Schuh70cc9552019-01-21 19:46:48 -080011693// The pure interface class that all value-parameterized tests inherit from.
11694// A value-parameterized class must inherit from both ::testing::Test and
11695// ::testing::WithParamInterface. In most cases that just means inheriting
11696// from ::testing::TestWithParam, but more complicated test hierarchies
11697// may need to inherit from Test and WithParamInterface at different levels.
11698//
11699// This interface has support for accessing the test parameter value via
11700// the GetParam() method.
11701//
11702// Use it with one of the parameter generator defining functions, like Range(),
11703// Values(), ValuesIn(), Bool(), and Combine().
11704//
11705// class FooTest : public ::testing::TestWithParam<int> {
11706// protected:
11707// FooTest() {
11708// // Can use GetParam() here.
11709// }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011710// ~FooTest() override {
Austin Schuh70cc9552019-01-21 19:46:48 -080011711// // Can use GetParam() here.
11712// }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011713// void SetUp() override {
Austin Schuh70cc9552019-01-21 19:46:48 -080011714// // Can use GetParam() here.
11715// }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011716// void TearDown override {
Austin Schuh70cc9552019-01-21 19:46:48 -080011717// // Can use GetParam() here.
11718// }
11719// };
11720// TEST_P(FooTest, DoesBar) {
11721// // Can use GetParam() method here.
11722// Foo foo;
11723// ASSERT_TRUE(foo.DoesBar(GetParam()));
11724// }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011725// INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
Austin Schuh70cc9552019-01-21 19:46:48 -080011726
11727template <typename T>
11728class WithParamInterface {
11729 public:
11730 typedef T ParamType;
11731 virtual ~WithParamInterface() {}
11732
11733 // The current parameter value. Is also available in the test fixture's
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011734 // constructor.
11735 static const ParamType& GetParam() {
11736 GTEST_CHECK_(parameter_ != nullptr)
Austin Schuh70cc9552019-01-21 19:46:48 -080011737 << "GetParam() can only be called inside a value-parameterized test "
11738 << "-- did you intend to write TEST_P instead of TEST_F?";
11739 return *parameter_;
11740 }
11741
11742 private:
11743 // Sets parameter value. The caller is responsible for making sure the value
11744 // remains alive and unchanged throughout the current test.
11745 static void SetParam(const ParamType* parameter) {
11746 parameter_ = parameter;
11747 }
11748
11749 // Static value used for accessing parameter during a test lifetime.
11750 static const ParamType* parameter_;
11751
11752 // TestClass must be a subclass of WithParamInterface<T> and Test.
11753 template <class TestClass> friend class internal::ParameterizedTestFactory;
11754};
11755
11756template <typename T>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011757const T* WithParamInterface<T>::parameter_ = nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -080011758
11759// Most value-parameterized classes can ignore the existence of
11760// WithParamInterface, and can just inherit from ::testing::TestWithParam.
11761
11762template <typename T>
11763class TestWithParam : public Test, public WithParamInterface<T> {
11764};
11765
Austin Schuh70cc9552019-01-21 19:46:48 -080011766// Macros for indicating success/failure in test code.
11767
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011768// Skips test in runtime.
11769// Skipping test aborts current function.
11770// Skipped tests are neither successful nor failed.
Austin Schuh3de38b02024-06-25 18:25:10 -070011771#define GTEST_SKIP() GTEST_SKIP_("")
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011772
Austin Schuh70cc9552019-01-21 19:46:48 -080011773// ADD_FAILURE unconditionally adds a failure to the current test.
11774// SUCCEED generates a success - it doesn't automatically make the
11775// current test successful, as a test is only successful when it has
11776// no failure.
11777//
11778// EXPECT_* verifies that a certain condition is satisfied. If not,
11779// it behaves like ADD_FAILURE. In particular:
11780//
11781// EXPECT_TRUE verifies that a Boolean condition is true.
11782// EXPECT_FALSE verifies that a Boolean condition is false.
11783//
11784// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
11785// that they will also abort the current function on failure. People
11786// usually want the fail-fast behavior of FAIL and ASSERT_*, but those
11787// writing data-driven tests often find themselves using ADD_FAILURE
11788// and EXPECT_* more.
11789
11790// Generates a nonfatal failure with a generic message.
11791#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
11792
11793// Generates a nonfatal failure at the given source file location with
11794// a generic message.
11795#define ADD_FAILURE_AT(file, line) \
11796 GTEST_MESSAGE_AT_(file, line, "Failed", \
11797 ::testing::TestPartResult::kNonFatalFailure)
11798
11799// Generates a fatal failure with a generic message.
11800#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
11801
Austin Schuh3de38b02024-06-25 18:25:10 -070011802// Like GTEST_FAIL(), but at the given source file location.
11803#define GTEST_FAIL_AT(file, line) \
11804 GTEST_MESSAGE_AT_(file, line, "Failed", \
11805 ::testing::TestPartResult::kFatalFailure)
11806
Austin Schuh70cc9552019-01-21 19:46:48 -080011807// Define this macro to 1 to omit the definition of FAIL(), which is a
11808// generic name and clashes with some other libraries.
11809#if !GTEST_DONT_DEFINE_FAIL
11810# define FAIL() GTEST_FAIL()
11811#endif
11812
11813// Generates a success with a generic message.
11814#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
11815
11816// Define this macro to 1 to omit the definition of SUCCEED(), which
11817// is a generic name and clashes with some other libraries.
11818#if !GTEST_DONT_DEFINE_SUCCEED
11819# define SUCCEED() GTEST_SUCCEED()
11820#endif
11821
11822// Macros for testing exceptions.
11823//
11824// * {ASSERT|EXPECT}_THROW(statement, expected_exception):
11825// Tests that the statement throws the expected exception.
11826// * {ASSERT|EXPECT}_NO_THROW(statement):
11827// Tests that the statement doesn't throw any exception.
11828// * {ASSERT|EXPECT}_ANY_THROW(statement):
11829// Tests that the statement throws an exception.
11830
11831#define EXPECT_THROW(statement, expected_exception) \
11832 GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
11833#define EXPECT_NO_THROW(statement) \
11834 GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
11835#define EXPECT_ANY_THROW(statement) \
11836 GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
11837#define ASSERT_THROW(statement, expected_exception) \
11838 GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
11839#define ASSERT_NO_THROW(statement) \
11840 GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
11841#define ASSERT_ANY_THROW(statement) \
11842 GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
11843
11844// Boolean assertions. Condition can be either a Boolean expression or an
11845// AssertionResult. For more information on how to use AssertionResult with
11846// these macros see comments on that class.
Austin Schuh3de38b02024-06-25 18:25:10 -070011847#define GTEST_EXPECT_TRUE(condition) \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011848 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
Austin Schuh70cc9552019-01-21 19:46:48 -080011849 GTEST_NONFATAL_FAILURE_)
Austin Schuh3de38b02024-06-25 18:25:10 -070011850#define GTEST_EXPECT_FALSE(condition) \
Austin Schuh70cc9552019-01-21 19:46:48 -080011851 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
11852 GTEST_NONFATAL_FAILURE_)
Austin Schuh3de38b02024-06-25 18:25:10 -070011853#define GTEST_ASSERT_TRUE(condition) \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011854 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
Austin Schuh70cc9552019-01-21 19:46:48 -080011855 GTEST_FATAL_FAILURE_)
Austin Schuh3de38b02024-06-25 18:25:10 -070011856#define GTEST_ASSERT_FALSE(condition) \
Austin Schuh70cc9552019-01-21 19:46:48 -080011857 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
11858 GTEST_FATAL_FAILURE_)
11859
Austin Schuh3de38b02024-06-25 18:25:10 -070011860// Define these macros to 1 to omit the definition of the corresponding
11861// EXPECT or ASSERT, which clashes with some users' own code.
11862
11863#if !GTEST_DONT_DEFINE_EXPECT_TRUE
11864#define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
11865#endif
11866
11867#if !GTEST_DONT_DEFINE_EXPECT_FALSE
11868#define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
11869#endif
11870
11871#if !GTEST_DONT_DEFINE_ASSERT_TRUE
11872#define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
11873#endif
11874
11875#if !GTEST_DONT_DEFINE_ASSERT_FALSE
11876#define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
11877#endif
11878
Austin Schuh70cc9552019-01-21 19:46:48 -080011879// Macros for testing equalities and inequalities.
11880//
11881// * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
11882// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
11883// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
11884// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
11885// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
11886// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
11887//
11888// When they are not, Google Test prints both the tested expressions and
11889// their actual values. The values must be compatible built-in types,
11890// or you will get a compiler error. By "compatible" we mean that the
11891// values can be compared by the respective operator.
11892//
11893// Note:
11894//
11895// 1. It is possible to make a user-defined type work with
11896// {ASSERT|EXPECT}_??(), but that requires overloading the
11897// comparison operators and is thus discouraged by the Google C++
11898// Usage Guide. Therefore, you are advised to use the
11899// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
11900// equal.
11901//
11902// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
11903// pointers (in particular, C strings). Therefore, if you use it
11904// with two C strings, you are testing how their locations in memory
11905// are related, not how their content is related. To compare two C
11906// strings by content, use {ASSERT|EXPECT}_STR*().
11907//
11908// 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
11909// {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
11910// what the actual value is when it fails, and similarly for the
11911// other comparisons.
11912//
11913// 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
11914// evaluate their arguments, which is undefined.
11915//
11916// 5. These macros evaluate their arguments exactly once.
11917//
11918// Examples:
11919//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080011920// EXPECT_NE(Foo(), 5);
11921// EXPECT_EQ(a_pointer, NULL);
Austin Schuh70cc9552019-01-21 19:46:48 -080011922// ASSERT_LT(i, array_size);
11923// ASSERT_GT(records.size(), 0) << "There is no record left.";
11924
11925#define EXPECT_EQ(val1, val2) \
Austin Schuh3de38b02024-06-25 18:25:10 -070011926 EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
Austin Schuh70cc9552019-01-21 19:46:48 -080011927#define EXPECT_NE(val1, val2) \
11928 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
11929#define EXPECT_LE(val1, val2) \
11930 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
11931#define EXPECT_LT(val1, val2) \
11932 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
11933#define EXPECT_GE(val1, val2) \
11934 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
11935#define EXPECT_GT(val1, val2) \
11936 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
11937
11938#define GTEST_ASSERT_EQ(val1, val2) \
Austin Schuh3de38b02024-06-25 18:25:10 -070011939 ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
Austin Schuh70cc9552019-01-21 19:46:48 -080011940#define GTEST_ASSERT_NE(val1, val2) \
11941 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
11942#define GTEST_ASSERT_LE(val1, val2) \
11943 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
11944#define GTEST_ASSERT_LT(val1, val2) \
11945 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
11946#define GTEST_ASSERT_GE(val1, val2) \
11947 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
11948#define GTEST_ASSERT_GT(val1, val2) \
11949 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
11950
11951// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
11952// ASSERT_XY(), which clashes with some users' own code.
11953
11954#if !GTEST_DONT_DEFINE_ASSERT_EQ
11955# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
11956#endif
11957
11958#if !GTEST_DONT_DEFINE_ASSERT_NE
11959# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
11960#endif
11961
11962#if !GTEST_DONT_DEFINE_ASSERT_LE
11963# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
11964#endif
11965
11966#if !GTEST_DONT_DEFINE_ASSERT_LT
11967# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
11968#endif
11969
11970#if !GTEST_DONT_DEFINE_ASSERT_GE
11971# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
11972#endif
11973
11974#if !GTEST_DONT_DEFINE_ASSERT_GT
11975# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
11976#endif
11977
11978// C-string Comparisons. All tests treat NULL and any non-NULL string
11979// as different. Two NULLs are equal.
11980//
11981// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
11982// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
11983// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
11984// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
11985//
11986// For wide or narrow string objects, you can use the
11987// {ASSERT|EXPECT}_??() macros.
11988//
11989// Don't depend on the order in which the arguments are evaluated,
11990// which is undefined.
11991//
11992// These macros evaluate their arguments exactly once.
11993
11994#define EXPECT_STREQ(s1, s2) \
11995 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
11996#define EXPECT_STRNE(s1, s2) \
11997 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
11998#define EXPECT_STRCASEEQ(s1, s2) \
11999 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
12000#define EXPECT_STRCASENE(s1, s2)\
12001 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
12002
12003#define ASSERT_STREQ(s1, s2) \
12004 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
12005#define ASSERT_STRNE(s1, s2) \
12006 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
12007#define ASSERT_STRCASEEQ(s1, s2) \
12008 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
12009#define ASSERT_STRCASENE(s1, s2)\
12010 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
12011
12012// Macros for comparing floating-point numbers.
12013//
12014// * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
12015// Tests that two float values are almost equal.
12016// * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
12017// Tests that two double values are almost equal.
12018// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
12019// Tests that v1 and v2 are within the given distance to each other.
12020//
12021// Google Test uses ULP-based comparison to automatically pick a default
12022// error bound that is appropriate for the operands. See the
12023// FloatingPoint template class in gtest-internal.h if you are
12024// interested in the implementation details.
12025
12026#define EXPECT_FLOAT_EQ(val1, val2)\
12027 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
12028 val1, val2)
12029
12030#define EXPECT_DOUBLE_EQ(val1, val2)\
12031 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
12032 val1, val2)
12033
12034#define ASSERT_FLOAT_EQ(val1, val2)\
12035 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
12036 val1, val2)
12037
12038#define ASSERT_DOUBLE_EQ(val1, val2)\
12039 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
12040 val1, val2)
12041
12042#define EXPECT_NEAR(val1, val2, abs_error)\
12043 EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
12044 val1, val2, abs_error)
12045
12046#define ASSERT_NEAR(val1, val2, abs_error)\
12047 ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
12048 val1, val2, abs_error)
12049
12050// These predicate format functions work on floating-point values, and
12051// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
12052//
12053// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
12054
12055// Asserts that val1 is less than, or almost equal to, val2. Fails
12056// otherwise. In particular, it fails if either val1 or val2 is NaN.
12057GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
12058 float val1, float val2);
12059GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
12060 double val1, double val2);
12061
12062
12063#if GTEST_OS_WINDOWS
12064
12065// Macros that test for HRESULT failure and success, these are only useful
12066// on Windows, and rely on Windows SDK macros and APIs to compile.
12067//
12068// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
12069//
12070// When expr unexpectedly fails or succeeds, Google Test prints the
12071// expected result and the actual result with both a human-readable
12072// string representation of the error, if available, as well as the
12073// hex result code.
12074# define EXPECT_HRESULT_SUCCEEDED(expr) \
12075 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
12076
12077# define ASSERT_HRESULT_SUCCEEDED(expr) \
12078 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
12079
12080# define EXPECT_HRESULT_FAILED(expr) \
12081 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
12082
12083# define ASSERT_HRESULT_FAILED(expr) \
12084 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
12085
12086#endif // GTEST_OS_WINDOWS
12087
12088// Macros that execute statement and check that it doesn't generate new fatal
12089// failures in the current thread.
12090//
12091// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
12092//
12093// Examples:
12094//
12095// EXPECT_NO_FATAL_FAILURE(Process());
12096// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
12097//
12098#define ASSERT_NO_FATAL_FAILURE(statement) \
12099 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
12100#define EXPECT_NO_FATAL_FAILURE(statement) \
12101 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
12102
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012103// Causes a trace (including the given source file path and line number,
12104// and the given message) to be included in every test failure message generated
12105// by code in the scope of the lifetime of an instance of this class. The effect
12106// is undone with the destruction of the instance.
12107//
12108// The message argument can be anything streamable to std::ostream.
12109//
12110// Example:
12111// testing::ScopedTrace trace("file.cc", 123, "message");
12112//
12113class GTEST_API_ ScopedTrace {
12114 public:
12115 // The c'tor pushes the given source file location and message onto
12116 // a trace stack maintained by Google Test.
12117
12118 // Template version. Uses Message() to convert the values into strings.
12119 // Slow, but flexible.
12120 template <typename T>
12121 ScopedTrace(const char* file, int line, const T& message) {
12122 PushTrace(file, line, (Message() << message).GetString());
12123 }
12124
12125 // Optimize for some known types.
12126 ScopedTrace(const char* file, int line, const char* message) {
12127 PushTrace(file, line, message ? message : "(null)");
12128 }
12129
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012130 ScopedTrace(const char* file, int line, const std::string& message) {
12131 PushTrace(file, line, message);
12132 }
12133
12134 // The d'tor pops the info pushed by the c'tor.
12135 //
12136 // Note that the d'tor is not virtual in order to be efficient.
12137 // Don't inherit from ScopedTrace!
12138 ~ScopedTrace();
12139
12140 private:
12141 void PushTrace(const char* file, int line, std::string message);
12142
12143 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
12144} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
12145 // c'tor and d'tor. Therefore it doesn't
12146 // need to be used otherwise.
12147
Austin Schuh70cc9552019-01-21 19:46:48 -080012148// Causes a trace (including the source file path, the current line
12149// number, and the given message) to be included in every test failure
12150// message generated by code in the current scope. The effect is
12151// undone when the control leaves the current scope.
12152//
12153// The message argument can be anything streamable to std::ostream.
12154//
12155// In the implementation, we include the current line number as part
12156// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
12157// to appear in the same block - as long as they are on different
12158// lines.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012159//
12160// Assuming that each thread maintains its own stack of traces.
12161// Therefore, a SCOPED_TRACE() would (correctly) only affect the
12162// assertions in its own thread.
Austin Schuh70cc9552019-01-21 19:46:48 -080012163#define SCOPED_TRACE(message) \
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012164 ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
12165 __FILE__, __LINE__, (message))
12166
Austin Schuh70cc9552019-01-21 19:46:48 -080012167// Compile-time assertion for type equality.
Austin Schuh3de38b02024-06-25 18:25:10 -070012168// StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
12169// are the same type. The value it returns is not interesting.
Austin Schuh70cc9552019-01-21 19:46:48 -080012170//
12171// Instead of making StaticAssertTypeEq a class template, we make it a
12172// function template that invokes a helper class template. This
12173// prevents a user from misusing StaticAssertTypeEq<T1, T2> by
12174// defining objects of that type.
12175//
12176// CAVEAT:
12177//
12178// When used inside a method of a class template,
12179// StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
12180// instantiated. For example, given:
12181//
12182// template <typename T> class Foo {
12183// public:
12184// void Bar() { testing::StaticAssertTypeEq<int, T>(); }
12185// };
12186//
12187// the code:
12188//
12189// void Test1() { Foo<bool> foo; }
12190//
12191// will NOT generate a compiler error, as Foo<bool>::Bar() is never
12192// actually instantiated. Instead, you need:
12193//
12194// void Test2() { Foo<bool> foo; foo.Bar(); }
12195//
12196// to cause a compiler error.
12197template <typename T1, typename T2>
Austin Schuh3de38b02024-06-25 18:25:10 -070012198constexpr bool StaticAssertTypeEq() noexcept {
12199 static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type");
Austin Schuh70cc9552019-01-21 19:46:48 -080012200 return true;
12201}
12202
12203// Defines a test.
12204//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012205// The first parameter is the name of the test suite, and the second
12206// parameter is the name of the test within the test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080012207//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012208// The convention is to end the test suite name with "Test". For
12209// example, a test suite for the Foo class can be named FooTest.
Austin Schuh70cc9552019-01-21 19:46:48 -080012210//
12211// Test code should appear between braces after an invocation of
12212// this macro. Example:
12213//
12214// TEST(FooTest, InitializesCorrectly) {
12215// Foo foo;
12216// EXPECT_TRUE(foo.StatusIsOK());
12217// }
12218
12219// Note that we call GetTestTypeId() instead of GetTypeId<
12220// ::testing::Test>() here to get the type ID of testing::Test. This
12221// is to work around a suspected linker bug when using Google Test as
12222// a framework on Mac OS X. The bug causes GetTypeId<
12223// ::testing::Test>() to return different values depending on whether
12224// the call is from the Google Test framework itself or from user test
12225// code. GetTestTypeId() is guaranteed to always return the same
12226// value, as it always calls GetTypeId<>() from the Google Test
12227// framework.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012228#define GTEST_TEST(test_suite_name, test_name) \
12229 GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \
12230 ::testing::internal::GetTestTypeId())
Austin Schuh70cc9552019-01-21 19:46:48 -080012231
12232// Define this macro to 1 to omit the definition of TEST(), which
12233// is a generic name and clashes with some other libraries.
12234#if !GTEST_DONT_DEFINE_TEST
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012235#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
Austin Schuh70cc9552019-01-21 19:46:48 -080012236#endif
12237
12238// Defines a test that uses a test fixture.
12239//
12240// The first parameter is the name of the test fixture class, which
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012241// also doubles as the test suite name. The second parameter is the
12242// name of the test within the test suite.
Austin Schuh70cc9552019-01-21 19:46:48 -080012243//
12244// A test fixture class must be declared earlier. The user should put
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012245// the test code between braces after using this macro. Example:
Austin Schuh70cc9552019-01-21 19:46:48 -080012246//
12247// class FooTest : public testing::Test {
12248// protected:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012249// void SetUp() override { b_.AddElement(3); }
Austin Schuh70cc9552019-01-21 19:46:48 -080012250//
12251// Foo a_;
12252// Foo b_;
12253// };
12254//
12255// TEST_F(FooTest, InitializesCorrectly) {
12256// EXPECT_TRUE(a_.StatusIsOK());
12257// }
12258//
12259// TEST_F(FooTest, ReturnsElementCountCorrectly) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012260// EXPECT_EQ(a_.size(), 0);
12261// EXPECT_EQ(b_.size(), 1);
Austin Schuh70cc9552019-01-21 19:46:48 -080012262// }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012263//
12264// GOOGLETEST_CM0011 DO NOT DELETE
Austin Schuh3de38b02024-06-25 18:25:10 -070012265#if !GTEST_DONT_DEFINE_TEST
Austin Schuh70cc9552019-01-21 19:46:48 -080012266#define TEST_F(test_fixture, test_name)\
12267 GTEST_TEST_(test_fixture, test_name, test_fixture, \
12268 ::testing::internal::GetTypeId<test_fixture>())
Austin Schuh3de38b02024-06-25 18:25:10 -070012269#endif // !GTEST_DONT_DEFINE_TEST
Austin Schuh70cc9552019-01-21 19:46:48 -080012270
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012271// Returns a path to temporary directory.
12272// Tries to determine an appropriate directory for the platform.
12273GTEST_API_ std::string TempDir();
12274
12275#ifdef _MSC_VER
12276# pragma warning(pop)
12277#endif
12278
12279// Dynamically registers a test with the framework.
12280//
12281// This is an advanced API only to be used when the `TEST` macros are
12282// insufficient. The macros should be preferred when possible, as they avoid
12283// most of the complexity of calling this function.
12284//
12285// The `factory` argument is a factory callable (move-constructible) object or
12286// function pointer that creates a new instance of the Test object. It
12287// handles ownership to the caller. The signature of the callable is
12288// `Fixture*()`, where `Fixture` is the test fixture class for the test. All
12289// tests registered with the same `test_suite_name` must return the same
12290// fixture type. This is checked at runtime.
12291//
12292// The framework will infer the fixture class from the factory and will call
12293// the `SetUpTestSuite` and `TearDownTestSuite` for it.
12294//
12295// Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
12296// undefined.
12297//
12298// Use case example:
12299//
12300// class MyFixture : public ::testing::Test {
12301// public:
12302// // All of these optional, just like in regular macro usage.
12303// static void SetUpTestSuite() { ... }
12304// static void TearDownTestSuite() { ... }
12305// void SetUp() override { ... }
12306// void TearDown() override { ... }
12307// };
12308//
12309// class MyTest : public MyFixture {
12310// public:
12311// explicit MyTest(int data) : data_(data) {}
12312// void TestBody() override { ... }
12313//
12314// private:
12315// int data_;
12316// };
12317//
12318// void RegisterMyTests(const std::vector<int>& values) {
12319// for (int v : values) {
12320// ::testing::RegisterTest(
12321// "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
12322// std::to_string(v).c_str(),
12323// __FILE__, __LINE__,
12324// // Important to use the fixture type as the return type here.
12325// [=]() -> MyFixture* { return new MyTest(v); });
12326// }
12327// }
12328// ...
12329// int main(int argc, char** argv) {
12330// std::vector<int> values_to_test = LoadValuesFromConfig();
12331// RegisterMyTests(values_to_test);
12332// ...
12333// return RUN_ALL_TESTS();
12334// }
12335//
12336template <int&... ExplicitParameterBarrier, typename Factory>
12337TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
12338 const char* type_param, const char* value_param,
12339 const char* file, int line, Factory factory) {
12340 using TestT = typename std::remove_pointer<decltype(factory())>::type;
12341
12342 class FactoryImpl : public internal::TestFactoryBase {
12343 public:
12344 explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}
12345 Test* CreateTest() override { return factory_(); }
12346
12347 private:
12348 Factory factory_;
12349 };
12350
12351 return internal::MakeAndRegisterTestInfo(
12352 test_suite_name, test_name, type_param, value_param,
12353 internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),
Austin Schuh3de38b02024-06-25 18:25:10 -070012354 internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),
12355 internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012356 new FactoryImpl{std::move(factory)});
12357}
12358
Austin Schuh70cc9552019-01-21 19:46:48 -080012359} // namespace testing
12360
12361// Use this function in main() to run all tests. It returns 0 if all
12362// tests are successful, or 1 otherwise.
12363//
12364// RUN_ALL_TESTS() should be invoked after the command line has been
12365// parsed by InitGoogleTest().
12366//
12367// This function was formerly a macro; thus, it is in the global
12368// namespace and has an all-caps name.
12369int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
12370
12371inline int RUN_ALL_TESTS() {
12372 return ::testing::UnitTest::GetInstance()->Run();
12373}
12374
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080012375GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
12376
Austin Schuh3de38b02024-06-25 18:25:10 -070012377#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_