1 // 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.
29
30 //
31 // The Google C++ Testing and Mocking Framework (Google Test)
32 //
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
50 // GOOGLETEST_CM0001 DO NOT DELETE
51
52 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_
53 #define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
54
55 #include <cstddef>
56 #include <limits>
57 #include <memory>
58 #include <ostream>
59 #include <type_traits>
60 #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 //
91 // The Google C++ Testing and Mocking Framework (Google Test)
92 //
93 // This header file declares functions and macros used internally by
94 // Google Test. They are subject to change without notice.
95
96 // GOOGLETEST_CM0001 DO NOT DELETE
97
98 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
99 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
100
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 //
130 // 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
141 // GOOGLETEST_CM0001 DO NOT DELETE
142
143 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
144 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
145
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.
175 // 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).
184 // 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().
191 // 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.
198 // 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.
204
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
216 // GTEST_OS_DRAGONFLY - DragonFlyBSD
217 // GTEST_OS_FREEBSD - FreeBSD
218 // GTEST_OS_FUCHSIA - Fuchsia
219 // GTEST_OS_GNU_HURD - GNU/Hurd
220 // GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD
221 // GTEST_OS_HAIKU - Haiku
222 // GTEST_OS_HPUX - HP-UX
223 // GTEST_OS_LINUX - Linux
224 // GTEST_OS_LINUX_ANDROID - Google Android
225 // GTEST_OS_MAC - Mac OS X
226 // GTEST_OS_IOS - iOS
227 // GTEST_OS_NACL - Google Native Client (NaCl)
228 // GTEST_OS_NETBSD - NetBSD
229 // GTEST_OS_OPENBSD - OpenBSD
230 // GTEST_OS_OS2 - OS/2
231 // GTEST_OS_QNX - QNX
232 // GTEST_OS_SOLARIS - Sun Solaris
233 // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile)
234 // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop
235 // GTEST_OS_WINDOWS_MINGW - MinGW
236 // GTEST_OS_WINDOWS_MOBILE - Windows Mobile
237 // GTEST_OS_WINDOWS_PHONE - Windows Phone
238 // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT
239 // GTEST_OS_ZOS - z/OS
240 //
241 // Among the platforms, Cygwin, Linux, Mac OS X, and Windows have the
242 // most stable support. Since core members of the Google Test project
243 // don't have access to other platforms, support for them may be less
244 // stable. If you notice any problems on your platform, please notify
245 // googletestframework@googlegroups.com (patches for fixing them are
246 // even more welcome!).
247 //
248 // It is possible that none of the GTEST_OS_* macros are defined.
249
250 // Feature-indicating macros
251 // -------------------------
252 //
253 // Macros indicating which Google Test features are available (a macro
254 // is defined to 1 if the corresponding feature is supported;
255 // otherwise UNDEFINED -- it's never defined to 0.). Google Test
256 // defines these macros automatically. Code outside Google Test MUST
257 // NOT define them.
258 //
259 // These macros are public so that portable tests can be written.
260 // Such tests typically surround code using a feature with an #if
261 // which controls that code. For example:
262 //
263 // #if GTEST_HAS_DEATH_TEST
264 // EXPECT_DEATH(DoSomethingDeadly());
265 // #endif
266 //
267 // GTEST_HAS_DEATH_TEST - death tests
268 // GTEST_HAS_TYPED_TEST - typed tests
269 // GTEST_HAS_TYPED_TEST_P - type-parameterized tests
270 // GTEST_IS_THREADSAFE - Google Test is thread-safe.
271 // GOOGLETEST_CM0007 DO NOT DELETE
272 // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with
273 // GTEST_HAS_POSIX_RE (see above) which users can
274 // define themselves.
275 // GTEST_USES_SIMPLE_RE - our own simple regex is used;
276 // the above RE\b(s) are mutually exclusive.
277
278 // Misc public macros
279 // ------------------
280 //
281 // GTEST_FLAG(flag_name) - references the variable corresponding to
282 // the given Google Test flag.
283
284 // Internal utilities
285 // ------------------
286 //
287 // The following macros and utilities are for Google Test's INTERNAL
288 // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY.
289 //
290 // Macros for basic C++ coding:
291 // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
292 // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a
293 // variable don't have to be used.
294 // GTEST_DISALLOW_ASSIGN_ - disables copy operator=.
295 // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
296 // GTEST_DISALLOW_MOVE_ASSIGN_ - disables move operator=.
297 // GTEST_DISALLOW_MOVE_AND_ASSIGN_ - disables move ctor and operator=.
298 // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used.
299 // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
300 // suppressed (constant conditional).
301 // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
302 // is suppressed.
303 // GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
304 // UniversalPrinter<absl::any> specializations.
305 // GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
306 // or
307 // UniversalPrinter<absl::optional>
308 // specializations.
309 // GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
310 // Matcher<absl::string_view>
311 // specializations.
312 // GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
313 // UniversalPrinter<absl::variant>
314 // specializations.
315 //
316 // Synchronization:
317 // Mutex, MutexLock, ThreadLocal, GetThreadCount()
318 // - synchronization primitives.
319 //
320 // Regular expressions:
321 // RE - a simple regular expression class using the POSIX
322 // Extended Regular Expression syntax on UNIX-like platforms
323 // GOOGLETEST_CM0008 DO NOT DELETE
324 // or a reduced regular exception syntax on other
325 // platforms, including Windows.
326 // Logging:
327 // GTEST_LOG_() - logs messages at the specified severity level.
328 // LogToStderr() - directs all log messages to stderr.
329 // FlushInfoLog() - flushes informational log messages.
330 //
331 // Stdout and stderr capturing:
332 // CaptureStdout() - starts capturing stdout.
333 // GetCapturedStdout() - stops capturing stdout and returns the captured
334 // string.
335 // CaptureStderr() - starts capturing stderr.
336 // GetCapturedStderr() - stops capturing stderr and returns the captured
337 // string.
338 //
339 // Integer types:
340 // TypeWithSize - maps an integer to a int type.
341 // TimeInMillis - integers of known sizes.
342 // BiggestInt - the biggest signed integer type.
343 //
344 // Command-line utilities:
345 // GTEST_DECLARE_*() - declares a flag.
346 // GTEST_DEFINE_*() - defines a flag.
347 // GetInjectableArgvs() - returns the command line as a vector of strings.
348 //
349 // Environment variable utilities:
350 // GetEnv() - gets the value of an environment variable.
351 // BoolFromGTestEnv() - parses a bool environment variable.
352 // Int32FromGTestEnv() - parses an int32_t environment variable.
353 // StringFromGTestEnv() - parses a string environment variable.
354 //
355 // Deprecation warnings:
356 // GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as
357 // deprecated; calling a marked function
358 // should generate a compiler warning
359
360 #include <ctype.h> // for isspace, etc
361 #include <stddef.h> // for ptrdiff_t
362 #include <stdio.h>
363 #include <stdlib.h>
364 #include <string.h>
365
366 #include <cerrno>
367 #include <cstdint>
368 #include <limits>
369 #include <type_traits>
370
371 #ifndef _WIN32_WCE
372 # include <sys/types.h>
373 # include <sys/stat.h>
374 #endif // !_WIN32_WCE
375
376 #if defined __APPLE__
377 # include <AvailabilityMacros.h>
378 # include <TargetConditionals.h>
379 #endif
380
381 #include <iostream> // NOLINT
382 #include <locale>
383 #include <memory>
384 #include <string> // NOLINT
385 #include <tuple>
386 #include <vector> // NOLINT
387
388 // Copyright 2015, Google Inc.
389 // All rights reserved.
390 //
391 // Redistribution and use in source and binary forms, with or without
392 // modification, are permitted provided that the following conditions are
393 // met:
394 //
395 // * Redistributions of source code must retain the above copyright
396 // notice, this list of conditions and the following disclaimer.
397 // * Redistributions in binary form must reproduce the above
398 // copyright notice, this list of conditions and the following disclaimer
399 // in the documentation and/or other materials provided with the
400 // distribution.
401 // * Neither the name of Google Inc. nor the names of its
402 // contributors may be used to endorse or promote products derived from
403 // this software without specific prior written permission.
404 //
405 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
406 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
407 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
408 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
409 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
410 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
411 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
412 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
413 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
414 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
415 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
416 //
417 // Injection point for custom user configurations. See README for details
418 //
419 // ** Custom implementation starts here **
420
421 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
422 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
423
424 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
425 // Copyright 2015, Google Inc.
426 // All rights reserved.
427 //
428 // Redistribution and use in source and binary forms, with or without
429 // modification, are permitted provided that the following conditions are
430 // met:
431 //
432 // * Redistributions of source code must retain the above copyright
433 // notice, this list of conditions and the following disclaimer.
434 // * Redistributions in binary form must reproduce the above
435 // copyright notice, this list of conditions and the following disclaimer
436 // in the documentation and/or other materials provided with the
437 // distribution.
438 // * Neither the name of Google Inc. nor the names of its
439 // contributors may be used to endorse or promote products derived from
440 // this software without specific prior written permission.
441 //
442 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
443 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
444 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
445 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
446 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
447 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
448 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
449 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
450 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
451 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
452 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
453 //
454 // The Google C++ Testing and Mocking Framework (Google Test)
455 //
456 // This header file defines the GTEST_OS_* macro.
457 // It is separate from gtest-port.h so that custom/gtest-port.h can include it.
458
459 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
460 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
461
462 // Determines the platform on which Google Test is compiled.
463 #ifdef __CYGWIN__
464 # define GTEST_OS_CYGWIN 1
465 # elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
466 # define GTEST_OS_WINDOWS_MINGW 1
467 # define GTEST_OS_WINDOWS 1
468 #elif defined _WIN32
469 # define GTEST_OS_WINDOWS 1
470 # ifdef _WIN32_WCE
471 # define GTEST_OS_WINDOWS_MOBILE 1
472 # elif defined(WINAPI_FAMILY)
473 # include <winapifamily.h>
474 # if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
475 # define GTEST_OS_WINDOWS_DESKTOP 1
476 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
477 # define GTEST_OS_WINDOWS_PHONE 1
478 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
479 # define GTEST_OS_WINDOWS_RT 1
480 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
481 # define GTEST_OS_WINDOWS_PHONE 1
482 # define GTEST_OS_WINDOWS_TV_TITLE 1
483 # else
484 // WINAPI_FAMILY defined but no known partition matched.
485 // Default to desktop.
486 # define GTEST_OS_WINDOWS_DESKTOP 1
487 # endif
488 # else
489 # define GTEST_OS_WINDOWS_DESKTOP 1
490 # endif // _WIN32_WCE
491 #elif defined __OS2__
492 # define GTEST_OS_OS2 1
493 #elif defined __APPLE__
494 # define GTEST_OS_MAC 1
495 # include <TargetConditionals.h>
496 # if TARGET_OS_IPHONE
497 # define GTEST_OS_IOS 1
498 # endif
499 #elif defined __DragonFly__
500 # define GTEST_OS_DRAGONFLY 1
501 #elif defined __FreeBSD__
502 # define GTEST_OS_FREEBSD 1
503 #elif defined __Fuchsia__
504 # define GTEST_OS_FUCHSIA 1
505 #elif defined(__GNU__)
506 # define GTEST_OS_GNU_HURD 1
507 #elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
508 # define GTEST_OS_GNU_KFREEBSD 1
509 #elif defined __linux__
510 # define GTEST_OS_LINUX 1
511 # if defined __ANDROID__
512 # define GTEST_OS_LINUX_ANDROID 1
513 # endif
514 #elif defined __MVS__
515 # define GTEST_OS_ZOS 1
516 #elif defined(__sun) && defined(__SVR4)
517 # define GTEST_OS_SOLARIS 1
518 #elif defined(_AIX)
519 # define GTEST_OS_AIX 1
520 #elif defined(__hpux)
521 # define GTEST_OS_HPUX 1
522 #elif defined __native_client__
523 # define GTEST_OS_NACL 1
524 #elif defined __NetBSD__
525 # define GTEST_OS_NETBSD 1
526 #elif defined __OpenBSD__
527 # define GTEST_OS_OPENBSD 1
528 #elif defined __QNX__
529 # define GTEST_OS_QNX 1
530 #elif defined(__HAIKU__)
531 #define GTEST_OS_HAIKU 1
532 #elif defined ESP8266
533 #define GTEST_OS_ESP8266 1
534 #elif defined ESP32
535 #define GTEST_OS_ESP32 1
536 #elif defined(__XTENSA__)
537 #define GTEST_OS_XTENSA 1
538 #endif // __CYGWIN__
539
540 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
541
542 #if !defined(GTEST_DEV_EMAIL_)
543 # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
544 # define GTEST_FLAG_PREFIX_ "gtest_"
545 # define GTEST_FLAG_PREFIX_DASH_ "gtest-"
546 # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
547 # define GTEST_NAME_ "Google Test"
548 # define GTEST_PROJECT_URL_ "https://github.com/google/googletest/"
549 #endif // !defined(GTEST_DEV_EMAIL_)
550
551 #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
552 # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
553 #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
554
555 // Determines the version of gcc that is used to compile this.
556 #ifdef __GNUC__
557 // 40302 means version 4.3.2.
558 # define GTEST_GCC_VER_ \
559 (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
560 #endif // __GNUC__
561
562 // Macros for disabling Microsoft Visual C++ warnings.
563 //
564 // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
565 // /* code that triggers warnings C4800 and C4385 */
566 // GTEST_DISABLE_MSC_WARNINGS_POP_()
567 #if defined(_MSC_VER)
568 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
569 __pragma(warning(push)) \
570 __pragma(warning(disable: warnings))
571 # define GTEST_DISABLE_MSC_WARNINGS_POP_() \
572 __pragma(warning(pop))
573 #else
574 // Not all compilers are MSVC
575 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
576 # define GTEST_DISABLE_MSC_WARNINGS_POP_()
577 #endif
578
579 // Clang on Windows does not understand MSVC's pragma warning.
580 // We need clang-specific way to disable function deprecation warning.
581 #ifdef __clang__
582 # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
583 _Pragma("clang diagnostic push") \
584 _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \
585 _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"")
586 #define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
587 _Pragma("clang diagnostic pop")
588 #else
589 # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
590 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
591 # define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
592 GTEST_DISABLE_MSC_WARNINGS_POP_()
593 #endif
594
595 // Brings in definitions for functions used in the testing::internal::posix
596 // namespace (read, write, close, chdir, isatty, stat). We do not currently
597 // use them on Windows Mobile.
598 #if GTEST_OS_WINDOWS
599 # if !GTEST_OS_WINDOWS_MOBILE
600 # include <direct.h>
601 # include <io.h>
602 # endif
603 // In order to avoid having to include <windows.h>, use forward declaration
604 #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
605 // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two
606 // separate (equivalent) structs, instead of using typedef
607 typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
608 #else
609 // Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.
610 // This assumption is verified by
611 // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
612 typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
613 #endif
614 #elif GTEST_OS_XTENSA
615 #include <unistd.h>
616 // Xtensa toolchains define strcasecmp in the string.h header instead of
617 // strings.h. string.h is already included.
618 #else
619 // This assumes that non-Windows OSes provide unistd.h. For OSes where this
620 // is not the case, we need to include headers that provide the functions
621 // mentioned above.
622 # include <unistd.h>
623 # include <strings.h>
624 #endif // GTEST_OS_WINDOWS
625
626 #if GTEST_OS_LINUX_ANDROID
627 // Used to define __ANDROID_API__ matching the target NDK API level.
628 # include <android/api-level.h> // NOLINT
629 #endif
630
631 // Defines this to true if and only if Google Test can use POSIX regular
632 // expressions.
633 #ifndef GTEST_HAS_POSIX_RE
634 # if GTEST_OS_LINUX_ANDROID
635 // On Android, <regex.h> is only available starting with Gingerbread.
636 # define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
637 # else
638 #define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA)
639 # endif
640 #endif
641
642 #if GTEST_USES_PCRE
643 // The appropriate headers have already been included.
644
645 #elif GTEST_HAS_POSIX_RE
646
647 // On some platforms, <regex.h> needs someone to define size_t, and
648 // won't compile otherwise. We can #include it here as we already
649 // included <stdlib.h>, which is guaranteed to define size_t through
650 // <stddef.h>.
651 # include <regex.h> // NOLINT
652
653 # define GTEST_USES_POSIX_RE 1
654
655 #elif GTEST_OS_WINDOWS
656
657 // <regex.h> is not available on Windows. Use our own simple regex
658 // implementation instead.
659 # define GTEST_USES_SIMPLE_RE 1
660
661 #else
662
663 // <regex.h> may not be available on this platform. Use our own
664 // simple regex implementation instead.
665 # define GTEST_USES_SIMPLE_RE 1
666
667 #endif // GTEST_USES_PCRE
668
669 #ifndef GTEST_HAS_EXCEPTIONS
670 // The user didn't tell us whether exceptions are enabled, so we need
671 // to figure it out.
672 # if defined(_MSC_VER) && defined(_CPPUNWIND)
673 // MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled.
674 # define GTEST_HAS_EXCEPTIONS 1
675 # elif defined(__BORLANDC__)
676 // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS
677 // macro to enable exceptions, so we'll do the same.
678 // Assumes that exceptions are enabled by default.
679 # ifndef _HAS_EXCEPTIONS
680 # define _HAS_EXCEPTIONS 1
681 # endif // _HAS_EXCEPTIONS
682 # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
683 # elif defined(__clang__)
684 // clang defines __EXCEPTIONS if and only if exceptions are enabled before clang
685 // 220714, but if and only if cleanups are enabled after that. In Obj-C++ files,
686 // there can be cleanups for ObjC exceptions which also need cleanups, even if
687 // C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which
688 // checks for C++ exceptions starting at clang r206352, but which checked for
689 // cleanups prior to that. To reliably check for C++ exception availability with
690 // clang, check for
691 // __EXCEPTIONS && __has_feature(cxx_exceptions).
692 # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
693 # elif defined(__GNUC__) && __EXCEPTIONS
694 // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
695 # define GTEST_HAS_EXCEPTIONS 1
696 # elif defined(__SUNPRO_CC)
697 // Sun Pro CC supports exceptions. However, there is no compile-time way of
698 // detecting whether they are enabled or not. Therefore, we assume that
699 // they are enabled unless the user tells us otherwise.
700 # define GTEST_HAS_EXCEPTIONS 1
701 # elif defined(__IBMCPP__) && __EXCEPTIONS
702 // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
703 # define GTEST_HAS_EXCEPTIONS 1
704 # elif defined(__HP_aCC)
705 // Exception handling is in effect by default in HP aCC compiler. It has to
706 // be turned of by +noeh compiler option if desired.
707 # define GTEST_HAS_EXCEPTIONS 1
708 # else
709 // For other compilers, we assume exceptions are disabled to be
710 // conservative.
711 # define GTEST_HAS_EXCEPTIONS 0
712 # endif // defined(_MSC_VER) || defined(__BORLANDC__)
713 #endif // GTEST_HAS_EXCEPTIONS
714
715 #ifndef GTEST_HAS_STD_WSTRING
716 // The user didn't tell us whether ::std::wstring is available, so we need
717 // to figure it out.
718 // Cygwin 1.7 and below doesn't support ::std::wstring.
719 // Solaris' libc++ doesn't support it either. Android has
720 // no support for it at least as recent as Froyo (2.2).
721 #define GTEST_HAS_STD_WSTRING \
722 (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
723 GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || GTEST_OS_XTENSA))
724
725 #endif // GTEST_HAS_STD_WSTRING
726
727 // Determines whether RTTI is available.
728 #ifndef GTEST_HAS_RTTI
729 // The user didn't tell us whether RTTI is enabled, so we need to
730 // figure it out.
731
732 # ifdef _MSC_VER
733
734 #ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled.
735 # define GTEST_HAS_RTTI 1
736 # else
737 # define GTEST_HAS_RTTI 0
738 # endif
739
740 // Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is
741 // enabled.
742 # elif defined(__GNUC__)
743
744 # ifdef __GXX_RTTI
745 // When building against STLport with the Android NDK and with
746 // -frtti -fno-exceptions, the build fails at link time with undefined
747 // references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
748 // so disable RTTI when detected.
749 # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
750 !defined(__EXCEPTIONS)
751 # define GTEST_HAS_RTTI 0
752 # else
753 # define GTEST_HAS_RTTI 1
754 # endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
755 # else
756 # define GTEST_HAS_RTTI 0
757 # endif // __GXX_RTTI
758
759 // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
760 // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
761 // first version with C++ support.
762 # elif defined(__clang__)
763
764 # define GTEST_HAS_RTTI __has_feature(cxx_rtti)
765
766 // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
767 // both the typeid and dynamic_cast features are present.
768 # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
769
770 # ifdef __RTTI_ALL__
771 # define GTEST_HAS_RTTI 1
772 # else
773 # define GTEST_HAS_RTTI 0
774 # endif
775
776 # else
777
778 // For all other compilers, we assume RTTI is enabled.
779 # define GTEST_HAS_RTTI 1
780
781 # endif // _MSC_VER
782
783 #endif // GTEST_HAS_RTTI
784
785 // It's this header's responsibility to #include <typeinfo> when RTTI
786 // is enabled.
787 #if GTEST_HAS_RTTI
788 # include <typeinfo>
789 #endif
790
791 // Determines whether Google Test can use the pthreads library.
792 #ifndef GTEST_HAS_PTHREAD
793 // The user didn't tell us explicitly, so we make reasonable assumptions about
794 // which platforms have pthreads support.
795 //
796 // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
797 // to your compiler flags.
798 #define GTEST_HAS_PTHREAD \
799 (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \
800 GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
801 GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \
802 GTEST_OS_HAIKU || GTEST_OS_GNU_HURD)
803 #endif // GTEST_HAS_PTHREAD
804
805 #if GTEST_HAS_PTHREAD
806 // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
807 // true.
808 # include <pthread.h> // NOLINT
809
810 // For timespec and nanosleep, used below.
811 # include <time.h> // NOLINT
812 #endif
813
814 // Determines whether clone(2) is supported.
815 // Usually it will only be available on Linux, excluding
816 // Linux on the Itanium architecture.
817 // Also see http://linux.die.net/man/2/clone.
818 #ifndef GTEST_HAS_CLONE
819 // The user didn't tell us, so we need to figure it out.
820
821 # if GTEST_OS_LINUX && !defined(__ia64__)
822 # if GTEST_OS_LINUX_ANDROID
823 // On Android, clone() became available at different API levels for each 32-bit
824 // architecture.
825 # if defined(__LP64__) || \
826 (defined(__arm__) && __ANDROID_API__ >= 9) || \
827 (defined(__mips__) && __ANDROID_API__ >= 12) || \
828 (defined(__i386__) && __ANDROID_API__ >= 17)
829 # define GTEST_HAS_CLONE 1
830 # else
831 # define GTEST_HAS_CLONE 0
832 # endif
833 # else
834 # define GTEST_HAS_CLONE 1
835 # endif
836 # else
837 # define GTEST_HAS_CLONE 0
838 # endif // GTEST_OS_LINUX && !defined(__ia64__)
839
840 #endif // GTEST_HAS_CLONE
841
842 // Determines whether to support stream redirection. This is used to test
843 // output correctness and to implement death tests.
844 #ifndef GTEST_HAS_STREAM_REDIRECTION
845 // By default, we assume that stream redirection is supported on all
846 // platforms except known mobile ones.
847 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
848 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
849 # define GTEST_HAS_STREAM_REDIRECTION 0
850 # else
851 # define GTEST_HAS_STREAM_REDIRECTION 1
852 # endif // !GTEST_OS_WINDOWS_MOBILE
853 #endif // GTEST_HAS_STREAM_REDIRECTION
854
855 // Determines whether to support death tests.
856 // pops up a dialog window that cannot be suppressed programmatically.
857 #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
858 (GTEST_OS_MAC && !GTEST_OS_IOS) || \
859 (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \
860 GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \
861 GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
862 GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU || \
863 GTEST_OS_GNU_HURD)
864 # define GTEST_HAS_DEATH_TEST 1
865 #endif
866
867 // Determines whether to support type-driven tests.
868
869 // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
870 // Sun Pro CC, IBM Visual Age, and HP aCC support.
871 #if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \
872 defined(__IBMCPP__) || defined(__HP_aCC)
873 # define GTEST_HAS_TYPED_TEST 1
874 # define GTEST_HAS_TYPED_TEST_P 1
875 #endif
876
877 // Determines whether the system compiler uses UTF-16 for encoding wide strings.
878 #define GTEST_WIDE_STRING_USES_UTF16_ \
879 (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2)
880
881 // Determines whether test results can be streamed to a socket.
882 #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \
883 GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD || \
884 GTEST_OS_GNU_HURD
885 # define GTEST_CAN_STREAM_RESULTS_ 1
886 #endif
887
888 // Defines some utility macros.
889
890 // The GNU compiler emits a warning if nested "if" statements are followed by
891 // an "else" statement and braces are not used to explicitly disambiguate the
892 // "else" binding. This leads to problems with code like:
893 //
894 // if (gate)
895 // ASSERT_*(condition) << "Some message";
896 //
897 // The "switch (0) case 0:" idiom is used to suppress this.
898 #ifdef __INTEL_COMPILER
899 # define GTEST_AMBIGUOUS_ELSE_BLOCKER_
900 #else
901 # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT
902 #endif
903
904 // Use this annotation at the end of a struct/class definition to
905 // prevent the compiler from optimizing away instances that are never
906 // used. This is useful when all interesting logic happens inside the
907 // c'tor and / or d'tor. Example:
908 //
909 // struct Foo {
910 // Foo() { ... }
911 // } GTEST_ATTRIBUTE_UNUSED_;
912 //
913 // Also use it after a variable or parameter declaration to tell the
914 // compiler the variable/parameter does not have to be used.
915 #if defined(__GNUC__) && !defined(COMPILER_ICC)
916 # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
917 #elif defined(__clang__)
918 # if __has_attribute(unused)
919 # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
920 # endif
921 #endif
922 #ifndef GTEST_ATTRIBUTE_UNUSED_
923 # define GTEST_ATTRIBUTE_UNUSED_
924 #endif
925
926 // Use this annotation before a function that takes a printf format string.
927 #if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC)
928 # if defined(__MINGW_PRINTF_FORMAT)
929 // MinGW has two different printf implementations. Ensure the format macro
930 // matches the selected implementation. See
931 // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.
932 # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
933 __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \
934 first_to_check)))
935 # else
936 # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
937 __attribute__((__format__(__printf__, string_index, first_to_check)))
938 # endif
939 #else
940 # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
941 #endif
942
943
944 // A macro to disallow copy operator=
945 // This should be used in the private: declarations for a class.
946 #define GTEST_DISALLOW_ASSIGN_(type) \
947 type& operator=(type const &) = delete
948
949 // A macro to disallow copy constructor and operator=
950 // This should be used in the private: declarations for a class.
951 #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \
952 type(type const&) = delete; \
953 type& operator=(type const&) = delete
954
955 // A macro to disallow move operator=
956 // This should be used in the private: declarations for a class.
957 #define GTEST_DISALLOW_MOVE_ASSIGN_(type) \
958 type& operator=(type &&) noexcept = delete
959
960 // A macro to disallow move constructor and operator=
961 // This should be used in the private: declarations for a class.
962 #define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \
963 type(type&&) noexcept = delete; \
964 type& operator=(type&&) noexcept = delete
965
966 // Tell the compiler to warn about unused return values for functions declared
967 // with this macro. The macro should be used on function declarations
968 // following the argument list:
969 //
970 // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
971 #if defined(__GNUC__) && !defined(COMPILER_ICC)
972 # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
973 #else
974 # define GTEST_MUST_USE_RESULT_
975 #endif // __GNUC__ && !COMPILER_ICC
976
977 // MS C++ compiler emits warning when a conditional expression is compile time
978 // constant. In some contexts this warning is false positive and needs to be
979 // suppressed. Use the following two macros in such cases:
980 //
981 // GTEST_INTENTIONAL_CONST_COND_PUSH_()
982 // while (true) {
983 // GTEST_INTENTIONAL_CONST_COND_POP_()
984 // }
985 # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
986 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
987 # define GTEST_INTENTIONAL_CONST_COND_POP_() \
988 GTEST_DISABLE_MSC_WARNINGS_POP_()
989
990 // Determine whether the compiler supports Microsoft's Structured Exception
991 // Handling. This is supported by several Windows compilers but generally
992 // does not exist on any other system.
993 #ifndef GTEST_HAS_SEH
994 // The user didn't tell us, so we need to figure it out.
995
996 # if defined(_MSC_VER) || defined(__BORLANDC__)
997 // These two compilers are known to support SEH.
998 # define GTEST_HAS_SEH 1
999 # else
1000 // Assume no SEH.
1001 # define GTEST_HAS_SEH 0
1002 # endif
1003
1004 #endif // GTEST_HAS_SEH
1005
1006 #ifndef GTEST_IS_THREADSAFE
1007
1008 #define GTEST_IS_THREADSAFE \
1009 (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \
1010 (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \
1011 GTEST_HAS_PTHREAD)
1012
1013 #endif // GTEST_IS_THREADSAFE
1014
1015 // GTEST_API_ qualifies all symbols that must be exported. The definitions below
1016 // are guarded by #ifndef to give embedders a chance to define GTEST_API_ in
1017 // gtest/internal/custom/gtest-port.h
1018 #ifndef GTEST_API_
1019
1020 #ifdef _MSC_VER
1021 # if GTEST_LINKED_AS_SHARED_LIBRARY
1022 # define GTEST_API_ __declspec(dllimport)
1023 # elif GTEST_CREATE_SHARED_LIBRARY
1024 # define GTEST_API_ __declspec(dllexport)
1025 # endif
1026 #elif __GNUC__ >= 4 || defined(__clang__)
1027 # define GTEST_API_ __attribute__((visibility ("default")))
1028 #endif // _MSC_VER
1029
1030 #endif // GTEST_API_
1031
1032 #ifndef GTEST_API_
1033 # define GTEST_API_
1034 #endif // GTEST_API_
1035
1036 #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE
1037 # define GTEST_DEFAULT_DEATH_TEST_STYLE "fast"
1038 #endif // GTEST_DEFAULT_DEATH_TEST_STYLE
1039
1040 #ifdef __GNUC__
1041 // Ask the compiler to never inline a given function.
1042 # define GTEST_NO_INLINE_ __attribute__((noinline))
1043 #else
1044 # define GTEST_NO_INLINE_
1045 #endif
1046
1047 // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
1048 #if !defined(GTEST_HAS_CXXABI_H_)
1049 # if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
1050 # define GTEST_HAS_CXXABI_H_ 1
1051 # else
1052 # define GTEST_HAS_CXXABI_H_ 0
1053 # endif
1054 #endif
1055
1056 // A function level attribute to disable checking for use of uninitialized
1057 // memory when built with MemorySanitizer.
1058 #if defined(__clang__)
1059 # if __has_feature(memory_sanitizer)
1060 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
1061 __attribute__((no_sanitize_memory))
1062 # else
1063 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
1064 # endif // __has_feature(memory_sanitizer)
1065 #else
1066 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
1067 #endif // __clang__
1068
1069 // A function level attribute to disable AddressSanitizer instrumentation.
1070 #if defined(__clang__)
1071 # if __has_feature(address_sanitizer)
1072 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
1073 __attribute__((no_sanitize_address))
1074 # else
1075 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1076 # endif // __has_feature(address_sanitizer)
1077 #else
1078 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1079 #endif // __clang__
1080
1081 // A function level attribute to disable HWAddressSanitizer instrumentation.
1082 #if defined(__clang__)
1083 # if __has_feature(hwaddress_sanitizer)
1084 # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
1085 __attribute__((no_sanitize("hwaddress")))
1086 # else
1087 # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1088 # endif // __has_feature(hwaddress_sanitizer)
1089 #else
1090 # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1091 #endif // __clang__
1092
1093 // A function level attribute to disable ThreadSanitizer instrumentation.
1094 #if defined(__clang__)
1095 # if __has_feature(thread_sanitizer)
1096 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
1097 __attribute__((no_sanitize_thread))
1098 # else
1099 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
1100 # endif // __has_feature(thread_sanitizer)
1101 #else
1102 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
1103 #endif // __clang__
1104
1105 namespace testing {
1106
1107 class Message;
1108
1109 // Legacy imports for backwards compatibility.
1110 // New code should use std:: names directly.
1111 using std::get;
1112 using std::make_tuple;
1113 using std::tuple;
1114 using std::tuple_element;
1115 using std::tuple_size;
1116
1117 namespace internal {
1118
1119 // A secret type that Google Test users don't know about. It has no
1120 // definition on purpose. Therefore it's impossible to create a
1121 // Secret object, which is what we want.
1122 class Secret;
1123
1124 // The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile
1125 // time expression is true (in new code, use static_assert instead). For
1126 // example, you could use it to verify the size of a static array:
1127 //
1128 // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
1129 // names_incorrect_size);
1130 //
1131 // The second argument to the macro must be a valid C++ identifier. If the
1132 // expression is false, compiler will issue an error containing this identifier.
1133 #define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
1134
1135 // A helper for suppressing warnings on constant condition. It just
1136 // returns 'condition'.
1137 GTEST_API_ bool IsTrue(bool condition);
1138
1139 // Defines RE.
1140
1141 #if GTEST_USES_PCRE
1142 // if used, PCRE is injected by custom/gtest-port.h
1143 #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
1144
1145 // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
1146 // Regular Expression syntax.
1147 class GTEST_API_ RE {
1148 public:
1149 // A copy constructor is required by the Standard to initialize object
1150 // references from r-values.
RE(const RE & other)1151 RE(const RE& other) { Init(other.pattern()); }
1152
1153 // Constructs an RE from a string.
RE(const::std::string & regex)1154 RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT
1155
RE(const char * regex)1156 RE(const char* regex) { Init(regex); } // NOLINT
1157 ~RE();
1158
1159 // Returns the string representation of the regex.
pattern()1160 const char* pattern() const { return pattern_; }
1161
1162 // FullMatch(str, re) returns true if and only if regular expression re
1163 // matches the entire str.
1164 // PartialMatch(str, re) returns true if and only if regular expression re
1165 // matches a substring of str (including str itself).
FullMatch(const::std::string & str,const RE & re)1166 static bool FullMatch(const ::std::string& str, const RE& re) {
1167 return FullMatch(str.c_str(), re);
1168 }
PartialMatch(const::std::string & str,const RE & re)1169 static bool PartialMatch(const ::std::string& str, const RE& re) {
1170 return PartialMatch(str.c_str(), re);
1171 }
1172
1173 static bool FullMatch(const char* str, const RE& re);
1174 static bool PartialMatch(const char* str, const RE& re);
1175
1176 private:
1177 void Init(const char* regex);
1178 const char* pattern_;
1179 bool is_valid_;
1180
1181 # if GTEST_USES_POSIX_RE
1182
1183 regex_t full_regex_; // For FullMatch().
1184 regex_t partial_regex_; // For PartialMatch().
1185
1186 # else // GTEST_USES_SIMPLE_RE
1187
1188 const char* full_pattern_; // For FullMatch();
1189
1190 # endif
1191 };
1192
1193 #endif // GTEST_USES_PCRE
1194
1195 // Formats a source file path and a line number as they would appear
1196 // in an error message from the compiler used to compile this code.
1197 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
1198
1199 // Formats a file location for compiler-independent XML output.
1200 // Although this function is not platform dependent, we put it next to
1201 // FormatFileLocation in order to contrast the two functions.
1202 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
1203 int line);
1204
1205 // Defines logging utilities:
1206 // GTEST_LOG_(severity) - logs messages at the specified severity level. The
1207 // message itself is streamed into the macro.
1208 // LogToStderr() - directs all log messages to stderr.
1209 // FlushInfoLog() - flushes informational log messages.
1210
1211 enum GTestLogSeverity {
1212 GTEST_INFO,
1213 GTEST_WARNING,
1214 GTEST_ERROR,
1215 GTEST_FATAL
1216 };
1217
1218 // Formats log entry severity, provides a stream object for streaming the
1219 // log message, and terminates the message with a newline when going out of
1220 // scope.
1221 class GTEST_API_ GTestLog {
1222 public:
1223 GTestLog(GTestLogSeverity severity, const char* file, int line);
1224
1225 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
1226 ~GTestLog();
1227
GetStream()1228 ::std::ostream& GetStream() { return ::std::cerr; }
1229
1230 private:
1231 const GTestLogSeverity severity_;
1232
1233 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
1234 };
1235
1236 #if !defined(GTEST_LOG_)
1237
1238 # define GTEST_LOG_(severity) \
1239 ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
1240 __FILE__, __LINE__).GetStream()
1241
LogToStderr()1242 inline void LogToStderr() {}
FlushInfoLog()1243 inline void FlushInfoLog() { fflush(nullptr); }
1244
1245 #endif // !defined(GTEST_LOG_)
1246
1247 #if !defined(GTEST_CHECK_)
1248 // INTERNAL IMPLEMENTATION - DO NOT USE.
1249 //
1250 // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
1251 // is not satisfied.
1252 // Synopsys:
1253 // GTEST_CHECK_(boolean_condition);
1254 // or
1255 // GTEST_CHECK_(boolean_condition) << "Additional message";
1256 //
1257 // This checks the condition and if the condition is not satisfied
1258 // it prints message about the condition violation, including the
1259 // condition itself, plus additional message streamed into it, if any,
1260 // and then it aborts the program. It aborts the program irrespective of
1261 // whether it is built in the debug mode or not.
1262 # define GTEST_CHECK_(condition) \
1263 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1264 if (::testing::internal::IsTrue(condition)) \
1265 ; \
1266 else \
1267 GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
1268 #endif // !defined(GTEST_CHECK_)
1269
1270 // An all-mode assert to verify that the given POSIX-style function
1271 // call returns 0 (indicating success). Known limitation: this
1272 // doesn't expand to a balanced 'if' statement, so enclose the macro
1273 // in {} if you need to use it as the only statement in an 'if'
1274 // branch.
1275 #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
1276 if (const int gtest_error = (posix_call)) \
1277 GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
1278 << gtest_error
1279
1280 // Transforms "T" into "const T&" according to standard reference collapsing
1281 // rules (this is only needed as a backport for C++98 compilers that do not
1282 // support reference collapsing). Specifically, it transforms:
1283 //
1284 // char ==> const char&
1285 // const char ==> const char&
1286 // char& ==> char&
1287 // const char& ==> const char&
1288 //
1289 // Note that the non-const reference will not have "const" added. This is
1290 // standard, and necessary so that "T" can always bind to "const T&".
1291 template <typename T>
1292 struct ConstRef { typedef const T& type; };
1293 template <typename T>
1294 struct ConstRef<T&> { typedef T& type; };
1295
1296 // The argument T must depend on some template parameters.
1297 #define GTEST_REFERENCE_TO_CONST_(T) \
1298 typename ::testing::internal::ConstRef<T>::type
1299
1300 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1301 //
1302 // Use ImplicitCast_ as a safe version of static_cast for upcasting in
1303 // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
1304 // const Foo*). When you use ImplicitCast_, the compiler checks that
1305 // the cast is safe. Such explicit ImplicitCast_s are necessary in
1306 // surprisingly many situations where C++ demands an exact type match
1307 // instead of an argument type convertable to a target type.
1308 //
1309 // The syntax for using ImplicitCast_ is the same as for static_cast:
1310 //
1311 // ImplicitCast_<ToType>(expr)
1312 //
1313 // ImplicitCast_ would have been part of the C++ standard library,
1314 // but the proposal was submitted too late. It will probably make
1315 // its way into the language in the future.
1316 //
1317 // This relatively ugly name is intentional. It prevents clashes with
1318 // similar functions users may have (e.g., implicit_cast). The internal
1319 // namespace alone is not enough because the function can be found by ADL.
1320 template<typename To>
1321 inline To ImplicitCast_(To x) { return x; }
1322
1323 // When you upcast (that is, cast a pointer from type Foo to type
1324 // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
1325 // always succeed. When you downcast (that is, cast a pointer from
1326 // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
1327 // how do you know the pointer is really of type SubclassOfFoo? It
1328 // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
1329 // when you downcast, you should use this macro. In debug mode, we
1330 // use dynamic_cast<> to double-check the downcast is legal (we die
1331 // if it's not). In normal mode, we do the efficient static_cast<>
1332 // instead. Thus, it's important to test in debug mode to make sure
1333 // the cast is legal!
1334 // This is the only place in the code we should use dynamic_cast<>.
1335 // In particular, you SHOULDN'T be using dynamic_cast<> in order to
1336 // do RTTI (eg code like this:
1337 // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
1338 // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
1339 // You should design the code some other way not to need this.
1340 //
1341 // This relatively ugly name is intentional. It prevents clashes with
1342 // similar functions users may have (e.g., down_cast). The internal
1343 // namespace alone is not enough because the function can be found by ADL.
1344 template<typename To, typename From> // use like this: DownCast_<T*>(foo);
1345 inline To DownCast_(From* f) { // so we only accept pointers
1346 // Ensures that To is a sub-type of From *. This test is here only
1347 // for compile-time type checking, and has no overhead in an
1348 // optimized build at run-time, as it will be optimized away
1349 // completely.
1350 GTEST_INTENTIONAL_CONST_COND_PUSH_()
1351 if (false) {
1352 GTEST_INTENTIONAL_CONST_COND_POP_()
1353 const To to = nullptr;
1354 ::testing::internal::ImplicitCast_<From*>(to);
1355 }
1356
1357 #if GTEST_HAS_RTTI
1358 // RTTI: debug mode only!
1359 GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);
1360 #endif
1361 return static_cast<To>(f);
1362 }
1363
1364 // Downcasts the pointer of type Base to Derived.
1365 // Derived must be a subclass of Base. The parameter MUST
1366 // point to a class of type Derived, not any subclass of it.
1367 // When RTTI is available, the function performs a runtime
1368 // check to enforce this.
1369 template <class Derived, class Base>
1370 Derived* CheckedDowncastToActualType(Base* base) {
1371 #if GTEST_HAS_RTTI
1372 GTEST_CHECK_(typeid(*base) == typeid(Derived));
1373 #endif
1374
1375 #if GTEST_HAS_DOWNCAST_
1376 return ::down_cast<Derived*>(base);
1377 #elif GTEST_HAS_RTTI
1378 return dynamic_cast<Derived*>(base); // NOLINT
1379 #else
1380 return static_cast<Derived*>(base); // Poor man's downcast.
1381 #endif
1382 }
1383
1384 #if GTEST_HAS_STREAM_REDIRECTION
1385
1386 // Defines the stderr capturer:
1387 // CaptureStdout - starts capturing stdout.
1388 // GetCapturedStdout - stops capturing stdout and returns the captured string.
1389 // CaptureStderr - starts capturing stderr.
1390 // GetCapturedStderr - stops capturing stderr and returns the captured string.
1391 //
1392 GTEST_API_ void CaptureStdout();
1393 GTEST_API_ std::string GetCapturedStdout();
1394 GTEST_API_ void CaptureStderr();
1395 GTEST_API_ std::string GetCapturedStderr();
1396
1397 #endif // GTEST_HAS_STREAM_REDIRECTION
1398 // Returns the size (in bytes) of a file.
1399 GTEST_API_ size_t GetFileSize(FILE* file);
1400
1401 // Reads the entire content of a file as a string.
1402 GTEST_API_ std::string ReadEntireFile(FILE* file);
1403
1404 // All command line arguments.
1405 GTEST_API_ std::vector<std::string> GetArgvs();
1406
1407 #if GTEST_HAS_DEATH_TEST
1408
1409 std::vector<std::string> GetInjectableArgvs();
1410 // Deprecated: pass the args vector by value instead.
1411 void SetInjectableArgvs(const std::vector<std::string>* new_argvs);
1412 void SetInjectableArgvs(const std::vector<std::string>& new_argvs);
1413 void ClearInjectableArgvs();
1414
1415 #endif // GTEST_HAS_DEATH_TEST
1416
1417 // Defines synchronization primitives.
1418 #if GTEST_IS_THREADSAFE
1419 # if GTEST_HAS_PTHREAD
1420 // Sleeps for (roughly) n milliseconds. This function is only for testing
1421 // Google Test's own constructs. Don't use it in user tests, either
1422 // directly or indirectly.
1423 inline void SleepMilliseconds(int n) {
1424 const timespec time = {
1425 0, // 0 seconds.
1426 n * 1000L * 1000L, // And n ms.
1427 };
1428 nanosleep(&time, nullptr);
1429 }
1430 # endif // GTEST_HAS_PTHREAD
1431
1432 # if GTEST_HAS_NOTIFICATION_
1433 // Notification has already been imported into the namespace.
1434 // Nothing to do here.
1435
1436 # elif GTEST_HAS_PTHREAD
1437 // Allows a controller thread to pause execution of newly created
1438 // threads until notified. Instances of this class must be created
1439 // and destroyed in the controller thread.
1440 //
1441 // This class is only for testing Google Test's own constructs. Do not
1442 // use it in user tests, either directly or indirectly.
1443 class Notification {
1444 public:
1445 Notification() : notified_(false) {
1446 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
1447 }
1448 ~Notification() {
1449 pthread_mutex_destroy(&mutex_);
1450 }
1451
1452 // Notifies all threads created with this notification to start. Must
1453 // be called from the controller thread.
1454 void Notify() {
1455 pthread_mutex_lock(&mutex_);
1456 notified_ = true;
1457 pthread_mutex_unlock(&mutex_);
1458 }
1459
1460 // Blocks until the controller thread notifies. Must be called from a test
1461 // thread.
1462 void WaitForNotification() {
1463 for (;;) {
1464 pthread_mutex_lock(&mutex_);
1465 const bool notified = notified_;
1466 pthread_mutex_unlock(&mutex_);
1467 if (notified)
1468 break;
1469 SleepMilliseconds(10);
1470 }
1471 }
1472
1473 private:
1474 pthread_mutex_t mutex_;
1475 bool notified_;
1476
1477 GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1478 };
1479
1480 # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1481
1482 GTEST_API_ void SleepMilliseconds(int n);
1483
1484 // Provides leak-safe Windows kernel handle ownership.
1485 // Used in death tests and in threading support.
1486 class GTEST_API_ AutoHandle {
1487 public:
1488 // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
1489 // avoid including <windows.h> in this header file. Including <windows.h> is
1490 // undesirable because it defines a lot of symbols and macros that tend to
1491 // conflict with client code. This assumption is verified by
1492 // WindowsTypesTest.HANDLEIsVoidStar.
1493 typedef void* Handle;
1494 AutoHandle();
1495 explicit AutoHandle(Handle handle);
1496
1497 ~AutoHandle();
1498
1499 Handle Get() const;
1500 void Reset();
1501 void Reset(Handle handle);
1502
1503 private:
1504 // Returns true if and only if the handle is a valid handle object that can be
1505 // closed.
1506 bool IsCloseable() const;
1507
1508 Handle handle_;
1509
1510 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1511 };
1512
1513 // Allows a controller thread to pause execution of newly created
1514 // threads until notified. Instances of this class must be created
1515 // and destroyed in the controller thread.
1516 //
1517 // This class is only for testing Google Test's own constructs. Do not
1518 // use it in user tests, either directly or indirectly.
1519 class GTEST_API_ Notification {
1520 public:
1521 Notification();
1522 void Notify();
1523 void WaitForNotification();
1524
1525 private:
1526 AutoHandle event_;
1527
1528 GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1529 };
1530 # endif // GTEST_HAS_NOTIFICATION_
1531
1532 // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
1533 // defined, but we don't want to use MinGW's pthreads implementation, which
1534 // has conformance problems with some versions of the POSIX standard.
1535 # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
1536
1537 // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
1538 // Consequently, it cannot select a correct instantiation of ThreadWithParam
1539 // in order to call its Run(). Introducing ThreadWithParamBase as a
1540 // non-templated base class for ThreadWithParam allows us to bypass this
1541 // problem.
1542 class ThreadWithParamBase {
1543 public:
1544 virtual ~ThreadWithParamBase() {}
1545 virtual void Run() = 0;
1546 };
1547
1548 // pthread_create() accepts a pointer to a function type with the C linkage.
1549 // According to the Standard (7.5/1), function types with different linkages
1550 // are different even if they are otherwise identical. Some compilers (for
1551 // example, SunStudio) treat them as different types. Since class methods
1552 // cannot be defined with C-linkage we need to define a free C-function to
1553 // pass into pthread_create().
1554 extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
1555 static_cast<ThreadWithParamBase*>(thread)->Run();
1556 return nullptr;
1557 }
1558
1559 // Helper class for testing Google Test's multi-threading constructs.
1560 // To use it, write:
1561 //
1562 // void ThreadFunc(int param) { /* Do things with param */ }
1563 // Notification thread_can_start;
1564 // ...
1565 // // The thread_can_start parameter is optional; you can supply NULL.
1566 // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
1567 // thread_can_start.Notify();
1568 //
1569 // These classes are only for testing Google Test's own constructs. Do
1570 // not use them in user tests, either directly or indirectly.
1571 template <typename T>
1572 class ThreadWithParam : public ThreadWithParamBase {
1573 public:
1574 typedef void UserThreadFunc(T);
1575
1576 ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1577 : func_(func),
1578 param_(param),
1579 thread_can_start_(thread_can_start),
1580 finished_(false) {
1581 ThreadWithParamBase* const base = this;
1582 // The thread can be created only after all fields except thread_
1583 // have been initialized.
1584 GTEST_CHECK_POSIX_SUCCESS_(
1585 pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base));
1586 }
1587 ~ThreadWithParam() override { Join(); }
1588
1589 void Join() {
1590 if (!finished_) {
1591 GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr));
1592 finished_ = true;
1593 }
1594 }
1595
1596 void Run() override {
1597 if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification();
1598 func_(param_);
1599 }
1600
1601 private:
1602 UserThreadFunc* const func_; // User-supplied thread function.
1603 const T param_; // User-supplied parameter to the thread function.
1604 // When non-NULL, used to block execution until the controller thread
1605 // notifies.
1606 Notification* const thread_can_start_;
1607 bool finished_; // true if and only if we know that the thread function has
1608 // finished.
1609 pthread_t thread_; // The native thread object.
1610
1611 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1612 };
1613 # endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
1614 // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1615
1616 # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1617 // Mutex and ThreadLocal have already been imported into the namespace.
1618 // Nothing to do here.
1619
1620 # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1621
1622 // Mutex implements mutex on Windows platforms. It is used in conjunction
1623 // with class MutexLock:
1624 //
1625 // Mutex mutex;
1626 // ...
1627 // MutexLock lock(&mutex); // Acquires the mutex and releases it at the
1628 // // end of the current scope.
1629 //
1630 // A static Mutex *must* be defined or declared using one of the following
1631 // macros:
1632 // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
1633 // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
1634 //
1635 // (A non-static Mutex is defined/declared in the usual way).
1636 class GTEST_API_ Mutex {
1637 public:
1638 enum MutexType { kStatic = 0, kDynamic = 1 };
1639 // We rely on kStaticMutex being 0 as it is to what the linker initializes
1640 // type_ in static mutexes. critical_section_ will be initialized lazily
1641 // in ThreadSafeLazyInit().
1642 enum StaticConstructorSelector { kStaticMutex = 0 };
1643
1644 // This constructor intentionally does nothing. It relies on type_ being
1645 // statically initialized to 0 (effectively setting it to kStatic) and on
1646 // ThreadSafeLazyInit() to lazily initialize the rest of the members.
1647 explicit Mutex(StaticConstructorSelector /*dummy*/) {}
1648
1649 Mutex();
1650 ~Mutex();
1651
1652 void Lock();
1653
1654 void Unlock();
1655
1656 // Does nothing if the current thread holds the mutex. Otherwise, crashes
1657 // with high probability.
1658 void AssertHeld();
1659
1660 private:
1661 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
1662 void ThreadSafeLazyInit();
1663
1664 // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503,
1665 // we assume that 0 is an invalid value for thread IDs.
1666 unsigned int owner_thread_id_;
1667
1668 // For static mutexes, we rely on these members being initialized to zeros
1669 // by the linker.
1670 MutexType type_;
1671 long critical_section_init_phase_; // NOLINT
1672 GTEST_CRITICAL_SECTION* critical_section_;
1673
1674 GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1675 };
1676
1677 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1678 extern ::testing::internal::Mutex mutex
1679
1680 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1681 ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
1682
1683 // We cannot name this class MutexLock because the ctor declaration would
1684 // conflict with a macro named MutexLock, which is defined on some
1685 // platforms. That macro is used as a defensive measure to prevent against
1686 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1687 // "MutexLock l(&mu)". Hence the typedef trick below.
1688 class GTestMutexLock {
1689 public:
1690 explicit GTestMutexLock(Mutex* mutex)
1691 : mutex_(mutex) { mutex_->Lock(); }
1692
1693 ~GTestMutexLock() { mutex_->Unlock(); }
1694
1695 private:
1696 Mutex* const mutex_;
1697
1698 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1699 };
1700
1701 typedef GTestMutexLock MutexLock;
1702
1703 // Base class for ValueHolder<T>. Allows a caller to hold and delete a value
1704 // without knowing its type.
1705 class ThreadLocalValueHolderBase {
1706 public:
1707 virtual ~ThreadLocalValueHolderBase() {}
1708 };
1709
1710 // Provides a way for a thread to send notifications to a ThreadLocal
1711 // regardless of its parameter type.
1712 class ThreadLocalBase {
1713 public:
1714 // Creates a new ValueHolder<T> object holding a default value passed to
1715 // this ThreadLocal<T>'s constructor and returns it. It is the caller's
1716 // responsibility not to call this when the ThreadLocal<T> instance already
1717 // has a value on the current thread.
1718 virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
1719
1720 protected:
1721 ThreadLocalBase() {}
1722 virtual ~ThreadLocalBase() {}
1723
1724 private:
1725 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
1726 };
1727
1728 // Maps a thread to a set of ThreadLocals that have values instantiated on that
1729 // thread and notifies them when the thread exits. A ThreadLocal instance is
1730 // expected to persist until all threads it has values on have terminated.
1731 class GTEST_API_ ThreadLocalRegistry {
1732 public:
1733 // Registers thread_local_instance as having value on the current thread.
1734 // Returns a value that can be used to identify the thread from other threads.
1735 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
1736 const ThreadLocalBase* thread_local_instance);
1737
1738 // Invoked when a ThreadLocal instance is destroyed.
1739 static void OnThreadLocalDestroyed(
1740 const ThreadLocalBase* thread_local_instance);
1741 };
1742
1743 class GTEST_API_ ThreadWithParamBase {
1744 public:
1745 void Join();
1746
1747 protected:
1748 class Runnable {
1749 public:
1750 virtual ~Runnable() {}
1751 virtual void Run() = 0;
1752 };
1753
1754 ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
1755 virtual ~ThreadWithParamBase();
1756
1757 private:
1758 AutoHandle thread_;
1759 };
1760
1761 // Helper class for testing Google Test's multi-threading constructs.
1762 template <typename T>
1763 class ThreadWithParam : public ThreadWithParamBase {
1764 public:
1765 typedef void UserThreadFunc(T);
1766
1767 ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1768 : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
1769 }
1770 virtual ~ThreadWithParam() {}
1771
1772 private:
1773 class RunnableImpl : public Runnable {
1774 public:
1775 RunnableImpl(UserThreadFunc* func, T param)
1776 : func_(func),
1777 param_(param) {
1778 }
1779 virtual ~RunnableImpl() {}
1780 virtual void Run() {
1781 func_(param_);
1782 }
1783
1784 private:
1785 UserThreadFunc* const func_;
1786 const T param_;
1787
1788 GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
1789 };
1790
1791 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1792 };
1793
1794 // Implements thread-local storage on Windows systems.
1795 //
1796 // // Thread 1
1797 // ThreadLocal<int> tl(100); // 100 is the default value for each thread.
1798 //
1799 // // Thread 2
1800 // tl.set(150); // Changes the value for thread 2 only.
1801 // EXPECT_EQ(150, tl.get());
1802 //
1803 // // Thread 1
1804 // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value.
1805 // tl.set(200);
1806 // EXPECT_EQ(200, tl.get());
1807 //
1808 // The template type argument T must have a public copy constructor.
1809 // In addition, the default ThreadLocal constructor requires T to have
1810 // a public default constructor.
1811 //
1812 // The users of a TheadLocal instance have to make sure that all but one
1813 // threads (including the main one) using that instance have exited before
1814 // destroying it. Otherwise, the per-thread objects managed for them by the
1815 // ThreadLocal instance are not guaranteed to be destroyed on all platforms.
1816 //
1817 // Google Test only uses global ThreadLocal objects. That means they
1818 // will die after main() has returned. Therefore, no per-thread
1819 // object managed by Google Test will be leaked as long as all threads
1820 // using Google Test have exited when main() returns.
1821 template <typename T>
1822 class ThreadLocal : public ThreadLocalBase {
1823 public:
1824 ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
1825 explicit ThreadLocal(const T& value)
1826 : default_factory_(new InstanceValueHolderFactory(value)) {}
1827
1828 ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
1829
1830 T* pointer() { return GetOrCreateValue(); }
1831 const T* pointer() const { return GetOrCreateValue(); }
1832 const T& get() const { return *pointer(); }
1833 void set(const T& value) { *pointer() = value; }
1834
1835 private:
1836 // Holds a value of T. Can be deleted via its base class without the caller
1837 // knowing the type of T.
1838 class ValueHolder : public ThreadLocalValueHolderBase {
1839 public:
1840 ValueHolder() : value_() {}
1841 explicit ValueHolder(const T& value) : value_(value) {}
1842
1843 T* pointer() { return &value_; }
1844
1845 private:
1846 T value_;
1847 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
1848 };
1849
1850
1851 T* GetOrCreateValue() const {
1852 return static_cast<ValueHolder*>(
1853 ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
1854 }
1855
1856 virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
1857 return default_factory_->MakeNewHolder();
1858 }
1859
1860 class ValueHolderFactory {
1861 public:
1862 ValueHolderFactory() {}
1863 virtual ~ValueHolderFactory() {}
1864 virtual ValueHolder* MakeNewHolder() const = 0;
1865
1866 private:
1867 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
1868 };
1869
1870 class DefaultValueHolderFactory : public ValueHolderFactory {
1871 public:
1872 DefaultValueHolderFactory() {}
1873 ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
1874
1875 private:
1876 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
1877 };
1878
1879 class InstanceValueHolderFactory : public ValueHolderFactory {
1880 public:
1881 explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
1882 ValueHolder* MakeNewHolder() const override {
1883 return new ValueHolder(value_);
1884 }
1885
1886 private:
1887 const T value_; // The value for each thread.
1888
1889 GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
1890 };
1891
1892 std::unique_ptr<ValueHolderFactory> default_factory_;
1893
1894 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
1895 };
1896
1897 # elif GTEST_HAS_PTHREAD
1898
1899 // MutexBase and Mutex implement mutex on pthreads-based platforms.
1900 class MutexBase {
1901 public:
1902 // Acquires this mutex.
1903 void Lock() {
1904 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
1905 owner_ = pthread_self();
1906 has_owner_ = true;
1907 }
1908
1909 // Releases this mutex.
1910 void Unlock() {
1911 // Since the lock is being released the owner_ field should no longer be
1912 // considered valid. We don't protect writing to has_owner_ here, as it's
1913 // the caller's responsibility to ensure that the current thread holds the
1914 // mutex when this is called.
1915 has_owner_ = false;
1916 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
1917 }
1918
1919 // Does nothing if the current thread holds the mutex. Otherwise, crashes
1920 // with high probability.
1921 void AssertHeld() const {
1922 GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
1923 << "The current thread is not holding the mutex @" << this;
1924 }
1925
1926 // A static mutex may be used before main() is entered. It may even
1927 // be used before the dynamic initialization stage. Therefore we
1928 // must be able to initialize a static mutex object at link time.
1929 // This means MutexBase has to be a POD and its member variables
1930 // have to be public.
1931 public:
1932 pthread_mutex_t mutex_; // The underlying pthread mutex.
1933 // has_owner_ indicates whether the owner_ field below contains a valid thread
1934 // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
1935 // accesses to the owner_ field should be protected by a check of this field.
1936 // An alternative might be to memset() owner_ to all zeros, but there's no
1937 // guarantee that a zero'd pthread_t is necessarily invalid or even different
1938 // from pthread_self().
1939 bool has_owner_;
1940 pthread_t owner_; // The thread holding the mutex.
1941 };
1942
1943 // Forward-declares a static mutex.
1944 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1945 extern ::testing::internal::MutexBase mutex
1946
1947 // Defines and statically (i.e. at link time) initializes a static mutex.
1948 // The initialization list here does not explicitly initialize each field,
1949 // instead relying on default initialization for the unspecified fields. In
1950 // particular, the owner_ field (a pthread_t) is not explicitly initialized.
1951 // This allows initialization to work whether pthread_t is a scalar or struct.
1952 // The flag -Wmissing-field-initializers must not be specified for this to work.
1953 #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1954 ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0}
1955
1956 // The Mutex class can only be used for mutexes created at runtime. It
1957 // shares its API with MutexBase otherwise.
1958 class Mutex : public MutexBase {
1959 public:
1960 Mutex() {
1961 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
1962 has_owner_ = false;
1963 }
1964 ~Mutex() {
1965 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
1966 }
1967
1968 private:
1969 GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1970 };
1971
1972 // We cannot name this class MutexLock because the ctor declaration would
1973 // conflict with a macro named MutexLock, which is defined on some
1974 // platforms. That macro is used as a defensive measure to prevent against
1975 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1976 // "MutexLock l(&mu)". Hence the typedef trick below.
1977 class GTestMutexLock {
1978 public:
1979 explicit GTestMutexLock(MutexBase* mutex)
1980 : mutex_(mutex) { mutex_->Lock(); }
1981
1982 ~GTestMutexLock() { mutex_->Unlock(); }
1983
1984 private:
1985 MutexBase* const mutex_;
1986
1987 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1988 };
1989
1990 typedef GTestMutexLock MutexLock;
1991
1992 // Helpers for ThreadLocal.
1993
1994 // pthread_key_create() requires DeleteThreadLocalValue() to have
1995 // C-linkage. Therefore it cannot be templatized to access
1996 // ThreadLocal<T>. Hence the need for class
1997 // ThreadLocalValueHolderBase.
1998 class ThreadLocalValueHolderBase {
1999 public:
2000 virtual ~ThreadLocalValueHolderBase() {}
2001 };
2002
2003 // Called by pthread to delete thread-local data stored by
2004 // pthread_setspecific().
2005 extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
2006 delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
2007 }
2008
2009 // Implements thread-local storage on pthreads-based systems.
2010 template <typename T>
2011 class GTEST_API_ ThreadLocal {
2012 public:
2013 ThreadLocal()
2014 : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
2015 explicit ThreadLocal(const T& value)
2016 : key_(CreateKey()),
2017 default_factory_(new InstanceValueHolderFactory(value)) {}
2018
2019 ~ThreadLocal() {
2020 // Destroys the managed object for the current thread, if any.
2021 DeleteThreadLocalValue(pthread_getspecific(key_));
2022
2023 // Releases resources associated with the key. This will *not*
2024 // delete managed objects for other threads.
2025 GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
2026 }
2027
2028 T* pointer() { return GetOrCreateValue(); }
2029 const T* pointer() const { return GetOrCreateValue(); }
2030 const T& get() const { return *pointer(); }
2031 void set(const T& value) { *pointer() = value; }
2032
2033 private:
2034 // Holds a value of type T.
2035 class ValueHolder : public ThreadLocalValueHolderBase {
2036 public:
2037 ValueHolder() : value_() {}
2038 explicit ValueHolder(const T& value) : value_(value) {}
2039
2040 T* pointer() { return &value_; }
2041
2042 private:
2043 T value_;
2044 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
2045 };
2046
2047 static pthread_key_t CreateKey() {
2048 pthread_key_t key;
2049 // When a thread exits, DeleteThreadLocalValue() will be called on
2050 // the object managed for that thread.
2051 GTEST_CHECK_POSIX_SUCCESS_(
2052 pthread_key_create(&key, &DeleteThreadLocalValue));
2053 return key;
2054 }
2055
2056 T* GetOrCreateValue() const {
2057 ThreadLocalValueHolderBase* const holder =
2058 static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
2059 if (holder != nullptr) {
2060 return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
2061 }
2062
2063 ValueHolder* const new_holder = default_factory_->MakeNewHolder();
2064 ThreadLocalValueHolderBase* const holder_base = new_holder;
2065 GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
2066 return new_holder->pointer();
2067 }
2068
2069 class ValueHolderFactory {
2070 public:
2071 ValueHolderFactory() {}
2072 virtual ~ValueHolderFactory() {}
2073 virtual ValueHolder* MakeNewHolder() const = 0;
2074
2075 private:
2076 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
2077 };
2078
2079 class DefaultValueHolderFactory : public ValueHolderFactory {
2080 public:
2081 DefaultValueHolderFactory() {}
2082 ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
2083
2084 private:
2085 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
2086 };
2087
2088 class InstanceValueHolderFactory : public ValueHolderFactory {
2089 public:
2090 explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
2091 ValueHolder* MakeNewHolder() const override {
2092 return new ValueHolder(value_);
2093 }
2094
2095 private:
2096 const T value_; // The value for each thread.
2097
2098 GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
2099 };
2100
2101 // A key pthreads uses for looking up per-thread values.
2102 const pthread_key_t key_;
2103 std::unique_ptr<ValueHolderFactory> default_factory_;
2104
2105 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
2106 };
2107
2108 # endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
2109
2110 #else // GTEST_IS_THREADSAFE
2111
2112 // A dummy implementation of synchronization primitives (mutex, lock,
2113 // and thread-local variable). Necessary for compiling Google Test where
2114 // mutex is not supported - using Google Test in multiple threads is not
2115 // supported on such platforms.
2116
2117 class Mutex {
2118 public:
2119 Mutex() {}
2120 void Lock() {}
2121 void Unlock() {}
2122 void AssertHeld() const {}
2123 };
2124
2125 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
2126 extern ::testing::internal::Mutex mutex
2127
2128 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
2129
2130 // We cannot name this class MutexLock because the ctor declaration would
2131 // conflict with a macro named MutexLock, which is defined on some
2132 // platforms. That macro is used as a defensive measure to prevent against
2133 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
2134 // "MutexLock l(&mu)". Hence the typedef trick below.
2135 class GTestMutexLock {
2136 public:
2137 explicit GTestMutexLock(Mutex*) {} // NOLINT
2138 };
2139
2140 typedef GTestMutexLock MutexLock;
2141
2142 template <typename T>
2143 class GTEST_API_ ThreadLocal {
2144 public:
2145 ThreadLocal() : value_() {}
2146 explicit ThreadLocal(const T& value) : value_(value) {}
2147 T* pointer() { return &value_; }
2148 const T* pointer() const { return &value_; }
2149 const T& get() const { return value_; }
2150 void set(const T& value) { value_ = value; }
2151 private:
2152 T value_;
2153 };
2154
2155 #endif // GTEST_IS_THREADSAFE
2156
2157 // Returns the number of threads running in the process, or 0 to indicate that
2158 // we cannot detect it.
2159 GTEST_API_ size_t GetThreadCount();
2160
2161 #if GTEST_OS_WINDOWS
2162 # define GTEST_PATH_SEP_ "\\"
2163 # define GTEST_HAS_ALT_PATH_SEP_ 1
2164 #else
2165 # define GTEST_PATH_SEP_ "/"
2166 # define GTEST_HAS_ALT_PATH_SEP_ 0
2167 #endif // GTEST_OS_WINDOWS
2168
2169 // Utilities for char.
2170
2171 // isspace(int ch) and friends accept an unsigned char or EOF. char
2172 // may be signed, depending on the compiler (or compiler flags).
2173 // Therefore we need to cast a char to unsigned char before calling
2174 // isspace(), etc.
2175
2176 inline bool IsAlpha(char ch) {
2177 return isalpha(static_cast<unsigned char>(ch)) != 0;
2178 }
2179 inline bool IsAlNum(char ch) {
2180 return isalnum(static_cast<unsigned char>(ch)) != 0;
2181 }
2182 inline bool IsDigit(char ch) {
2183 return isdigit(static_cast<unsigned char>(ch)) != 0;
2184 }
2185 inline bool IsLower(char ch) {
2186 return islower(static_cast<unsigned char>(ch)) != 0;
2187 }
2188 inline bool IsSpace(char ch) {
2189 return isspace(static_cast<unsigned char>(ch)) != 0;
2190 }
2191 inline bool IsUpper(char ch) {
2192 return isupper(static_cast<unsigned char>(ch)) != 0;
2193 }
2194 inline bool IsXDigit(char ch) {
2195 return isxdigit(static_cast<unsigned char>(ch)) != 0;
2196 }
2197 #ifdef __cpp_char8_t
2198 inline bool IsXDigit(char8_t ch) {
2199 return isxdigit(static_cast<unsigned char>(ch)) != 0;
2200 }
2201 #endif
2202 inline bool IsXDigit(char16_t ch) {
2203 const unsigned char low_byte = static_cast<unsigned char>(ch);
2204 return ch == low_byte && isxdigit(low_byte) != 0;
2205 }
2206 inline bool IsXDigit(char32_t ch) {
2207 const unsigned char low_byte = static_cast<unsigned char>(ch);
2208 return ch == low_byte && isxdigit(low_byte) != 0;
2209 }
2210 inline bool IsXDigit(wchar_t ch) {
2211 const unsigned char low_byte = static_cast<unsigned char>(ch);
2212 return ch == low_byte && isxdigit(low_byte) != 0;
2213 }
2214
2215 inline char ToLower(char ch) {
2216 return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
2217 }
2218 inline char ToUpper(char ch) {
2219 return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
2220 }
2221
2222 inline std::string StripTrailingSpaces(std::string str) {
2223 std::string::iterator it = str.end();
2224 while (it != str.begin() && IsSpace(*--it))
2225 it = str.erase(it);
2226 return str;
2227 }
2228
2229 // The testing::internal::posix namespace holds wrappers for common
2230 // POSIX functions. These wrappers hide the differences between
2231 // Windows/MSVC and POSIX systems. Since some compilers define these
2232 // standard functions as macros, the wrapper cannot have the same name
2233 // as the wrapped function.
2234
2235 namespace posix {
2236
2237 // Functions with a different name on Windows.
2238
2239 #if GTEST_OS_WINDOWS
2240
2241 typedef struct _stat StatStruct;
2242
2243 # ifdef __BORLANDC__
2244 inline int DoIsATTY(int fd) { return isatty(fd); }
2245 inline int StrCaseCmp(const char* s1, const char* s2) {
2246 return stricmp(s1, s2);
2247 }
2248 inline char* StrDup(const char* src) { return strdup(src); }
2249 # else // !__BORLANDC__
2250 # if GTEST_OS_WINDOWS_MOBILE
2251 inline int DoIsATTY(int /* fd */) { return 0; }
2252 # else
2253 inline int DoIsATTY(int fd) { return _isatty(fd); }
2254 # endif // GTEST_OS_WINDOWS_MOBILE
2255 inline int StrCaseCmp(const char* s1, const char* s2) {
2256 return _stricmp(s1, s2);
2257 }
2258 inline char* StrDup(const char* src) { return _strdup(src); }
2259 # endif // __BORLANDC__
2260
2261 # if GTEST_OS_WINDOWS_MOBILE
2262 inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
2263 // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
2264 // time and thus not defined there.
2265 # else
2266 inline int FileNo(FILE* file) { return _fileno(file); }
2267 inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
2268 inline int RmDir(const char* dir) { return _rmdir(dir); }
2269 inline bool IsDir(const StatStruct& st) {
2270 return (_S_IFDIR & st.st_mode) != 0;
2271 }
2272 # endif // GTEST_OS_WINDOWS_MOBILE
2273
2274 #elif GTEST_OS_ESP8266
2275 typedef struct stat StatStruct;
2276
2277 inline int FileNo(FILE* file) { return fileno(file); }
2278 inline int DoIsATTY(int fd) { return isatty(fd); }
2279 inline int Stat(const char* path, StatStruct* buf) {
2280 // stat function not implemented on ESP8266
2281 return 0;
2282 }
2283 inline int StrCaseCmp(const char* s1, const char* s2) {
2284 return strcasecmp(s1, s2);
2285 }
2286 inline char* StrDup(const char* src) { return strdup(src); }
2287 inline int RmDir(const char* dir) { return rmdir(dir); }
2288 inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2289
2290 #else
2291
2292 typedef struct stat StatStruct;
2293
2294 inline int FileNo(FILE* file) { return fileno(file); }
2295 inline int DoIsATTY(int fd) { return isatty(fd); }
2296 inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
2297 inline int StrCaseCmp(const char* s1, const char* s2) {
2298 return strcasecmp(s1, s2);
2299 }
2300 inline char* StrDup(const char* src) { return strdup(src); }
2301 inline int RmDir(const char* dir) { return rmdir(dir); }
2302 inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2303
2304 #endif // GTEST_OS_WINDOWS
2305
2306 inline int IsATTY(int fd) {
2307 // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout
2308 // to a file on Linux), which is unexpected, so save the previous value, and
2309 // restore it after the call.
2310 int savedErrno = errno;
2311 int isAttyValue = DoIsATTY(fd);
2312 errno = savedErrno;
2313
2314 return isAttyValue;
2315 }
2316
2317 // Functions deprecated by MSVC 8.0.
2318
2319 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
2320
2321 // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
2322 // StrError() aren't needed on Windows CE at this time and thus not
2323 // defined there.
2324
2325 #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
2326 !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !GTEST_OS_XTENSA
2327 inline int ChDir(const char* dir) { return chdir(dir); }
2328 #endif
2329 inline FILE* FOpen(const char* path, const char* mode) {
2330 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2331 struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
2332 std::wstring_convert<wchar_codecvt> converter;
2333 std::wstring wide_path = converter.from_bytes(path);
2334 std::wstring wide_mode = converter.from_bytes(mode);
2335 return _wfopen(wide_path.c_str(), wide_mode.c_str());
2336 #else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2337 return fopen(path, mode);
2338 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2339 }
2340 #if !GTEST_OS_WINDOWS_MOBILE
2341 inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
2342 return freopen(path, mode, stream);
2343 }
2344 inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
2345 #endif
2346 inline int FClose(FILE* fp) { return fclose(fp); }
2347 #if !GTEST_OS_WINDOWS_MOBILE
2348 inline int Read(int fd, void* buf, unsigned int count) {
2349 return static_cast<int>(read(fd, buf, count));
2350 }
2351 inline int Write(int fd, const void* buf, unsigned int count) {
2352 return static_cast<int>(write(fd, buf, count));
2353 }
2354 inline int Close(int fd) { return close(fd); }
2355 inline const char* StrError(int errnum) { return strerror(errnum); }
2356 #endif
2357 inline const char* GetEnv(const char* name) {
2358 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
2359 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
2360 // We are on an embedded platform, which has no environment variables.
2361 static_cast<void>(name); // To prevent 'unused argument' warning.
2362 return nullptr;
2363 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
2364 // Environment variables which we programmatically clear will be set to the
2365 // empty string rather than unset (NULL). Handle that case.
2366 const char* const env = getenv(name);
2367 return (env != nullptr && env[0] != '\0') ? env : nullptr;
2368 #else
2369 return getenv(name);
2370 #endif
2371 }
2372
2373 GTEST_DISABLE_MSC_DEPRECATED_POP_()
2374
2375 #if GTEST_OS_WINDOWS_MOBILE
2376 // Windows CE has no C library. The abort() function is used in
2377 // several places in Google Test. This implementation provides a reasonable
2378 // imitation of standard behaviour.
2379 [[noreturn]] void Abort();
2380 #else
2381 [[noreturn]] inline void Abort() { abort(); }
2382 #endif // GTEST_OS_WINDOWS_MOBILE
2383
2384 } // namespace posix
2385
2386 // MSVC "deprecates" snprintf and issues warnings wherever it is used. In
2387 // order to avoid these warnings, we need to use _snprintf or _snprintf_s on
2388 // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate
2389 // function in order to achieve that. We use macro definition here because
2390 // snprintf is a variadic function.
2391 #if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE
2392 // MSVC 2005 and above support variadic macros.
2393 # define GTEST_SNPRINTF_(buffer, size, format, ...) \
2394 _snprintf_s(buffer, size, size, format, __VA_ARGS__)
2395 #elif defined(_MSC_VER)
2396 // Windows CE does not define _snprintf_s
2397 # define GTEST_SNPRINTF_ _snprintf
2398 #else
2399 # define GTEST_SNPRINTF_ snprintf
2400 #endif
2401
2402 // The biggest signed integer type the compiler supports.
2403 //
2404 // long long is guaranteed to be at least 64-bits in C++11.
2405 using BiggestInt = long long; // NOLINT
2406
2407 // The maximum number a BiggestInt can represent.
2408 constexpr BiggestInt kMaxBiggestInt = (std::numeric_limits<BiggestInt>::max)();
2409
2410 // This template class serves as a compile-time function from size to
2411 // type. It maps a size in bytes to a primitive type with that
2412 // size. e.g.
2413 //
2414 // TypeWithSize<4>::UInt
2415 //
2416 // is typedef-ed to be unsigned int (unsigned integer made up of 4
2417 // bytes).
2418 //
2419 // Such functionality should belong to STL, but I cannot find it
2420 // there.
2421 //
2422 // Google Test uses this class in the implementation of floating-point
2423 // comparison.
2424 //
2425 // For now it only handles UInt (unsigned int) as that's all Google Test
2426 // needs. Other types can be easily added in the future if need
2427 // arises.
2428 template <size_t size>
2429 class TypeWithSize {
2430 public:
2431 // This prevents the user from using TypeWithSize<N> with incorrect
2432 // values of N.
2433 using UInt = void;
2434 };
2435
2436 // The specialization for size 4.
2437 template <>
2438 class TypeWithSize<4> {
2439 public:
2440 using Int = std::int32_t;
2441 using UInt = std::uint32_t;
2442 };
2443
2444 // The specialization for size 8.
2445 template <>
2446 class TypeWithSize<8> {
2447 public:
2448 using Int = std::int64_t;
2449 using UInt = std::uint64_t;
2450 };
2451
2452 // Integer types of known sizes.
2453 using TimeInMillis = int64_t; // Represents time in milliseconds.
2454
2455 // Utilities for command line flags and environment variables.
2456
2457 // Macro for referencing flags.
2458 #if !defined(GTEST_FLAG)
2459 # define GTEST_FLAG(name) FLAGS_gtest_##name
2460 #endif // !defined(GTEST_FLAG)
2461
2462 #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2463 # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
2464 #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2465
2466 #if !defined(GTEST_DECLARE_bool_)
2467 # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
2468
2469 // Macros for declaring flags.
2470 # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
2471 # define GTEST_DECLARE_int32_(name) \
2472 GTEST_API_ extern std::int32_t GTEST_FLAG(name)
2473 # define GTEST_DECLARE_string_(name) \
2474 GTEST_API_ extern ::std::string GTEST_FLAG(name)
2475
2476 // Macros for defining flags.
2477 # define GTEST_DEFINE_bool_(name, default_val, doc) \
2478 GTEST_API_ bool GTEST_FLAG(name) = (default_val)
2479 # define GTEST_DEFINE_int32_(name, default_val, doc) \
2480 GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val)
2481 # define GTEST_DEFINE_string_(name, default_val, doc) \
2482 GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
2483
2484 #endif // !defined(GTEST_DECLARE_bool_)
2485
2486 // Thread annotations
2487 #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2488 # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
2489 # define GTEST_LOCK_EXCLUDED_(locks)
2490 #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2491
2492 // Parses 'str' for a 32-bit signed integer. If successful, writes the result
2493 // to *value and returns true; otherwise leaves *value unchanged and returns
2494 // false.
2495 GTEST_API_ bool ParseInt32(const Message& src_text, const char* str,
2496 int32_t* value);
2497
2498 // Parses a bool/int32_t/string from the environment variable
2499 // corresponding to the given Google Test flag.
2500 bool BoolFromGTestEnv(const char* flag, bool default_val);
2501 GTEST_API_ int32_t Int32FromGTestEnv(const char* flag, int32_t default_val);
2502 std::string OutputFlagAlsoCheckEnvVar();
2503 const char* StringFromGTestEnv(const char* flag, const char* default_val);
2504
2505 } // namespace internal
2506 } // namespace testing
2507
2508 #if !defined(GTEST_INTERNAL_DEPRECATED)
2509
2510 // Internal Macro to mark an API deprecated, for googletest usage only
2511 // Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or
2512 // GTEST_INTERNAL_DEPRECATED(message) <return_type> myFunction(); Every usage of
2513 // a deprecated entity will trigger a warning when compiled with
2514 // `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler).
2515 // For msvc /W3 option will need to be used
2516 // Note that for 'other' compilers this macro evaluates to nothing to prevent
2517 // compilations errors.
2518 #if defined(_MSC_VER)
2519 #define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message))
2520 #elif defined(__GNUC__)
2521 #define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message)))
2522 #else
2523 #define GTEST_INTERNAL_DEPRECATED(message)
2524 #endif
2525
2526 #endif // !defined(GTEST_INTERNAL_DEPRECATED)
2527
2528 #if GTEST_HAS_ABSL
2529 // Always use absl::any for UniversalPrinter<> specializations if googletest
2530 // is built with absl support.
2531 #define GTEST_INTERNAL_HAS_ANY 1
2532 #include "absl/types/any.h"
2533 namespace testing {
2534 namespace internal {
2535 using Any = ::absl::any;
2536 } // namespace internal
2537 } // namespace testing
2538 #else
2539 #ifdef __has_include
2540 #if __has_include(<any>) && __cplusplus >= 201703L
2541 // Otherwise for C++17 and higher use std::any for UniversalPrinter<>
2542 // specializations.
2543 #define GTEST_INTERNAL_HAS_ANY 1
2544 #include <any>
2545 namespace testing {
2546 namespace internal {
2547 using Any = ::std::any;
2548 } // namespace internal
2549 } // namespace testing
2550 // The case where absl is configured NOT to alias std::any is not
2551 // supported.
2552 #endif // __has_include(<any>) && __cplusplus >= 201703L
2553 #endif // __has_include
2554 #endif // GTEST_HAS_ABSL
2555
2556 #if GTEST_HAS_ABSL
2557 // Always use absl::optional for UniversalPrinter<> specializations if
2558 // googletest is built with absl support.
2559 #define GTEST_INTERNAL_HAS_OPTIONAL 1
2560 #include "absl/types/optional.h"
2561 namespace testing {
2562 namespace internal {
2563 template <typename T>
2564 using Optional = ::absl::optional<T>;
2565 } // namespace internal
2566 } // namespace testing
2567 #else
2568 #ifdef __has_include
2569 #if __has_include(<optional>) && __cplusplus >= 201703L
2570 // Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
2571 // specializations.
2572 #define GTEST_INTERNAL_HAS_OPTIONAL 1
2573 #include <optional>
2574 namespace testing {
2575 namespace internal {
2576 template <typename T>
2577 using Optional = ::std::optional<T>;
2578 } // namespace internal
2579 } // namespace testing
2580 // The case where absl is configured NOT to alias std::optional is not
2581 // supported.
2582 #endif // __has_include(<optional>) && __cplusplus >= 201703L
2583 #endif // __has_include
2584 #endif // GTEST_HAS_ABSL
2585
2586 #if GTEST_HAS_ABSL
2587 // Always use absl::string_view for Matcher<> specializations if googletest
2588 // is built with absl support.
2589 # define GTEST_INTERNAL_HAS_STRING_VIEW 1
2590 #include "absl/strings/string_view.h"
2591 namespace testing {
2592 namespace internal {
2593 using StringView = ::absl::string_view;
2594 } // namespace internal
2595 } // namespace testing
2596 #else
2597 # ifdef __has_include
2598 # if __has_include(<string_view>) && __cplusplus >= 201703L
2599 // Otherwise for C++17 and higher use std::string_view for Matcher<>
2600 // specializations.
2601 # define GTEST_INTERNAL_HAS_STRING_VIEW 1
2602 #include <string_view>
2603 namespace testing {
2604 namespace internal {
2605 using StringView = ::std::string_view;
2606 } // namespace internal
2607 } // namespace testing
2608 // The case where absl is configured NOT to alias std::string_view is not
2609 // supported.
2610 # endif // __has_include(<string_view>) && __cplusplus >= 201703L
2611 # endif // __has_include
2612 #endif // GTEST_HAS_ABSL
2613
2614 #if GTEST_HAS_ABSL
2615 // Always use absl::variant for UniversalPrinter<> specializations if googletest
2616 // is built with absl support.
2617 #define GTEST_INTERNAL_HAS_VARIANT 1
2618 #include "absl/types/variant.h"
2619 namespace testing {
2620 namespace internal {
2621 template <typename... T>
2622 using Variant = ::absl::variant<T...>;
2623 } // namespace internal
2624 } // namespace testing
2625 #else
2626 #ifdef __has_include
2627 #if __has_include(<variant>) && __cplusplus >= 201703L
2628 // Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
2629 // specializations.
2630 #define GTEST_INTERNAL_HAS_VARIANT 1
2631 #include <variant>
2632 namespace testing {
2633 namespace internal {
2634 template <typename... T>
2635 using Variant = ::std::variant<T...>;
2636 } // namespace internal
2637 } // namespace testing
2638 // The case where absl is configured NOT to alias std::variant is not supported.
2639 #endif // __has_include(<variant>) && __cplusplus >= 201703L
2640 #endif // __has_include
2641 #endif // GTEST_HAS_ABSL
2642
2643 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
2644
2645 #if GTEST_OS_LINUX
2646 # include <stdlib.h>
2647 # include <sys/types.h>
2648 # include <sys/wait.h>
2649 # include <unistd.h>
2650 #endif // GTEST_OS_LINUX
2651
2652 #if GTEST_HAS_EXCEPTIONS
2653 # include <stdexcept>
2654 #endif
2655
2656 #include <ctype.h>
2657 #include <float.h>
2658 #include <string.h>
2659 #include <cstdint>
2660 #include <iomanip>
2661 #include <limits>
2662 #include <map>
2663 #include <set>
2664 #include <string>
2665 #include <type_traits>
2666 #include <vector>
2667
2668 // Copyright 2005, Google Inc.
2669 // All rights reserved.
2670 //
2671 // Redistribution and use in source and binary forms, with or without
2672 // modification, are permitted provided that the following conditions are
2673 // met:
2674 //
2675 // * Redistributions of source code must retain the above copyright
2676 // notice, this list of conditions and the following disclaimer.
2677 // * Redistributions in binary form must reproduce the above
2678 // copyright notice, this list of conditions and the following disclaimer
2679 // in the documentation and/or other materials provided with the
2680 // distribution.
2681 // * Neither the name of Google Inc. nor the names of its
2682 // contributors may be used to endorse or promote products derived from
2683 // this software without specific prior written permission.
2684 //
2685 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2686 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2687 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2688 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2689 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2690 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2691 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2692 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2693 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2694 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2695 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2696
2697 //
2698 // The Google C++ Testing and Mocking Framework (Google Test)
2699 //
2700 // This header file defines the Message class.
2701 //
2702 // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
2703 // leave some internal implementation details in this header file.
2704 // They are clearly marked by comments like this:
2705 //
2706 // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2707 //
2708 // Such code is NOT meant to be used by a user directly, and is subject
2709 // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
2710 // program!
2711
2712 // GOOGLETEST_CM0001 DO NOT DELETE
2713
2714 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
2715 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
2716
2717 #include <limits>
2718 #include <memory>
2719 #include <sstream>
2720
2721
2722 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
2723 /* class A needs to have dll-interface to be used by clients of class B */)
2724
2725 // Ensures that there is at least one operator<< in the global namespace.
2726 // See Message& operator<<(...) below for why.
2727 void operator<<(const testing::internal::Secret&, int);
2728
2729 namespace testing {
2730
2731 // The Message class works like an ostream repeater.
2732 //
2733 // Typical usage:
2734 //
2735 // 1. You stream a bunch of values to a Message object.
2736 // It will remember the text in a stringstream.
2737 // 2. Then you stream the Message object to an ostream.
2738 // This causes the text in the Message to be streamed
2739 // to the ostream.
2740 //
2741 // For example;
2742 //
2743 // testing::Message foo;
2744 // foo << 1 << " != " << 2;
2745 // std::cout << foo;
2746 //
2747 // will print "1 != 2".
2748 //
2749 // Message is not intended to be inherited from. In particular, its
2750 // destructor is not virtual.
2751 //
2752 // Note that stringstream behaves differently in gcc and in MSVC. You
2753 // can stream a NULL char pointer to it in the former, but not in the
2754 // latter (it causes an access violation if you do). The Message
2755 // class hides this difference by treating a NULL char pointer as
2756 // "(null)".
2757 class GTEST_API_ Message {
2758 private:
2759 // The type of basic IO manipulators (endl, ends, and flush) for
2760 // narrow streams.
2761 typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
2762
2763 public:
2764 // Constructs an empty Message.
2765 Message();
2766
2767 // Copy constructor.
2768 Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT
2769 *ss_ << msg.GetString();
2770 }
2771
2772 // Constructs a Message from a C-string.
2773 explicit Message(const char* str) : ss_(new ::std::stringstream) {
2774 *ss_ << str;
2775 }
2776
2777 // Streams a non-pointer value to this object.
2778 template <typename T>
2779 inline Message& operator <<(const T& val) {
2780 // Some libraries overload << for STL containers. These
2781 // overloads are defined in the global namespace instead of ::std.
2782 //
2783 // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
2784 // overloads are visible in either the std namespace or the global
2785 // namespace, but not other namespaces, including the testing
2786 // namespace which Google Test's Message class is in.
2787 //
2788 // To allow STL containers (and other types that has a << operator
2789 // defined in the global namespace) to be used in Google Test
2790 // assertions, testing::Message must access the custom << operator
2791 // from the global namespace. With this using declaration,
2792 // overloads of << defined in the global namespace and those
2793 // visible via Koenig lookup are both exposed in this function.
2794 using ::operator <<;
2795 *ss_ << val;
2796 return *this;
2797 }
2798
2799 // Streams a pointer value to this object.
2800 //
2801 // This function is an overload of the previous one. When you
2802 // stream a pointer to a Message, this definition will be used as it
2803 // is more specialized. (The C++ Standard, section
2804 // [temp.func.order].) If you stream a non-pointer, then the
2805 // previous definition will be used.
2806 //
2807 // The reason for this overload is that streaming a NULL pointer to
2808 // ostream is undefined behavior. Depending on the compiler, you
2809 // may get "0", "(nil)", "(null)", or an access violation. To
2810 // ensure consistent result across compilers, we always treat NULL
2811 // as "(null)".
2812 template <typename T>
2813 inline Message& operator <<(T* const& pointer) { // NOLINT
2814 if (pointer == nullptr) {
2815 *ss_ << "(null)";
2816 } else {
2817 *ss_ << pointer;
2818 }
2819 return *this;
2820 }
2821
2822 // Since the basic IO manipulators are overloaded for both narrow
2823 // and wide streams, we have to provide this specialized definition
2824 // of operator <<, even though its body is the same as the
2825 // templatized version above. Without this definition, streaming
2826 // endl or other basic IO manipulators to Message will confuse the
2827 // compiler.
2828 Message& operator <<(BasicNarrowIoManip val) {
2829 *ss_ << val;
2830 return *this;
2831 }
2832
2833 // Instead of 1/0, we want to see true/false for bool values.
2834 Message& operator <<(bool b) {
2835 return *this << (b ? "true" : "false");
2836 }
2837
2838 // These two overloads allow streaming a wide C string to a Message
2839 // using the UTF-8 encoding.
2840 Message& operator <<(const wchar_t* wide_c_str);
2841 Message& operator <<(wchar_t* wide_c_str);
2842
2843 #if GTEST_HAS_STD_WSTRING
2844 // Converts the given wide string to a narrow string using the UTF-8
2845 // encoding, and streams the result to this Message object.
2846 Message& operator <<(const ::std::wstring& wstr);
2847 #endif // GTEST_HAS_STD_WSTRING
2848
2849 // Gets the text streamed to this object so far as an std::string.
2850 // Each '\0' character in the buffer is replaced with "\\0".
2851 //
2852 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2853 std::string GetString() const;
2854
2855 private:
2856 // We'll hold the text streamed to this object here.
2857 const std::unique_ptr< ::std::stringstream> ss_;
2858
2859 // We declare (but don't implement) this to prevent the compiler
2860 // from implementing the assignment operator.
2861 void operator=(const Message&);
2862 };
2863
2864 // Streams a Message to an ostream.
2865 inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
2866 return os << sb.GetString();
2867 }
2868
2869 namespace internal {
2870
2871 // Converts a streamable value to an std::string. A NULL pointer is
2872 // converted to "(null)". When the input value is a ::string,
2873 // ::std::string, ::wstring, or ::std::wstring object, each NUL
2874 // character in it is replaced with "\\0".
2875 template <typename T>
2876 std::string StreamableToString(const T& streamable) {
2877 return (Message() << streamable).GetString();
2878 }
2879
2880 } // namespace internal
2881 } // namespace testing
2882
2883 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
2884
2885 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
2886 // Copyright 2008, Google Inc.
2887 // All rights reserved.
2888 //
2889 // Redistribution and use in source and binary forms, with or without
2890 // modification, are permitted provided that the following conditions are
2891 // met:
2892 //
2893 // * Redistributions of source code must retain the above copyright
2894 // notice, this list of conditions and the following disclaimer.
2895 // * Redistributions in binary form must reproduce the above
2896 // copyright notice, this list of conditions and the following disclaimer
2897 // in the documentation and/or other materials provided with the
2898 // distribution.
2899 // * Neither the name of Google Inc. nor the names of its
2900 // contributors may be used to endorse or promote products derived from
2901 // this software without specific prior written permission.
2902 //
2903 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2904 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2905 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2906 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2907 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2908 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2909 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2910 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2911 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2912 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2913 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2914 //
2915 // Google Test filepath utilities
2916 //
2917 // This header file declares classes and functions used internally by
2918 // Google Test. They are subject to change without notice.
2919 //
2920 // This file is #included in gtest/internal/gtest-internal.h.
2921 // Do not include this header file separately!
2922
2923 // GOOGLETEST_CM0001 DO NOT DELETE
2924
2925 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
2926 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
2927
2928 // Copyright 2005, Google Inc.
2929 // All rights reserved.
2930 //
2931 // Redistribution and use in source and binary forms, with or without
2932 // modification, are permitted provided that the following conditions are
2933 // met:
2934 //
2935 // * Redistributions of source code must retain the above copyright
2936 // notice, this list of conditions and the following disclaimer.
2937 // * Redistributions in binary form must reproduce the above
2938 // copyright notice, this list of conditions and the following disclaimer
2939 // in the documentation and/or other materials provided with the
2940 // distribution.
2941 // * Neither the name of Google Inc. nor the names of its
2942 // contributors may be used to endorse or promote products derived from
2943 // this software without specific prior written permission.
2944 //
2945 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2946 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2947 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2948 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2949 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2950 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2951 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2952 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2953 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2954 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2955 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2956 //
2957 // The Google C++ Testing and Mocking Framework (Google Test)
2958 //
2959 // This header file declares the String class and functions used internally by
2960 // Google Test. They are subject to change without notice. They should not used
2961 // by code external to Google Test.
2962 //
2963 // This header file is #included by gtest-internal.h.
2964 // It should not be #included by other files.
2965
2966 // GOOGLETEST_CM0001 DO NOT DELETE
2967
2968 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
2969 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
2970
2971 #ifdef __BORLANDC__
2972 // string.h is not guaranteed to provide strcpy on C++ Builder.
2973 # include <mem.h>
2974 #endif
2975
2976 #include <string.h>
2977 #include <cstdint>
2978 #include <string>
2979
2980
2981 namespace testing {
2982 namespace internal {
2983
2984 // String - an abstract class holding static string utilities.
2985 class GTEST_API_ String {
2986 public:
2987 // Static utility methods
2988
2989 // Clones a 0-terminated C string, allocating memory using new. The
2990 // caller is responsible for deleting the return value using
2991 // delete[]. Returns the cloned string, or NULL if the input is
2992 // NULL.
2993 //
2994 // This is different from strdup() in string.h, which allocates
2995 // memory using malloc().
2996 static const char* CloneCString(const char* c_str);
2997
2998 #if GTEST_OS_WINDOWS_MOBILE
2999 // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
3000 // able to pass strings to Win32 APIs on CE we need to convert them
3001 // to 'Unicode', UTF-16.
3002
3003 // Creates a UTF-16 wide string from the given ANSI string, allocating
3004 // memory using new. The caller is responsible for deleting the return
3005 // value using delete[]. Returns the wide string, or NULL if the
3006 // input is NULL.
3007 //
3008 // The wide string is created using the ANSI codepage (CP_ACP) to
3009 // match the behaviour of the ANSI versions of Win32 calls and the
3010 // C runtime.
3011 static LPCWSTR AnsiToUtf16(const char* c_str);
3012
3013 // Creates an ANSI string from the given wide string, allocating
3014 // memory using new. The caller is responsible for deleting the return
3015 // value using delete[]. Returns the ANSI string, or NULL if the
3016 // input is NULL.
3017 //
3018 // The returned string is created using the ANSI codepage (CP_ACP) to
3019 // match the behaviour of the ANSI versions of Win32 calls and the
3020 // C runtime.
3021 static const char* Utf16ToAnsi(LPCWSTR utf16_str);
3022 #endif
3023
3024 // Compares two C strings. Returns true if and only if they have the same
3025 // content.
3026 //
3027 // Unlike strcmp(), this function can handle NULL argument(s). A
3028 // NULL C string is considered different to any non-NULL C string,
3029 // including the empty string.
3030 static bool CStringEquals(const char* lhs, const char* rhs);
3031
3032 // Converts a wide C string to a String using the UTF-8 encoding.
3033 // NULL will be converted to "(null)". If an error occurred during
3034 // the conversion, "(failed to convert from wide string)" is
3035 // returned.
3036 static std::string ShowWideCString(const wchar_t* wide_c_str);
3037
3038 // Compares two wide C strings. Returns true if and only if they have the
3039 // same content.
3040 //
3041 // Unlike wcscmp(), this function can handle NULL argument(s). A
3042 // NULL C string is considered different to any non-NULL C string,
3043 // including the empty string.
3044 static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
3045
3046 // Compares two C strings, ignoring case. Returns true if and only if
3047 // they have the same content.
3048 //
3049 // Unlike strcasecmp(), this function can handle NULL argument(s).
3050 // A NULL C string is considered different to any non-NULL C string,
3051 // including the empty string.
3052 static bool CaseInsensitiveCStringEquals(const char* lhs,
3053 const char* rhs);
3054
3055 // Compares two wide C strings, ignoring case. Returns true if and only if
3056 // they have the same content.
3057 //
3058 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3059 // A NULL C string is considered different to any non-NULL wide C string,
3060 // including the empty string.
3061 // NB: The implementations on different platforms slightly differ.
3062 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3063 // environment variable. On GNU platform this method uses wcscasecmp
3064 // which compares according to LC_CTYPE category of the current locale.
3065 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3066 // current locale.
3067 static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3068 const wchar_t* rhs);
3069
3070 // Returns true if and only if the given string ends with the given suffix,
3071 // ignoring case. Any string is considered to end with an empty suffix.
3072 static bool EndsWithCaseInsensitive(
3073 const std::string& str, const std::string& suffix);
3074
3075 // Formats an int value as "%02d".
3076 static std::string FormatIntWidth2(int value); // "%02d" for width == 2
3077
3078 // Formats an int value to given width with leading zeros.
3079 static std::string FormatIntWidthN(int value, int width);
3080
3081 // Formats an int value as "%X".
3082 static std::string FormatHexInt(int value);
3083
3084 // Formats an int value as "%X".
3085 static std::string FormatHexUInt32(uint32_t value);
3086
3087 // Formats a byte as "%02X".
3088 static std::string FormatByte(unsigned char value);
3089
3090 private:
3091 String(); // Not meant to be instantiated.
3092 }; // class String
3093
3094 // Gets the content of the stringstream's buffer as an std::string. Each '\0'
3095 // character in the buffer is replaced with "\\0".
3096 GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
3097
3098 } // namespace internal
3099 } // namespace testing
3100
3101 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
3102
3103 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
3104 /* class A needs to have dll-interface to be used by clients of class B */)
3105
3106 namespace testing {
3107 namespace internal {
3108
3109 // FilePath - a class for file and directory pathname manipulation which
3110 // handles platform-specific conventions (like the pathname separator).
3111 // Used for helper functions for naming files in a directory for xml output.
3112 // Except for Set methods, all methods are const or static, which provides an
3113 // "immutable value object" -- useful for peace of mind.
3114 // A FilePath with a value ending in a path separator ("like/this/") represents
3115 // a directory, otherwise it is assumed to represent a file. In either case,
3116 // it may or may not represent an actual file or directory in the file system.
3117 // Names are NOT checked for syntax correctness -- no checking for illegal
3118 // characters, malformed paths, etc.
3119
3120 class GTEST_API_ FilePath {
3121 public:
3122 FilePath() : pathname_("") { }
3123 FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
3124
3125 explicit FilePath(const std::string& pathname) : pathname_(pathname) {
3126 Normalize();
3127 }
3128
3129 FilePath& operator=(const FilePath& rhs) {
3130 Set(rhs);
3131 return *this;
3132 }
3133
3134 void Set(const FilePath& rhs) {
3135 pathname_ = rhs.pathname_;
3136 }
3137
3138 const std::string& string() const { return pathname_; }
3139 const char* c_str() const { return pathname_.c_str(); }
3140
3141 // Returns the current working directory, or "" if unsuccessful.
3142 static FilePath GetCurrentDir();
3143
3144 // Given directory = "dir", base_name = "test", number = 0,
3145 // extension = "xml", returns "dir/test.xml". If number is greater
3146 // than zero (e.g., 12), returns "dir/test_12.xml".
3147 // On Windows platform, uses \ as the separator rather than /.
3148 static FilePath MakeFileName(const FilePath& directory,
3149 const FilePath& base_name,
3150 int number,
3151 const char* extension);
3152
3153 // Given directory = "dir", relative_path = "test.xml",
3154 // returns "dir/test.xml".
3155 // On Windows, uses \ as the separator rather than /.
3156 static FilePath ConcatPaths(const FilePath& directory,
3157 const FilePath& relative_path);
3158
3159 // Returns a pathname for a file that does not currently exist. The pathname
3160 // will be directory/base_name.extension or
3161 // directory/base_name_<number>.extension if directory/base_name.extension
3162 // already exists. The number will be incremented until a pathname is found
3163 // that does not already exist.
3164 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
3165 // There could be a race condition if two or more processes are calling this
3166 // function at the same time -- they could both pick the same filename.
3167 static FilePath GenerateUniqueFileName(const FilePath& directory,
3168 const FilePath& base_name,
3169 const char* extension);
3170
3171 // Returns true if and only if the path is "".
3172 bool IsEmpty() const { return pathname_.empty(); }
3173
3174 // If input name has a trailing separator character, removes it and returns
3175 // the name, otherwise return the name string unmodified.
3176 // On Windows platform, uses \ as the separator, other platforms use /.
3177 FilePath RemoveTrailingPathSeparator() const;
3178
3179 // Returns a copy of the FilePath with the directory part removed.
3180 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
3181 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
3182 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
3183 // returns an empty FilePath ("").
3184 // On Windows platform, '\' is the path separator, otherwise it is '/'.
3185 FilePath RemoveDirectoryName() const;
3186
3187 // RemoveFileName returns the directory path with the filename removed.
3188 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
3189 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
3190 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
3191 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
3192 // On Windows platform, '\' is the path separator, otherwise it is '/'.
3193 FilePath RemoveFileName() const;
3194
3195 // Returns a copy of the FilePath with the case-insensitive extension removed.
3196 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
3197 // FilePath("dir/file"). If a case-insensitive extension is not
3198 // found, returns a copy of the original FilePath.
3199 FilePath RemoveExtension(const char* extension) const;
3200
3201 // Creates directories so that path exists. Returns true if successful or if
3202 // the directories already exist; returns false if unable to create
3203 // directories for any reason. Will also return false if the FilePath does
3204 // not represent a directory (that is, it doesn't end with a path separator).
3205 bool CreateDirectoriesRecursively() const;
3206
3207 // Create the directory so that path exists. Returns true if successful or
3208 // if the directory already exists; returns false if unable to create the
3209 // directory for any reason, including if the parent directory does not
3210 // exist. Not named "CreateDirectory" because that's a macro on Windows.
3211 bool CreateFolder() const;
3212
3213 // Returns true if FilePath describes something in the file-system,
3214 // either a file, directory, or whatever, and that something exists.
3215 bool FileOrDirectoryExists() const;
3216
3217 // Returns true if pathname describes a directory in the file-system
3218 // that exists.
3219 bool DirectoryExists() const;
3220
3221 // Returns true if FilePath ends with a path separator, which indicates that
3222 // it is intended to represent a directory. Returns false otherwise.
3223 // This does NOT check that a directory (or file) actually exists.
3224 bool IsDirectory() const;
3225
3226 // Returns true if pathname describes a root directory. (Windows has one
3227 // root directory per disk drive.)
3228 bool IsRootDirectory() const;
3229
3230 // Returns true if pathname describes an absolute path.
3231 bool IsAbsolutePath() const;
3232
3233 private:
3234 // Replaces multiple consecutive separators with a single separator.
3235 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
3236 // redundancies that might be in a pathname involving "." or "..".
3237 //
3238 // A pathname with multiple consecutive separators may occur either through
3239 // user error or as a result of some scripts or APIs that generate a pathname
3240 // with a trailing separator. On other platforms the same API or script
3241 // may NOT generate a pathname with a trailing "/". Then elsewhere that
3242 // pathname may have another "/" and pathname components added to it,
3243 // without checking for the separator already being there.
3244 // The script language and operating system may allow paths like "foo//bar"
3245 // but some of the functions in FilePath will not handle that correctly. In
3246 // particular, RemoveTrailingPathSeparator() only removes one separator, and
3247 // it is called in CreateDirectoriesRecursively() assuming that it will change
3248 // a pathname from directory syntax (trailing separator) to filename syntax.
3249 //
3250 // On Windows this method also replaces the alternate path separator '/' with
3251 // the primary path separator '\\', so that for example "bar\\/\\foo" becomes
3252 // "bar\\foo".
3253
3254 void Normalize();
3255
3256 // Returns a pointer to the last occurrence of a valid path separator in
3257 // the FilePath. On Windows, for example, both '/' and '\' are valid path
3258 // separators. Returns NULL if no path separator was found.
3259 const char* FindLastPathSeparator() const;
3260
3261 std::string pathname_;
3262 }; // class FilePath
3263
3264 } // namespace internal
3265 } // namespace testing
3266
3267 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
3268
3269 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
3270 // Copyright 2008 Google Inc.
3271 // All Rights Reserved.
3272 //
3273 // Redistribution and use in source and binary forms, with or without
3274 // modification, are permitted provided that the following conditions are
3275 // met:
3276 //
3277 // * Redistributions of source code must retain the above copyright
3278 // notice, this list of conditions and the following disclaimer.
3279 // * Redistributions in binary form must reproduce the above
3280 // copyright notice, this list of conditions and the following disclaimer
3281 // in the documentation and/or other materials provided with the
3282 // distribution.
3283 // * Neither the name of Google Inc. nor the names of its
3284 // contributors may be used to endorse or promote products derived from
3285 // this software without specific prior written permission.
3286 //
3287 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
3288 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
3289 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
3290 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3291 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3292 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3293 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3294 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3295 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3296 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3297 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3298
3299 // Type utilities needed for implementing typed and type-parameterized
3300 // tests.
3301
3302 // GOOGLETEST_CM0001 DO NOT DELETE
3303
3304 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
3305 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
3306
3307
3308 // #ifdef __GNUC__ is too general here. It is possible to use gcc without using
3309 // libstdc++ (which is where cxxabi.h comes from).
3310 # if GTEST_HAS_CXXABI_H_
3311 # include <cxxabi.h>
3312 # elif defined(__HP_aCC)
3313 # include <acxx_demangle.h>
3314 # endif // GTEST_HASH_CXXABI_H_
3315
3316 namespace testing {
3317 namespace internal {
3318
3319 // Canonicalizes a given name with respect to the Standard C++ Library.
3320 // This handles removing the inline namespace within `std` that is
3321 // used by various standard libraries (e.g., `std::__1`). Names outside
3322 // of namespace std are returned unmodified.
3323 inline std::string CanonicalizeForStdLibVersioning(std::string s) {
3324 static const char prefix[] = "std::__";
3325 if (s.compare(0, strlen(prefix), prefix) == 0) {
3326 std::string::size_type end = s.find("::", strlen(prefix));
3327 if (end != s.npos) {
3328 // Erase everything between the initial `std` and the second `::`.
3329 s.erase(strlen("std"), end - strlen("std"));
3330 }
3331 }
3332 return s;
3333 }
3334
3335 #if GTEST_HAS_RTTI
3336 // GetTypeName(const std::type_info&) returns a human-readable name of type T.
3337 inline std::string GetTypeName(const std::type_info& type) {
3338 const char* const name = type.name();
3339 #if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
3340 int status = 0;
3341 // gcc's implementation of typeid(T).name() mangles the type name,
3342 // so we have to demangle it.
3343 #if GTEST_HAS_CXXABI_H_
3344 using abi::__cxa_demangle;
3345 #endif // GTEST_HAS_CXXABI_H_
3346 char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
3347 const std::string name_str(status == 0 ? readable_name : name);
3348 free(readable_name);
3349 return CanonicalizeForStdLibVersioning(name_str);
3350 #else
3351 return name;
3352 #endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
3353 }
3354 #endif // GTEST_HAS_RTTI
3355
3356 // GetTypeName<T>() returns a human-readable name of type T if and only if
3357 // RTTI is enabled, otherwise it returns a dummy type name.
3358 // NB: This function is also used in Google Mock, so don't move it inside of
3359 // the typed-test-only section below.
3360 template <typename T>
3361 std::string GetTypeName() {
3362 #if GTEST_HAS_RTTI
3363 return GetTypeName(typeid(T));
3364 #else
3365 return "<type>";
3366 #endif // GTEST_HAS_RTTI
3367 }
3368
3369 // A unique type indicating an empty node
3370 struct None {};
3371
3372 # define GTEST_TEMPLATE_ template <typename T> class
3373
3374 // The template "selector" struct TemplateSel<Tmpl> is used to
3375 // represent Tmpl, which must be a class template with one type
3376 // parameter, as a type. TemplateSel<Tmpl>::Bind<T>::type is defined
3377 // as the type Tmpl<T>. This allows us to actually instantiate the
3378 // template "selected" by TemplateSel<Tmpl>.
3379 //
3380 // This trick is necessary for simulating typedef for class templates,
3381 // which C++ doesn't support directly.
3382 template <GTEST_TEMPLATE_ Tmpl>
3383 struct TemplateSel {
3384 template <typename T>
3385 struct Bind {
3386 typedef Tmpl<T> type;
3387 };
3388 };
3389
3390 # define GTEST_BIND_(TmplSel, T) \
3391 TmplSel::template Bind<T>::type
3392
3393 template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>
3394 struct Templates {
3395 using Head = TemplateSel<Head_>;
3396 using Tail = Templates<Tail_...>;
3397 };
3398
3399 template <GTEST_TEMPLATE_ Head_>
3400 struct Templates<Head_> {
3401 using Head = TemplateSel<Head_>;
3402 using Tail = None;
3403 };
3404
3405 // Tuple-like type lists
3406 template <typename Head_, typename... Tail_>
3407 struct Types {
3408 using Head = Head_;
3409 using Tail = Types<Tail_...>;
3410 };
3411
3412 template <typename Head_>
3413 struct Types<Head_> {
3414 using Head = Head_;
3415 using Tail = None;
3416 };
3417
3418 // Helper metafunctions to tell apart a single type from types
3419 // generated by ::testing::Types
3420 template <typename... Ts>
3421 struct ProxyTypeList {
3422 using type = Types<Ts...>;
3423 };
3424
3425 template <typename>
3426 struct is_proxy_type_list : std::false_type {};
3427
3428 template <typename... Ts>
3429 struct is_proxy_type_list<ProxyTypeList<Ts...>> : std::true_type {};
3430
3431 // Generator which conditionally creates type lists.
3432 // It recognizes if a requested type list should be created
3433 // and prevents creating a new type list nested within another one.
3434 template <typename T>
3435 struct GenerateTypeList {
3436 private:
3437 using proxy = typename std::conditional<is_proxy_type_list<T>::value, T,
3438 ProxyTypeList<T>>::type;
3439
3440 public:
3441 using type = typename proxy::type;
3442 };
3443
3444 } // namespace internal
3445
3446 template <typename... Ts>
3447 using Types = internal::ProxyTypeList<Ts...>;
3448
3449 } // namespace testing
3450
3451 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
3452
3453 // Due to C++ preprocessor weirdness, we need double indirection to
3454 // concatenate two tokens when one of them is __LINE__. Writing
3455 //
3456 // foo ## __LINE__
3457 //
3458 // will result in the token foo__LINE__, instead of foo followed by
3459 // the current line number. For more details, see
3460 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
3461 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
3462 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
3463
3464 // Stringifies its argument.
3465 // Work around a bug in visual studio which doesn't accept code like this:
3466 //
3467 // #define GTEST_STRINGIFY_(name) #name
3468 // #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
3469 // MACRO(, x, y)
3470 //
3471 // Complaining about the argument to GTEST_STRINGIFY_ being empty.
3472 // This is allowed by the spec.
3473 #define GTEST_STRINGIFY_HELPER_(name, ...) #name
3474 #define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
3475
3476 namespace proto2 {
3477 class MessageLite;
3478 }
3479
3480 namespace testing {
3481
3482 // Forward declarations.
3483
3484 class AssertionResult; // Result of an assertion.
3485 class Message; // Represents a failure message.
3486 class Test; // Represents a test.
3487 class TestInfo; // Information about a test.
3488 class TestPartResult; // Result of a test part.
3489 class UnitTest; // A collection of test suites.
3490
3491 template <typename T>
3492 ::std::string PrintToString(const T& value);
3493
3494 namespace internal {
3495
3496 struct TraceInfo; // Information about a trace point.
3497 class TestInfoImpl; // Opaque implementation of TestInfo
3498 class UnitTestImpl; // Opaque implementation of UnitTest
3499
3500 // The text used in failure messages to indicate the start of the
3501 // stack trace.
3502 GTEST_API_ extern const char kStackTraceMarker[];
3503
3504 // An IgnoredValue object can be implicitly constructed from ANY value.
3505 class IgnoredValue {
3506 struct Sink {};
3507 public:
3508 // This constructor template allows any value to be implicitly
3509 // converted to IgnoredValue. The object has no data member and
3510 // doesn't try to remember anything about the argument. We
3511 // deliberately omit the 'explicit' keyword in order to allow the
3512 // conversion to be implicit.
3513 // Disable the conversion if T already has a magical conversion operator.
3514 // Otherwise we get ambiguity.
3515 template <typename T,
3516 typename std::enable_if<!std::is_convertible<T, Sink>::value,
3517 int>::type = 0>
3518 IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
3519 };
3520
3521 // Appends the user-supplied message to the Google-Test-generated message.
3522 GTEST_API_ std::string AppendUserMessage(
3523 const std::string& gtest_msg, const Message& user_msg);
3524
3525 #if GTEST_HAS_EXCEPTIONS
3526
3527 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
3528 /* an exported class was derived from a class that was not exported */)
3529
3530 // This exception is thrown by (and only by) a failed Google Test
3531 // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
3532 // are enabled). We derive it from std::runtime_error, which is for
3533 // errors presumably detectable only at run time. Since
3534 // std::runtime_error inherits from std::exception, many testing
3535 // frameworks know how to extract and print the message inside it.
3536 class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
3537 public:
3538 explicit GoogleTestFailureException(const TestPartResult& failure);
3539 };
3540
3541 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
3542
3543 #endif // GTEST_HAS_EXCEPTIONS
3544
3545 namespace edit_distance {
3546 // Returns the optimal edits to go from 'left' to 'right'.
3547 // All edits cost the same, with replace having lower priority than
3548 // add/remove.
3549 // Simple implementation of the Wagner-Fischer algorithm.
3550 // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
3551 enum EditType { kMatch, kAdd, kRemove, kReplace };
3552 GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
3553 const std::vector<size_t>& left, const std::vector<size_t>& right);
3554
3555 // Same as above, but the input is represented as strings.
3556 GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
3557 const std::vector<std::string>& left,
3558 const std::vector<std::string>& right);
3559
3560 // Create a diff of the input strings in Unified diff format.
3561 GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
3562 const std::vector<std::string>& right,
3563 size_t context = 2);
3564
3565 } // namespace edit_distance
3566
3567 // Calculate the diff between 'left' and 'right' and return it in unified diff
3568 // format.
3569 // If not null, stores in 'total_line_count' the total number of lines found
3570 // in left + right.
3571 GTEST_API_ std::string DiffStrings(const std::string& left,
3572 const std::string& right,
3573 size_t* total_line_count);
3574
3575 // Constructs and returns the message for an equality assertion
3576 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
3577 //
3578 // The first four parameters are the expressions used in the assertion
3579 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
3580 // where foo is 5 and bar is 6, we have:
3581 //
3582 // expected_expression: "foo"
3583 // actual_expression: "bar"
3584 // expected_value: "5"
3585 // actual_value: "6"
3586 //
3587 // The ignoring_case parameter is true if and only if the assertion is a
3588 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
3589 // be inserted into the message.
3590 GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
3591 const char* actual_expression,
3592 const std::string& expected_value,
3593 const std::string& actual_value,
3594 bool ignoring_case);
3595
3596 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
3597 GTEST_API_ std::string GetBoolAssertionFailureMessage(
3598 const AssertionResult& assertion_result,
3599 const char* expression_text,
3600 const char* actual_predicate_value,
3601 const char* expected_predicate_value);
3602
3603 // This template class represents an IEEE floating-point number
3604 // (either single-precision or double-precision, depending on the
3605 // template parameters).
3606 //
3607 // The purpose of this class is to do more sophisticated number
3608 // comparison. (Due to round-off error, etc, it's very unlikely that
3609 // two floating-points will be equal exactly. Hence a naive
3610 // comparison by the == operation often doesn't work.)
3611 //
3612 // Format of IEEE floating-point:
3613 //
3614 // The most-significant bit being the leftmost, an IEEE
3615 // floating-point looks like
3616 //
3617 // sign_bit exponent_bits fraction_bits
3618 //
3619 // Here, sign_bit is a single bit that designates the sign of the
3620 // number.
3621 //
3622 // For float, there are 8 exponent bits and 23 fraction bits.
3623 //
3624 // For double, there are 11 exponent bits and 52 fraction bits.
3625 //
3626 // More details can be found at
3627 // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
3628 //
3629 // Template parameter:
3630 //
3631 // RawType: the raw floating-point type (either float or double)
3632 template <typename RawType>
3633 class FloatingPoint {
3634 public:
3635 // Defines the unsigned integer type that has the same size as the
3636 // floating point number.
3637 typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
3638
3639 // Constants.
3640
3641 // # of bits in a number.
3642 static const size_t kBitCount = 8*sizeof(RawType);
3643
3644 // # of fraction bits in a number.
3645 static const size_t kFractionBitCount =
3646 std::numeric_limits<RawType>::digits - 1;
3647
3648 // # of exponent bits in a number.
3649 static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
3650
3651 // The mask for the sign bit.
3652 static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
3653
3654 // The mask for the fraction bits.
3655 static const Bits kFractionBitMask =
3656 ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
3657
3658 // The mask for the exponent bits.
3659 static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
3660
3661 // How many ULP's (Units in the Last Place) we want to tolerate when
3662 // comparing two numbers. The larger the value, the more error we
3663 // allow. A 0 value means that two numbers must be exactly the same
3664 // to be considered equal.
3665 //
3666 // The maximum error of a single floating-point operation is 0.5
3667 // units in the last place. On Intel CPU's, all floating-point
3668 // calculations are done with 80-bit precision, while double has 64
3669 // bits. Therefore, 4 should be enough for ordinary use.
3670 //
3671 // See the following article for more details on ULP:
3672 // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
3673 static const uint32_t kMaxUlps = 4;
3674
3675 // Constructs a FloatingPoint from a raw floating-point number.
3676 //
3677 // On an Intel CPU, passing a non-normalized NAN (Not a Number)
3678 // around may change its bits, although the new value is guaranteed
3679 // to be also a NAN. Therefore, don't expect this constructor to
3680 // preserve the bits in x when x is a NAN.
3681 explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
3682
3683 // Static methods
3684
3685 // Reinterprets a bit pattern as a floating-point number.
3686 //
3687 // This function is needed to test the AlmostEquals() method.
3688 static RawType ReinterpretBits(const Bits bits) {
3689 FloatingPoint fp(0);
3690 fp.u_.bits_ = bits;
3691 return fp.u_.value_;
3692 }
3693
3694 // Returns the floating-point number that represent positive infinity.
3695 static RawType Infinity() {
3696 return ReinterpretBits(kExponentBitMask);
3697 }
3698
3699 // Returns the maximum representable finite floating-point number.
3700 static RawType Max();
3701
3702 // Non-static methods
3703
3704 // Returns the bits that represents this number.
3705 const Bits &bits() const { return u_.bits_; }
3706
3707 // Returns the exponent bits of this number.
3708 Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
3709
3710 // Returns the fraction bits of this number.
3711 Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
3712
3713 // Returns the sign bit of this number.
3714 Bits sign_bit() const { return kSignBitMask & u_.bits_; }
3715
3716 // Returns true if and only if this is NAN (not a number).
3717 bool is_nan() const {
3718 // It's a NAN if the exponent bits are all ones and the fraction
3719 // bits are not entirely zeros.
3720 return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
3721 }
3722
3723 // Returns true if and only if this number is at most kMaxUlps ULP's away
3724 // from rhs. In particular, this function:
3725 //
3726 // - returns false if either number is (or both are) NAN.
3727 // - treats really large numbers as almost equal to infinity.
3728 // - thinks +0.0 and -0.0 are 0 DLP's apart.
3729 bool AlmostEquals(const FloatingPoint& rhs) const {
3730 // The IEEE standard says that any comparison operation involving
3731 // a NAN must return false.
3732 if (is_nan() || rhs.is_nan()) return false;
3733
3734 return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
3735 <= kMaxUlps;
3736 }
3737
3738 private:
3739 // The data type used to store the actual floating-point number.
3740 union FloatingPointUnion {
3741 RawType value_; // The raw floating-point number.
3742 Bits bits_; // The bits that represent the number.
3743 };
3744
3745 // Converts an integer from the sign-and-magnitude representation to
3746 // the biased representation. More precisely, let N be 2 to the
3747 // power of (kBitCount - 1), an integer x is represented by the
3748 // unsigned number x + N.
3749 //
3750 // For instance,
3751 //
3752 // -N + 1 (the most negative number representable using
3753 // sign-and-magnitude) is represented by 1;
3754 // 0 is represented by N; and
3755 // N - 1 (the biggest number representable using
3756 // sign-and-magnitude) is represented by 2N - 1.
3757 //
3758 // Read http://en.wikipedia.org/wiki/Signed_number_representations
3759 // for more details on signed number representations.
3760 static Bits SignAndMagnitudeToBiased(const Bits &sam) {
3761 if (kSignBitMask & sam) {
3762 // sam represents a negative number.
3763 return ~sam + 1;
3764 } else {
3765 // sam represents a positive number.
3766 return kSignBitMask | sam;
3767 }
3768 }
3769
3770 // Given two numbers in the sign-and-magnitude representation,
3771 // returns the distance between them as an unsigned number.
3772 static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
3773 const Bits &sam2) {
3774 const Bits biased1 = SignAndMagnitudeToBiased(sam1);
3775 const Bits biased2 = SignAndMagnitudeToBiased(sam2);
3776 return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
3777 }
3778
3779 FloatingPointUnion u_;
3780 };
3781
3782 // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
3783 // macro defined by <windows.h>.
3784 template <>
3785 inline float FloatingPoint<float>::Max() { return FLT_MAX; }
3786 template <>
3787 inline double FloatingPoint<double>::Max() { return DBL_MAX; }
3788
3789 // Typedefs the instances of the FloatingPoint template class that we
3790 // care to use.
3791 typedef FloatingPoint<float> Float;
3792 typedef FloatingPoint<double> Double;
3793
3794 // In order to catch the mistake of putting tests that use different
3795 // test fixture classes in the same test suite, we need to assign
3796 // unique IDs to fixture classes and compare them. The TypeId type is
3797 // used to hold such IDs. The user should treat TypeId as an opaque
3798 // type: the only operation allowed on TypeId values is to compare
3799 // them for equality using the == operator.
3800 typedef const void* TypeId;
3801
3802 template <typename T>
3803 class TypeIdHelper {
3804 public:
3805 // dummy_ must not have a const type. Otherwise an overly eager
3806 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
3807 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
3808 static bool dummy_;
3809 };
3810
3811 template <typename T>
3812 bool TypeIdHelper<T>::dummy_ = false;
3813
3814 // GetTypeId<T>() returns the ID of type T. Different values will be
3815 // returned for different types. Calling the function twice with the
3816 // same type argument is guaranteed to return the same ID.
3817 template <typename T>
3818 TypeId GetTypeId() {
3819 // The compiler is required to allocate a different
3820 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
3821 // the template. Therefore, the address of dummy_ is guaranteed to
3822 // be unique.
3823 return &(TypeIdHelper<T>::dummy_);
3824 }
3825
3826 // Returns the type ID of ::testing::Test. Always call this instead
3827 // of GetTypeId< ::testing::Test>() to get the type ID of
3828 // ::testing::Test, as the latter may give the wrong result due to a
3829 // suspected linker bug when compiling Google Test as a Mac OS X
3830 // framework.
3831 GTEST_API_ TypeId GetTestTypeId();
3832
3833 // Defines the abstract factory interface that creates instances
3834 // of a Test object.
3835 class TestFactoryBase {
3836 public:
3837 virtual ~TestFactoryBase() {}
3838
3839 // Creates a test instance to run. The instance is both created and destroyed
3840 // within TestInfoImpl::Run()
3841 virtual Test* CreateTest() = 0;
3842
3843 protected:
3844 TestFactoryBase() {}
3845
3846 private:
3847 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
3848 };
3849
3850 // This class provides implementation of TeastFactoryBase interface.
3851 // It is used in TEST and TEST_F macros.
3852 template <class TestClass>
3853 class TestFactoryImpl : public TestFactoryBase {
3854 public:
3855 Test* CreateTest() override { return new TestClass; }
3856 };
3857
3858 #if GTEST_OS_WINDOWS
3859
3860 // Predicate-formatters for implementing the HRESULT checking macros
3861 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
3862 // We pass a long instead of HRESULT to avoid causing an
3863 // include dependency for the HRESULT type.
3864 GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
3865 long hr); // NOLINT
3866 GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
3867 long hr); // NOLINT
3868
3869 #endif // GTEST_OS_WINDOWS
3870
3871 // Types of SetUpTestSuite() and TearDownTestSuite() functions.
3872 using SetUpTestSuiteFunc = void (*)();
3873 using TearDownTestSuiteFunc = void (*)();
3874
3875 struct CodeLocation {
3876 CodeLocation(const std::string& a_file, int a_line)
3877 : file(a_file), line(a_line) {}
3878
3879 std::string file;
3880 int line;
3881 };
3882
3883 // Helper to identify which setup function for TestCase / TestSuite to call.
3884 // Only one function is allowed, either TestCase or TestSute but not both.
3885
3886 // Utility functions to help SuiteApiResolver
3887 using SetUpTearDownSuiteFuncType = void (*)();
3888
3889 inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
3890 SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {
3891 return a == def ? nullptr : a;
3892 }
3893
3894 template <typename T>
3895 // Note that SuiteApiResolver inherits from T because
3896 // SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
3897 // SuiteApiResolver can access them.
3898 struct SuiteApiResolver : T {
3899 // testing::Test is only forward declared at this point. So we make it a
3900 // dependend class for the compiler to be OK with it.
3901 using Test =
3902 typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
3903
3904 static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
3905 int line_num) {
3906 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3907 SetUpTearDownSuiteFuncType test_case_fp =
3908 GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
3909 SetUpTearDownSuiteFuncType test_suite_fp =
3910 GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);
3911
3912 GTEST_CHECK_(!test_case_fp || !test_suite_fp)
3913 << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
3914 "make sure there is only one present at "
3915 << filename << ":" << line_num;
3916
3917 return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
3918 #else
3919 (void)(filename);
3920 (void)(line_num);
3921 return &T::SetUpTestSuite;
3922 #endif
3923 }
3924
3925 static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
3926 int line_num) {
3927 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3928 SetUpTearDownSuiteFuncType test_case_fp =
3929 GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
3930 SetUpTearDownSuiteFuncType test_suite_fp =
3931 GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);
3932
3933 GTEST_CHECK_(!test_case_fp || !test_suite_fp)
3934 << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
3935 " please make sure there is only one present at"
3936 << filename << ":" << line_num;
3937
3938 return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
3939 #else
3940 (void)(filename);
3941 (void)(line_num);
3942 return &T::TearDownTestSuite;
3943 #endif
3944 }
3945 };
3946
3947 // Creates a new TestInfo object and registers it with Google Test;
3948 // returns the created object.
3949 //
3950 // Arguments:
3951 //
3952 // test_suite_name: name of the test suite
3953 // name: name of the test
3954 // type_param: the name of the test's type parameter, or NULL if
3955 // this is not a typed or a type-parameterized test.
3956 // value_param: text representation of the test's value parameter,
3957 // or NULL if this is not a type-parameterized test.
3958 // code_location: code location where the test is defined
3959 // fixture_class_id: ID of the test fixture class
3960 // set_up_tc: pointer to the function that sets up the test suite
3961 // tear_down_tc: pointer to the function that tears down the test suite
3962 // factory: pointer to the factory that creates a test object.
3963 // The newly created TestInfo instance will assume
3964 // ownership of the factory object.
3965 GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
3966 const char* test_suite_name, const char* name, const char* type_param,
3967 const char* value_param, CodeLocation code_location,
3968 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
3969 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
3970
3971 // If *pstr starts with the given prefix, modifies *pstr to be right
3972 // past the prefix and returns true; otherwise leaves *pstr unchanged
3973 // and returns false. None of pstr, *pstr, and prefix can be NULL.
3974 GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
3975
3976 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
3977 /* class A needs to have dll-interface to be used by clients of class B */)
3978
3979 // State of the definition of a type-parameterized test suite.
3980 class GTEST_API_ TypedTestSuitePState {
3981 public:
3982 TypedTestSuitePState() : registered_(false) {}
3983
3984 // Adds the given test name to defined_test_names_ and return true
3985 // if the test suite hasn't been registered; otherwise aborts the
3986 // program.
3987 bool AddTestName(const char* file, int line, const char* case_name,
3988 const char* test_name) {
3989 if (registered_) {
3990 fprintf(stderr,
3991 "%s Test %s must be defined before "
3992 "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
3993 FormatFileLocation(file, line).c_str(), test_name, case_name);
3994 fflush(stderr);
3995 posix::Abort();
3996 }
3997 registered_tests_.insert(
3998 ::std::make_pair(test_name, CodeLocation(file, line)));
3999 return true;
4000 }
4001
4002 bool TestExists(const std::string& test_name) const {
4003 return registered_tests_.count(test_name) > 0;
4004 }
4005
4006 const CodeLocation& GetCodeLocation(const std::string& test_name) const {
4007 RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
4008 GTEST_CHECK_(it != registered_tests_.end());
4009 return it->second;
4010 }
4011
4012 // Verifies that registered_tests match the test names in
4013 // defined_test_names_; returns registered_tests if successful, or
4014 // aborts the program otherwise.
4015 const char* VerifyRegisteredTestNames(const char* test_suite_name,
4016 const char* file, int line,
4017 const char* registered_tests);
4018
4019 private:
4020 typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
4021
4022 bool registered_;
4023 RegisteredTestsMap registered_tests_;
4024 };
4025
4026 // Legacy API is deprecated but still available
4027 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4028 using TypedTestCasePState = TypedTestSuitePState;
4029 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4030
4031 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
4032
4033 // Skips to the first non-space char after the first comma in 'str';
4034 // returns NULL if no comma is found in 'str'.
4035 inline const char* SkipComma(const char* str) {
4036 const char* comma = strchr(str, ',');
4037 if (comma == nullptr) {
4038 return nullptr;
4039 }
4040 while (IsSpace(*(++comma))) {}
4041 return comma;
4042 }
4043
4044 // Returns the prefix of 'str' before the first comma in it; returns
4045 // the entire string if it contains no comma.
4046 inline std::string GetPrefixUntilComma(const char* str) {
4047 const char* comma = strchr(str, ',');
4048 return comma == nullptr ? str : std::string(str, comma);
4049 }
4050
4051 // Splits a given string on a given delimiter, populating a given
4052 // vector with the fields.
4053 void SplitString(const ::std::string& str, char delimiter,
4054 ::std::vector< ::std::string>* dest);
4055
4056 // The default argument to the template below for the case when the user does
4057 // not provide a name generator.
4058 struct DefaultNameGenerator {
4059 template <typename T>
4060 static std::string GetName(int i) {
4061 return StreamableToString(i);
4062 }
4063 };
4064
4065 template <typename Provided = DefaultNameGenerator>
4066 struct NameGeneratorSelector {
4067 typedef Provided type;
4068 };
4069
4070 template <typename NameGenerator>
4071 void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}
4072
4073 template <typename NameGenerator, typename Types>
4074 void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
4075 result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
4076 GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
4077 i + 1);
4078 }
4079
4080 template <typename NameGenerator, typename Types>
4081 std::vector<std::string> GenerateNames() {
4082 std::vector<std::string> result;
4083 GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
4084 return result;
4085 }
4086
4087 // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
4088 // registers a list of type-parameterized tests with Google Test. The
4089 // return value is insignificant - we just need to return something
4090 // such that we can call this function in a namespace scope.
4091 //
4092 // Implementation note: The GTEST_TEMPLATE_ macro declares a template
4093 // template parameter. It's defined in gtest-type-util.h.
4094 template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
4095 class TypeParameterizedTest {
4096 public:
4097 // 'index' is the index of the test in the type list 'Types'
4098 // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
4099 // Types). Valid values for 'index' are [0, N - 1] where N is the
4100 // length of Types.
4101 static bool Register(const char* prefix, const CodeLocation& code_location,
4102 const char* case_name, const char* test_names, int index,
4103 const std::vector<std::string>& type_names =
4104 GenerateNames<DefaultNameGenerator, Types>()) {
4105 typedef typename Types::Head Type;
4106 typedef Fixture<Type> FixtureClass;
4107 typedef typename GTEST_BIND_(TestSel, Type) TestClass;
4108
4109 // First, registers the first type-parameterized test in the type
4110 // list.
4111 MakeAndRegisterTestInfo(
4112 (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
4113 "/" + type_names[static_cast<size_t>(index)])
4114 .c_str(),
4115 StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
4116 GetTypeName<Type>().c_str(),
4117 nullptr, // No value parameter.
4118 code_location, GetTypeId<FixtureClass>(),
4119 SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(
4120 code_location.file.c_str(), code_location.line),
4121 SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(
4122 code_location.file.c_str(), code_location.line),
4123 new TestFactoryImpl<TestClass>);
4124
4125 // Next, recurses (at compile time) with the tail of the type list.
4126 return TypeParameterizedTest<Fixture, TestSel,
4127 typename Types::Tail>::Register(prefix,
4128 code_location,
4129 case_name,
4130 test_names,
4131 index + 1,
4132 type_names);
4133 }
4134 };
4135
4136 // The base case for the compile time recursion.
4137 template <GTEST_TEMPLATE_ Fixture, class TestSel>
4138 class TypeParameterizedTest<Fixture, TestSel, internal::None> {
4139 public:
4140 static bool Register(const char* /*prefix*/, const CodeLocation&,
4141 const char* /*case_name*/, const char* /*test_names*/,
4142 int /*index*/,
4143 const std::vector<std::string>& =
4144 std::vector<std::string>() /*type_names*/) {
4145 return true;
4146 }
4147 };
4148
4149 GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
4150 CodeLocation code_location);
4151 GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
4152 const char* case_name);
4153
4154 // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
4155 // registers *all combinations* of 'Tests' and 'Types' with Google
4156 // Test. The return value is insignificant - we just need to return
4157 // something such that we can call this function in a namespace scope.
4158 template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
4159 class TypeParameterizedTestSuite {
4160 public:
4161 static bool Register(const char* prefix, CodeLocation code_location,
4162 const TypedTestSuitePState* state, const char* case_name,
4163 const char* test_names,
4164 const std::vector<std::string>& type_names =
4165 GenerateNames<DefaultNameGenerator, Types>()) {
4166 RegisterTypeParameterizedTestSuiteInstantiation(case_name);
4167 std::string test_name = StripTrailingSpaces(
4168 GetPrefixUntilComma(test_names));
4169 if (!state->TestExists(test_name)) {
4170 fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
4171 case_name, test_name.c_str(),
4172 FormatFileLocation(code_location.file.c_str(),
4173 code_location.line).c_str());
4174 fflush(stderr);
4175 posix::Abort();
4176 }
4177 const CodeLocation& test_location = state->GetCodeLocation(test_name);
4178
4179 typedef typename Tests::Head Head;
4180
4181 // First, register the first test in 'Test' for each type in 'Types'.
4182 TypeParameterizedTest<Fixture, Head, Types>::Register(
4183 prefix, test_location, case_name, test_names, 0, type_names);
4184
4185 // Next, recurses (at compile time) with the tail of the test list.
4186 return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
4187 Types>::Register(prefix, code_location,
4188 state, case_name,
4189 SkipComma(test_names),
4190 type_names);
4191 }
4192 };
4193
4194 // The base case for the compile time recursion.
4195 template <GTEST_TEMPLATE_ Fixture, typename Types>
4196 class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
4197 public:
4198 static bool Register(const char* /*prefix*/, const CodeLocation&,
4199 const TypedTestSuitePState* /*state*/,
4200 const char* /*case_name*/, const char* /*test_names*/,
4201 const std::vector<std::string>& =
4202 std::vector<std::string>() /*type_names*/) {
4203 return true;
4204 }
4205 };
4206
4207 // Returns the current OS stack trace as an std::string.
4208 //
4209 // The maximum number of stack frames to be included is specified by
4210 // the gtest_stack_trace_depth flag. The skip_count parameter
4211 // specifies the number of top frames to be skipped, which doesn't
4212 // count against the number of frames to be included.
4213 //
4214 // For example, if Foo() calls Bar(), which in turn calls
4215 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4216 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4217 GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
4218 UnitTest* unit_test, int skip_count);
4219
4220 // Helpers for suppressing warnings on unreachable code or constant
4221 // condition.
4222
4223 // Always returns true.
4224 GTEST_API_ bool AlwaysTrue();
4225
4226 // Always returns false.
4227 inline bool AlwaysFalse() { return !AlwaysTrue(); }
4228
4229 // Helper for suppressing false warning from Clang on a const char*
4230 // variable declared in a conditional expression always being NULL in
4231 // the else branch.
4232 struct GTEST_API_ ConstCharPtr {
4233 ConstCharPtr(const char* str) : value(str) {}
4234 operator bool() const { return true; }
4235 const char* value;
4236 };
4237
4238 // Helper for declaring std::string within 'if' statement
4239 // in pre C++17 build environment.
4240 struct TrueWithString {
4241 TrueWithString() = default;
4242 explicit TrueWithString(const char* str) : value(str) {}
4243 explicit TrueWithString(const std::string& str) : value(str) {}
4244 explicit operator bool() const { return true; }
4245 std::string value;
4246 };
4247
4248 // A simple Linear Congruential Generator for generating random
4249 // numbers with a uniform distribution. Unlike rand() and srand(), it
4250 // doesn't use global state (and therefore can't interfere with user
4251 // code). Unlike rand_r(), it's portable. An LCG isn't very random,
4252 // but it's good enough for our purposes.
4253 class GTEST_API_ Random {
4254 public:
4255 static const uint32_t kMaxRange = 1u << 31;
4256
4257 explicit Random(uint32_t seed) : state_(seed) {}
4258
4259 void Reseed(uint32_t seed) { state_ = seed; }
4260
4261 // Generates a random number from [0, range). Crashes if 'range' is
4262 // 0 or greater than kMaxRange.
4263 uint32_t Generate(uint32_t range);
4264
4265 private:
4266 uint32_t state_;
4267 GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
4268 };
4269
4270 // Turns const U&, U&, const U, and U all into U.
4271 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
4272 typename std::remove_const<typename std::remove_reference<T>::type>::type
4273
4274 // HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
4275 // that's true if and only if T has methods DebugString() and ShortDebugString()
4276 // that return std::string.
4277 template <typename T>
4278 class HasDebugStringAndShortDebugString {
4279 private:
4280 template <typename C>
4281 static auto CheckDebugString(C*) -> typename std::is_same<
4282 std::string, decltype(std::declval<const C>().DebugString())>::type;
4283 template <typename>
4284 static std::false_type CheckDebugString(...);
4285
4286 template <typename C>
4287 static auto CheckShortDebugString(C*) -> typename std::is_same<
4288 std::string, decltype(std::declval<const C>().ShortDebugString())>::type;
4289 template <typename>
4290 static std::false_type CheckShortDebugString(...);
4291
4292 using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));
4293 using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));
4294
4295 public:
4296 static constexpr bool value =
4297 HasDebugStringType::value && HasShortDebugStringType::value;
4298 };
4299
4300 template <typename T>
4301 constexpr bool HasDebugStringAndShortDebugString<T>::value;
4302
4303 // When the compiler sees expression IsContainerTest<C>(0), if C is an
4304 // STL-style container class, the first overload of IsContainerTest
4305 // will be viable (since both C::iterator* and C::const_iterator* are
4306 // valid types and NULL can be implicitly converted to them). It will
4307 // be picked over the second overload as 'int' is a perfect match for
4308 // the type of argument 0. If C::iterator or C::const_iterator is not
4309 // a valid type, the first overload is not viable, and the second
4310 // overload will be picked. Therefore, we can determine whether C is
4311 // a container class by checking the type of IsContainerTest<C>(0).
4312 // The value of the expression is insignificant.
4313 //
4314 // In C++11 mode we check the existence of a const_iterator and that an
4315 // iterator is properly implemented for the container.
4316 //
4317 // For pre-C++11 that we look for both C::iterator and C::const_iterator.
4318 // The reason is that C++ injects the name of a class as a member of the
4319 // class itself (e.g. you can refer to class iterator as either
4320 // 'iterator' or 'iterator::iterator'). If we look for C::iterator
4321 // only, for example, we would mistakenly think that a class named
4322 // iterator is an STL container.
4323 //
4324 // Also note that the simpler approach of overloading
4325 // IsContainerTest(typename C::const_iterator*) and
4326 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
4327 typedef int IsContainer;
4328 template <class C,
4329 class Iterator = decltype(::std::declval<const C&>().begin()),
4330 class = decltype(::std::declval<const C&>().end()),
4331 class = decltype(++::std::declval<Iterator&>()),
4332 class = decltype(*::std::declval<Iterator>()),
4333 class = typename C::const_iterator>
4334 IsContainer IsContainerTest(int /* dummy */) {
4335 return 0;
4336 }
4337
4338 typedef char IsNotContainer;
4339 template <class C>
4340 IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
4341
4342 // Trait to detect whether a type T is a hash table.
4343 // The heuristic used is that the type contains an inner type `hasher` and does
4344 // not contain an inner type `reverse_iterator`.
4345 // If the container is iterable in reverse, then order might actually matter.
4346 template <typename T>
4347 struct IsHashTable {
4348 private:
4349 template <typename U>
4350 static char test(typename U::hasher*, typename U::reverse_iterator*);
4351 template <typename U>
4352 static int test(typename U::hasher*, ...);
4353 template <typename U>
4354 static char test(...);
4355
4356 public:
4357 static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);
4358 };
4359
4360 template <typename T>
4361 const bool IsHashTable<T>::value;
4362
4363 template <typename C,
4364 bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>
4365 struct IsRecursiveContainerImpl;
4366
4367 template <typename C>
4368 struct IsRecursiveContainerImpl<C, false> : public std::false_type {};
4369
4370 // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
4371 // obey the same inconsistencies as the IsContainerTest, namely check if
4372 // something is a container is relying on only const_iterator in C++11 and
4373 // is relying on both const_iterator and iterator otherwise
4374 template <typename C>
4375 struct IsRecursiveContainerImpl<C, true> {
4376 using value_type = decltype(*std::declval<typename C::const_iterator>());
4377 using type =
4378 std::is_same<typename std::remove_const<
4379 typename std::remove_reference<value_type>::type>::type,
4380 C>;
4381 };
4382
4383 // IsRecursiveContainer<Type> is a unary compile-time predicate that
4384 // evaluates whether C is a recursive container type. A recursive container
4385 // type is a container type whose value_type is equal to the container type
4386 // itself. An example for a recursive container type is
4387 // boost::filesystem::path, whose iterator has a value_type that is equal to
4388 // boost::filesystem::path.
4389 template <typename C>
4390 struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};
4391
4392 // Utilities for native arrays.
4393
4394 // ArrayEq() compares two k-dimensional native arrays using the
4395 // elements' operator==, where k can be any integer >= 0. When k is
4396 // 0, ArrayEq() degenerates into comparing a single pair of values.
4397
4398 template <typename T, typename U>
4399 bool ArrayEq(const T* lhs, size_t size, const U* rhs);
4400
4401 // This generic version is used when k is 0.
4402 template <typename T, typename U>
4403 inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
4404
4405 // This overload is used when k >= 1.
4406 template <typename T, typename U, size_t N>
4407 inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
4408 return internal::ArrayEq(lhs, N, rhs);
4409 }
4410
4411 // This helper reduces code bloat. If we instead put its logic inside
4412 // the previous ArrayEq() function, arrays with different sizes would
4413 // lead to different copies of the template code.
4414 template <typename T, typename U>
4415 bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
4416 for (size_t i = 0; i != size; i++) {
4417 if (!internal::ArrayEq(lhs[i], rhs[i]))
4418 return false;
4419 }
4420 return true;
4421 }
4422
4423 // Finds the first element in the iterator range [begin, end) that
4424 // equals elem. Element may be a native array type itself.
4425 template <typename Iter, typename Element>
4426 Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
4427 for (Iter it = begin; it != end; ++it) {
4428 if (internal::ArrayEq(*it, elem))
4429 return it;
4430 }
4431 return end;
4432 }
4433
4434 // CopyArray() copies a k-dimensional native array using the elements'
4435 // operator=, where k can be any integer >= 0. When k is 0,
4436 // CopyArray() degenerates into copying a single value.
4437
4438 template <typename T, typename U>
4439 void CopyArray(const T* from, size_t size, U* to);
4440
4441 // This generic version is used when k is 0.
4442 template <typename T, typename U>
4443 inline void CopyArray(const T& from, U* to) { *to = from; }
4444
4445 // This overload is used when k >= 1.
4446 template <typename T, typename U, size_t N>
4447 inline void CopyArray(const T(&from)[N], U(*to)[N]) {
4448 internal::CopyArray(from, N, *to);
4449 }
4450
4451 // This helper reduces code bloat. If we instead put its logic inside
4452 // the previous CopyArray() function, arrays with different sizes
4453 // would lead to different copies of the template code.
4454 template <typename T, typename U>
4455 void CopyArray(const T* from, size_t size, U* to) {
4456 for (size_t i = 0; i != size; i++) {
4457 internal::CopyArray(from[i], to + i);
4458 }
4459 }
4460
4461 // The relation between an NativeArray object (see below) and the
4462 // native array it represents.
4463 // We use 2 different structs to allow non-copyable types to be used, as long
4464 // as RelationToSourceReference() is passed.
4465 struct RelationToSourceReference {};
4466 struct RelationToSourceCopy {};
4467
4468 // Adapts a native array to a read-only STL-style container. Instead
4469 // of the complete STL container concept, this adaptor only implements
4470 // members useful for Google Mock's container matchers. New members
4471 // should be added as needed. To simplify the implementation, we only
4472 // support Element being a raw type (i.e. having no top-level const or
4473 // reference modifier). It's the client's responsibility to satisfy
4474 // this requirement. Element can be an array type itself (hence
4475 // multi-dimensional arrays are supported).
4476 template <typename Element>
4477 class NativeArray {
4478 public:
4479 // STL-style container typedefs.
4480 typedef Element value_type;
4481 typedef Element* iterator;
4482 typedef const Element* const_iterator;
4483
4484 // Constructs from a native array. References the source.
4485 NativeArray(const Element* array, size_t count, RelationToSourceReference) {
4486 InitRef(array, count);
4487 }
4488
4489 // Constructs from a native array. Copies the source.
4490 NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
4491 InitCopy(array, count);
4492 }
4493
4494 // Copy constructor.
4495 NativeArray(const NativeArray& rhs) {
4496 (this->*rhs.clone_)(rhs.array_, rhs.size_);
4497 }
4498
4499 ~NativeArray() {
4500 if (clone_ != &NativeArray::InitRef)
4501 delete[] array_;
4502 }
4503
4504 // STL-style container methods.
4505 size_t size() const { return size_; }
4506 const_iterator begin() const { return array_; }
4507 const_iterator end() const { return array_ + size_; }
4508 bool operator==(const NativeArray& rhs) const {
4509 return size() == rhs.size() &&
4510 ArrayEq(begin(), size(), rhs.begin());
4511 }
4512
4513 private:
4514 static_assert(!std::is_const<Element>::value, "Type must not be const");
4515 static_assert(!std::is_reference<Element>::value,
4516 "Type must not be a reference");
4517
4518 // Initializes this object with a copy of the input.
4519 void InitCopy(const Element* array, size_t a_size) {
4520 Element* const copy = new Element[a_size];
4521 CopyArray(array, a_size, copy);
4522 array_ = copy;
4523 size_ = a_size;
4524 clone_ = &NativeArray::InitCopy;
4525 }
4526
4527 // Initializes this object with a reference of the input.
4528 void InitRef(const Element* array, size_t a_size) {
4529 array_ = array;
4530 size_ = a_size;
4531 clone_ = &NativeArray::InitRef;
4532 }
4533
4534 const Element* array_;
4535 size_t size_;
4536 void (NativeArray::*clone_)(const Element*, size_t);
4537 };
4538
4539 // Backport of std::index_sequence.
4540 template <size_t... Is>
4541 struct IndexSequence {
4542 using type = IndexSequence;
4543 };
4544
4545 // Double the IndexSequence, and one if plus_one is true.
4546 template <bool plus_one, typename T, size_t sizeofT>
4547 struct DoubleSequence;
4548 template <size_t... I, size_t sizeofT>
4549 struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
4550 using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
4551 };
4552 template <size_t... I, size_t sizeofT>
4553 struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
4554 using type = IndexSequence<I..., (sizeofT + I)...>;
4555 };
4556
4557 // Backport of std::make_index_sequence.
4558 // It uses O(ln(N)) instantiation depth.
4559 template <size_t N>
4560 struct MakeIndexSequenceImpl
4561 : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,
4562 N / 2>::type {};
4563
4564 template <>
4565 struct MakeIndexSequenceImpl<0> : IndexSequence<> {};
4566
4567 template <size_t N>
4568 using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;
4569
4570 template <typename... T>
4571 using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;
4572
4573 template <size_t>
4574 struct Ignore {
4575 Ignore(...); // NOLINT
4576 };
4577
4578 template <typename>
4579 struct ElemFromListImpl;
4580 template <size_t... I>
4581 struct ElemFromListImpl<IndexSequence<I...>> {
4582 // We make Ignore a template to solve a problem with MSVC.
4583 // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but
4584 // MSVC doesn't understand how to deal with that pack expansion.
4585 // Use `0 * I` to have a single instantiation of Ignore.
4586 template <typename R>
4587 static R Apply(Ignore<0 * I>..., R (*)(), ...);
4588 };
4589
4590 template <size_t N, typename... T>
4591 struct ElemFromList {
4592 using type =
4593 decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply(
4594 static_cast<T (*)()>(nullptr)...));
4595 };
4596
4597 struct FlatTupleConstructTag {};
4598
4599 template <typename... T>
4600 class FlatTuple;
4601
4602 template <typename Derived, size_t I>
4603 struct FlatTupleElemBase;
4604
4605 template <typename... T, size_t I>
4606 struct FlatTupleElemBase<FlatTuple<T...>, I> {
4607 using value_type = typename ElemFromList<I, T...>::type;
4608 FlatTupleElemBase() = default;
4609 template <typename Arg>
4610 explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)
4611 : value(std::forward<Arg>(t)) {}
4612 value_type value;
4613 };
4614
4615 template <typename Derived, typename Idx>
4616 struct FlatTupleBase;
4617
4618 template <size_t... Idx, typename... T>
4619 struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
4620 : FlatTupleElemBase<FlatTuple<T...>, Idx>... {
4621 using Indices = IndexSequence<Idx...>;
4622 FlatTupleBase() = default;
4623 template <typename... Args>
4624 explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)
4625 : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},
4626 std::forward<Args>(args))... {}
4627
4628 template <size_t I>
4629 const typename ElemFromList<I, T...>::type& Get() const {
4630 return FlatTupleElemBase<FlatTuple<T...>, I>::value;
4631 }
4632
4633 template <size_t I>
4634 typename ElemFromList<I, T...>::type& Get() {
4635 return FlatTupleElemBase<FlatTuple<T...>, I>::value;
4636 }
4637
4638 template <typename F>
4639 auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
4640 return std::forward<F>(f)(Get<Idx>()...);
4641 }
4642
4643 template <typename F>
4644 auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
4645 return std::forward<F>(f)(Get<Idx>()...);
4646 }
4647 };
4648
4649 // Analog to std::tuple but with different tradeoffs.
4650 // This class minimizes the template instantiation depth, thus allowing more
4651 // elements than std::tuple would. std::tuple has been seen to require an
4652 // instantiation depth of more than 10x the number of elements in some
4653 // implementations.
4654 // FlatTuple and ElemFromList are not recursive and have a fixed depth
4655 // regardless of T...
4656 // MakeIndexSequence, on the other hand, it is recursive but with an
4657 // instantiation depth of O(ln(N)).
4658 template <typename... T>
4659 class FlatTuple
4660 : private FlatTupleBase<FlatTuple<T...>,
4661 typename MakeIndexSequence<sizeof...(T)>::type> {
4662 using Indices = typename FlatTupleBase<
4663 FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices;
4664
4665 public:
4666 FlatTuple() = default;
4667 template <typename... Args>
4668 explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)
4669 : FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}
4670
4671 using FlatTuple::FlatTupleBase::Apply;
4672 using FlatTuple::FlatTupleBase::Get;
4673 };
4674
4675 // Utility functions to be called with static_assert to induce deprecation
4676 // warnings.
4677 GTEST_INTERNAL_DEPRECATED(
4678 "INSTANTIATE_TEST_CASE_P is deprecated, please use "
4679 "INSTANTIATE_TEST_SUITE_P")
4680 constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
4681
4682 GTEST_INTERNAL_DEPRECATED(
4683 "TYPED_TEST_CASE_P is deprecated, please use "
4684 "TYPED_TEST_SUITE_P")
4685 constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
4686
4687 GTEST_INTERNAL_DEPRECATED(
4688 "TYPED_TEST_CASE is deprecated, please use "
4689 "TYPED_TEST_SUITE")
4690 constexpr bool TypedTestCaseIsDeprecated() { return true; }
4691
4692 GTEST_INTERNAL_DEPRECATED(
4693 "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
4694 "REGISTER_TYPED_TEST_SUITE_P")
4695 constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
4696
4697 GTEST_INTERNAL_DEPRECATED(
4698 "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
4699 "INSTANTIATE_TYPED_TEST_SUITE_P")
4700 constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
4701
4702 } // namespace internal
4703 } // namespace testing
4704
4705 namespace std {
4706 // Some standard library implementations use `struct tuple_size` and some use
4707 // `class tuple_size`. Clang warns about the mismatch.
4708 // https://reviews.llvm.org/D55466
4709 #ifdef __clang__
4710 #pragma clang diagnostic push
4711 #pragma clang diagnostic ignored "-Wmismatched-tags"
4712 #endif
4713 template <typename... Ts>
4714 struct tuple_size<testing::internal::FlatTuple<Ts...>>
4715 : std::integral_constant<size_t, sizeof...(Ts)> {};
4716 #ifdef __clang__
4717 #pragma clang diagnostic pop
4718 #endif
4719 } // namespace std
4720
4721 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
4722 ::testing::internal::AssertHelper(result_type, file, line, message) \
4723 = ::testing::Message()
4724
4725 #define GTEST_MESSAGE_(message, result_type) \
4726 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
4727
4728 #define GTEST_FATAL_FAILURE_(message) \
4729 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
4730
4731 #define GTEST_NONFATAL_FAILURE_(message) \
4732 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
4733
4734 #define GTEST_SUCCESS_(message) \
4735 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
4736
4737 #define GTEST_SKIP_(message) \
4738 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
4739
4740 // Suppress MSVC warning 4072 (unreachable code) for the code following
4741 // statement if it returns or throws (or doesn't return or throw in some
4742 // situations).
4743 // NOTE: The "else" is important to keep this expansion to prevent a top-level
4744 // "else" from attaching to our "if".
4745 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
4746 if (::testing::internal::AlwaysTrue()) { \
4747 statement; \
4748 } else /* NOLINT */ \
4749 static_assert(true, "") // User must have a semicolon after expansion.
4750
4751 #if GTEST_HAS_EXCEPTIONS
4752
4753 namespace testing {
4754 namespace internal {
4755
4756 class NeverThrown {
4757 public:
4758 const char* what() const noexcept {
4759 return "this exception should never be thrown";
4760 }
4761 };
4762
4763 } // namespace internal
4764 } // namespace testing
4765
4766 #if GTEST_HAS_RTTI
4767
4768 #define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
4769
4770 #else // GTEST_HAS_RTTI
4771
4772 #define GTEST_EXCEPTION_TYPE_(e) \
4773 std::string { "an std::exception-derived error" }
4774
4775 #endif // GTEST_HAS_RTTI
4776
4777 #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
4778 catch (typename std::conditional< \
4779 std::is_same<typename std::remove_cv<typename std::remove_reference< \
4780 expected_exception>::type>::type, \
4781 std::exception>::value, \
4782 const ::testing::internal::NeverThrown&, const std::exception&>::type \
4783 e) { \
4784 gtest_msg.value = "Expected: " #statement \
4785 " throws an exception of type " #expected_exception \
4786 ".\n Actual: it throws "; \
4787 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
4788 gtest_msg.value += " with description \""; \
4789 gtest_msg.value += e.what(); \
4790 gtest_msg.value += "\"."; \
4791 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4792 }
4793
4794 #else // GTEST_HAS_EXCEPTIONS
4795
4796 #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
4797
4798 #endif // GTEST_HAS_EXCEPTIONS
4799
4800 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
4801 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4802 if (::testing::internal::TrueWithString gtest_msg{}) { \
4803 bool gtest_caught_expected = false; \
4804 try { \
4805 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4806 } catch (expected_exception const&) { \
4807 gtest_caught_expected = true; \
4808 } \
4809 GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
4810 catch (...) { \
4811 gtest_msg.value = "Expected: " #statement \
4812 " throws an exception of type " #expected_exception \
4813 ".\n Actual: it throws a different type."; \
4814 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4815 } \
4816 if (!gtest_caught_expected) { \
4817 gtest_msg.value = "Expected: " #statement \
4818 " throws an exception of type " #expected_exception \
4819 ".\n Actual: it throws nothing."; \
4820 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4821 } \
4822 } else /*NOLINT*/ \
4823 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
4824 : fail(gtest_msg.value.c_str())
4825
4826 #if GTEST_HAS_EXCEPTIONS
4827
4828 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
4829 catch (std::exception const& e) { \
4830 gtest_msg.value = "it throws "; \
4831 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
4832 gtest_msg.value += " with description \""; \
4833 gtest_msg.value += e.what(); \
4834 gtest_msg.value += "\"."; \
4835 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
4836 }
4837
4838 #else // GTEST_HAS_EXCEPTIONS
4839
4840 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()
4841
4842 #endif // GTEST_HAS_EXCEPTIONS
4843
4844 #define GTEST_TEST_NO_THROW_(statement, fail) \
4845 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4846 if (::testing::internal::TrueWithString gtest_msg{}) { \
4847 try { \
4848 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4849 } \
4850 GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
4851 catch (...) { \
4852 gtest_msg.value = "it throws."; \
4853 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
4854 } \
4855 } else \
4856 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
4857 fail(("Expected: " #statement " doesn't throw an exception.\n" \
4858 " Actual: " + gtest_msg.value).c_str())
4859
4860 #define GTEST_TEST_ANY_THROW_(statement, fail) \
4861 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4862 if (::testing::internal::AlwaysTrue()) { \
4863 bool gtest_caught_any = false; \
4864 try { \
4865 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4866 } \
4867 catch (...) { \
4868 gtest_caught_any = true; \
4869 } \
4870 if (!gtest_caught_any) { \
4871 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
4872 } \
4873 } else \
4874 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
4875 fail("Expected: " #statement " throws an exception.\n" \
4876 " Actual: it doesn't.")
4877
4878
4879 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
4880 // either a boolean expression or an AssertionResult. text is a textual
4881 // representation of expression as it was passed into the EXPECT_TRUE.
4882 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
4883 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4884 if (const ::testing::AssertionResult gtest_ar_ = \
4885 ::testing::AssertionResult(expression)) \
4886 ; \
4887 else \
4888 fail(::testing::internal::GetBoolAssertionFailureMessage(\
4889 gtest_ar_, text, #actual, #expected).c_str())
4890
4891 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
4892 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4893 if (::testing::internal::AlwaysTrue()) { \
4894 ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
4895 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4896 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
4897 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
4898 } \
4899 } else \
4900 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
4901 fail("Expected: " #statement " doesn't generate new fatal " \
4902 "failures in the current thread.\n" \
4903 " Actual: it does.")
4904
4905 // Expands to the name of the class that implements the given test.
4906 #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
4907 test_suite_name##_##test_name##_Test
4908
4909 // Helper macro for defining tests.
4910 #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
4911 static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \
4912 "test_suite_name must not be empty"); \
4913 static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \
4914 "test_name must not be empty"); \
4915 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
4916 : public parent_class { \
4917 public: \
4918 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
4919 ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
4920 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
4921 test_name)); \
4922 GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
4923 test_name)); \
4924 \
4925 private: \
4926 void TestBody() override; \
4927 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
4928 }; \
4929 \
4930 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
4931 test_name)::test_info_ = \
4932 ::testing::internal::MakeAndRegisterTestInfo( \
4933 #test_suite_name, #test_name, nullptr, nullptr, \
4934 ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
4935 ::testing::internal::SuiteApiResolver< \
4936 parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
4937 ::testing::internal::SuiteApiResolver< \
4938 parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
4939 new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
4940 test_suite_name, test_name)>); \
4941 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
4942
4943 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
4944 // Copyright 2005, Google Inc.
4945 // All rights reserved.
4946 //
4947 // Redistribution and use in source and binary forms, with or without
4948 // modification, are permitted provided that the following conditions are
4949 // met:
4950 //
4951 // * Redistributions of source code must retain the above copyright
4952 // notice, this list of conditions and the following disclaimer.
4953 // * Redistributions in binary form must reproduce the above
4954 // copyright notice, this list of conditions and the following disclaimer
4955 // in the documentation and/or other materials provided with the
4956 // distribution.
4957 // * Neither the name of Google Inc. nor the names of its
4958 // contributors may be used to endorse or promote products derived from
4959 // this software without specific prior written permission.
4960 //
4961 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4962 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
4963 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
4964 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
4965 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
4966 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
4967 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
4968 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
4969 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
4970 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
4971 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4972
4973 //
4974 // The Google C++ Testing and Mocking Framework (Google Test)
4975 //
4976 // This header file defines the public API for death tests. It is
4977 // #included by gtest.h so a user doesn't need to include this
4978 // directly.
4979 // GOOGLETEST_CM0001 DO NOT DELETE
4980
4981 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
4982 #define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
4983
4984 // Copyright 2005, Google Inc.
4985 // All rights reserved.
4986 //
4987 // Redistribution and use in source and binary forms, with or without
4988 // modification, are permitted provided that the following conditions are
4989 // met:
4990 //
4991 // * Redistributions of source code must retain the above copyright
4992 // notice, this list of conditions and the following disclaimer.
4993 // * Redistributions in binary form must reproduce the above
4994 // copyright notice, this list of conditions and the following disclaimer
4995 // in the documentation and/or other materials provided with the
4996 // distribution.
4997 // * Neither the name of Google Inc. nor the names of its
4998 // contributors may be used to endorse or promote products derived from
4999 // this software without specific prior written permission.
5000 //
5001 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5002 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5003 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5004 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5005 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5006 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5007 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5008 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5009 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5010 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5011 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5012 //
5013 // The Google C++ Testing and Mocking Framework (Google Test)
5014 //
5015 // This header file defines internal utilities needed for implementing
5016 // death tests. They are subject to change without notice.
5017 // GOOGLETEST_CM0001 DO NOT DELETE
5018
5019 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
5020 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
5021
5022 // Copyright 2007, Google Inc.
5023 // All rights reserved.
5024 //
5025 // Redistribution and use in source and binary forms, with or without
5026 // modification, are permitted provided that the following conditions are
5027 // met:
5028 //
5029 // * Redistributions of source code must retain the above copyright
5030 // notice, this list of conditions and the following disclaimer.
5031 // * Redistributions in binary form must reproduce the above
5032 // copyright notice, this list of conditions and the following disclaimer
5033 // in the documentation and/or other materials provided with the
5034 // distribution.
5035 // * Neither the name of Google Inc. nor the names of its
5036 // contributors may be used to endorse or promote products derived from
5037 // this software without specific prior written permission.
5038 //
5039 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5040 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5041 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5042 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5043 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5044 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5045 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5046 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5047 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5048 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5049 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5050
5051 // The Google C++ Testing and Mocking Framework (Google Test)
5052 //
5053 // This file implements just enough of the matcher interface to allow
5054 // EXPECT_DEATH and friends to accept a matcher argument.
5055
5056 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
5057 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
5058
5059 #include <atomic>
5060 #include <memory>
5061 #include <ostream>
5062 #include <string>
5063 #include <type_traits>
5064
5065 // Copyright 2007, Google Inc.
5066 // All rights reserved.
5067 //
5068 // Redistribution and use in source and binary forms, with or without
5069 // modification, are permitted provided that the following conditions are
5070 // met:
5071 //
5072 // * Redistributions of source code must retain the above copyright
5073 // notice, this list of conditions and the following disclaimer.
5074 // * Redistributions in binary form must reproduce the above
5075 // copyright notice, this list of conditions and the following disclaimer
5076 // in the documentation and/or other materials provided with the
5077 // distribution.
5078 // * Neither the name of Google Inc. nor the names of its
5079 // contributors may be used to endorse or promote products derived from
5080 // this software without specific prior written permission.
5081 //
5082 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5083 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5084 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5085 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5086 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5087 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5088 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5089 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5090 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5091 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5092 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5093
5094
5095 // Google Test - The Google C++ Testing and Mocking Framework
5096 //
5097 // This file implements a universal value printer that can print a
5098 // value of any type T:
5099 //
5100 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
5101 //
5102 // A user can teach this function how to print a class type T by
5103 // defining either operator<<() or PrintTo() in the namespace that
5104 // defines T. More specifically, the FIRST defined function in the
5105 // following list will be used (assuming T is defined in namespace
5106 // foo):
5107 //
5108 // 1. foo::PrintTo(const T&, ostream*)
5109 // 2. operator<<(ostream&, const T&) defined in either foo or the
5110 // global namespace.
5111 //
5112 // However if T is an STL-style container then it is printed element-wise
5113 // unless foo::PrintTo(const T&, ostream*) is defined. Note that
5114 // operator<<() is ignored for container types.
5115 //
5116 // If none of the above is defined, it will print the debug string of
5117 // the value if it is a protocol buffer, or print the raw bytes in the
5118 // value otherwise.
5119 //
5120 // To aid debugging: when T is a reference type, the address of the
5121 // value is also printed; when T is a (const) char pointer, both the
5122 // pointer value and the NUL-terminated string it points to are
5123 // printed.
5124 //
5125 // We also provide some convenient wrappers:
5126 //
5127 // // Prints a value to a string. For a (const or not) char
5128 // // pointer, the NUL-terminated string (but not the pointer) is
5129 // // printed.
5130 // std::string ::testing::PrintToString(const T& value);
5131 //
5132 // // Prints a value tersely: for a reference type, the referenced
5133 // // value (but not the address) is printed; for a (const or not) char
5134 // // pointer, the NUL-terminated string (but not the pointer) is
5135 // // printed.
5136 // void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
5137 //
5138 // // Prints value using the type inferred by the compiler. The difference
5139 // // from UniversalTersePrint() is that this function prints both the
5140 // // pointer and the NUL-terminated string for a (const or not) char pointer.
5141 // void ::testing::internal::UniversalPrint(const T& value, ostream*);
5142 //
5143 // // Prints the fields of a tuple tersely to a string vector, one
5144 // // element for each field. Tuple support must be enabled in
5145 // // gtest-port.h.
5146 // std::vector<string> UniversalTersePrintTupleFieldsToStrings(
5147 // const Tuple& value);
5148 //
5149 // Known limitation:
5150 //
5151 // The print primitives print the elements of an STL-style container
5152 // using the compiler-inferred type of *iter where iter is a
5153 // const_iterator of the container. When const_iterator is an input
5154 // iterator but not a forward iterator, this inferred type may not
5155 // match value_type, and the print output may be incorrect. In
5156 // practice, this is rarely a problem as for most containers
5157 // const_iterator is a forward iterator. We'll fix this if there's an
5158 // actual need for it. Note that this fix cannot rely on value_type
5159 // being defined as many user-defined container types don't have
5160 // value_type.
5161
5162 // GOOGLETEST_CM0001 DO NOT DELETE
5163
5164 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
5165 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
5166
5167 #include <functional>
5168 #include <memory>
5169 #include <ostream> // NOLINT
5170 #include <sstream>
5171 #include <string>
5172 #include <tuple>
5173 #include <type_traits>
5174 #include <utility>
5175 #include <vector>
5176
5177
5178 namespace testing {
5179
5180 // Definitions in the internal* namespaces are subject to change without notice.
5181 // DO NOT USE THEM IN USER CODE!
5182 namespace internal {
5183
5184 template <typename T>
5185 void UniversalPrint(const T& value, ::std::ostream* os);
5186
5187 // Used to print an STL-style container when the user doesn't define
5188 // a PrintTo() for it.
5189 struct ContainerPrinter {
5190 template <typename T,
5191 typename = typename std::enable_if<
5192 (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
5193 !IsRecursiveContainer<T>::value>::type>
5194 static void PrintValue(const T& container, std::ostream* os) {
5195 const size_t kMaxCount = 32; // The maximum number of elements to print.
5196 *os << '{';
5197 size_t count = 0;
5198 for (auto&& elem : container) {
5199 if (count > 0) {
5200 *os << ',';
5201 if (count == kMaxCount) { // Enough has been printed.
5202 *os << " ...";
5203 break;
5204 }
5205 }
5206 *os << ' ';
5207 // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
5208 // handle `elem` being a native array.
5209 internal::UniversalPrint(elem, os);
5210 ++count;
5211 }
5212
5213 if (count > 0) {
5214 *os << ' ';
5215 }
5216 *os << '}';
5217 }
5218 };
5219
5220 // Used to print a pointer that is neither a char pointer nor a member
5221 // pointer, when the user doesn't define PrintTo() for it. (A member
5222 // variable pointer or member function pointer doesn't really point to
5223 // a location in the address space. Their representation is
5224 // implementation-defined. Therefore they will be printed as raw
5225 // bytes.)
5226 struct FunctionPointerPrinter {
5227 template <typename T, typename = typename std::enable_if<
5228 std::is_function<T>::value>::type>
5229 static void PrintValue(T* p, ::std::ostream* os) {
5230 if (p == nullptr) {
5231 *os << "NULL";
5232 } else {
5233 // T is a function type, so '*os << p' doesn't do what we want
5234 // (it just prints p as bool). We want to print p as a const
5235 // void*.
5236 *os << reinterpret_cast<const void*>(p);
5237 }
5238 }
5239 };
5240
5241 struct PointerPrinter {
5242 template <typename T>
5243 static void PrintValue(T* p, ::std::ostream* os) {
5244 if (p == nullptr) {
5245 *os << "NULL";
5246 } else {
5247 // T is not a function type. We just call << to print p,
5248 // relying on ADL to pick up user-defined << for their pointer
5249 // types, if any.
5250 *os << p;
5251 }
5252 }
5253 };
5254
5255 namespace internal_stream_operator_without_lexical_name_lookup {
5256
5257 // The presence of an operator<< here will terminate lexical scope lookup
5258 // straight away (even though it cannot be a match because of its argument
5259 // types). Thus, the two operator<< calls in StreamPrinter will find only ADL
5260 // candidates.
5261 struct LookupBlocker {};
5262 void operator<<(LookupBlocker, LookupBlocker);
5263
5264 struct StreamPrinter {
5265 template <typename T,
5266 // Don't accept member pointers here. We'd print them via implicit
5267 // conversion to bool, which isn't useful.
5268 typename = typename std::enable_if<
5269 !std::is_member_pointer<T>::value>::type,
5270 // Only accept types for which we can find a streaming operator via
5271 // ADL (possibly involving implicit conversions).
5272 typename = decltype(std::declval<std::ostream&>()
5273 << std::declval<const T&>())>
5274 static void PrintValue(const T& value, ::std::ostream* os) {
5275 // Call streaming operator found by ADL, possibly with implicit conversions
5276 // of the arguments.
5277 *os << value;
5278 }
5279 };
5280
5281 } // namespace internal_stream_operator_without_lexical_name_lookup
5282
5283 struct ProtobufPrinter {
5284 // We print a protobuf using its ShortDebugString() when the string
5285 // doesn't exceed this many characters; otherwise we print it using
5286 // DebugString() for better readability.
5287 static const size_t kProtobufOneLinerMaxLength = 50;
5288
5289 template <typename T,
5290 typename = typename std::enable_if<
5291 internal::HasDebugStringAndShortDebugString<T>::value>::type>
5292 static void PrintValue(const T& value, ::std::ostream* os) {
5293 std::string pretty_str = value.ShortDebugString();
5294 if (pretty_str.length() > kProtobufOneLinerMaxLength) {
5295 pretty_str = "\n" + value.DebugString();
5296 }
5297 *os << ("<" + pretty_str + ">");
5298 }
5299 };
5300
5301 struct ConvertibleToIntegerPrinter {
5302 // Since T has no << operator or PrintTo() but can be implicitly
5303 // converted to BiggestInt, we print it as a BiggestInt.
5304 //
5305 // Most likely T is an enum type (either named or unnamed), in which
5306 // case printing it as an integer is the desired behavior. In case
5307 // T is not an enum, printing it as an integer is the best we can do
5308 // given that it has no user-defined printer.
5309 static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
5310 *os << value;
5311 }
5312 };
5313
5314 struct ConvertibleToStringViewPrinter {
5315 #if GTEST_INTERNAL_HAS_STRING_VIEW
5316 static void PrintValue(internal::StringView value, ::std::ostream* os) {
5317 internal::UniversalPrint(value, os);
5318 }
5319 #endif
5320 };
5321
5322
5323 // Prints the given number of bytes in the given object to the given
5324 // ostream.
5325 GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
5326 size_t count,
5327 ::std::ostream* os);
5328 struct RawBytesPrinter {
5329 // SFINAE on `sizeof` to make sure we have a complete type.
5330 template <typename T, size_t = sizeof(T)>
5331 static void PrintValue(const T& value, ::std::ostream* os) {
5332 PrintBytesInObjectTo(
5333 static_cast<const unsigned char*>(
5334 // Load bearing cast to void* to support iOS
5335 reinterpret_cast<const void*>(std::addressof(value))),
5336 sizeof(value), os);
5337 }
5338 };
5339
5340 struct FallbackPrinter {
5341 template <typename T>
5342 static void PrintValue(const T&, ::std::ostream* os) {
5343 *os << "(incomplete type)";
5344 }
5345 };
5346
5347 // Try every printer in order and return the first one that works.
5348 template <typename T, typename E, typename Printer, typename... Printers>
5349 struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
5350
5351 template <typename T, typename Printer, typename... Printers>
5352 struct FindFirstPrinter<
5353 T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
5354 Printer, Printers...> {
5355 using type = Printer;
5356 };
5357
5358 // Select the best printer in the following order:
5359 // - Print containers (they have begin/end/etc).
5360 // - Print function pointers.
5361 // - Print object pointers.
5362 // - Use the stream operator, if available.
5363 // - Print protocol buffers.
5364 // - Print types convertible to BiggestInt.
5365 // - Print types convertible to StringView, if available.
5366 // - Fallback to printing the raw bytes of the object.
5367 template <typename T>
5368 void PrintWithFallback(const T& value, ::std::ostream* os) {
5369 using Printer = typename FindFirstPrinter<
5370 T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
5371 internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
5372 ProtobufPrinter, ConvertibleToIntegerPrinter,
5373 ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
5374 Printer::PrintValue(value, os);
5375 }
5376
5377 // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
5378 // value of type ToPrint that is an operand of a comparison assertion
5379 // (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
5380 // the comparison, and is used to help determine the best way to
5381 // format the value. In particular, when the value is a C string
5382 // (char pointer) and the other operand is an STL string object, we
5383 // want to format the C string as a string, since we know it is
5384 // compared by value with the string object. If the value is a char
5385 // pointer but the other operand is not an STL string object, we don't
5386 // know whether the pointer is supposed to point to a NUL-terminated
5387 // string, and thus want to print it as a pointer to be safe.
5388 //
5389 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
5390
5391 // The default case.
5392 template <typename ToPrint, typename OtherOperand>
5393 class FormatForComparison {
5394 public:
5395 static ::std::string Format(const ToPrint& value) {
5396 return ::testing::PrintToString(value);
5397 }
5398 };
5399
5400 // Array.
5401 template <typename ToPrint, size_t N, typename OtherOperand>
5402 class FormatForComparison<ToPrint[N], OtherOperand> {
5403 public:
5404 static ::std::string Format(const ToPrint* value) {
5405 return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
5406 }
5407 };
5408
5409 // By default, print C string as pointers to be safe, as we don't know
5410 // whether they actually point to a NUL-terminated string.
5411
5412 #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
5413 template <typename OtherOperand> \
5414 class FormatForComparison<CharType*, OtherOperand> { \
5415 public: \
5416 static ::std::string Format(CharType* value) { \
5417 return ::testing::PrintToString(static_cast<const void*>(value)); \
5418 } \
5419 }
5420
5421 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
5422 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
5423 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
5424 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
5425 #ifdef __cpp_lib_char8_t
5426 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
5427 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
5428 #endif
5429 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
5430 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
5431 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
5432 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
5433
5434 #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
5435
5436 // If a C string is compared with an STL string object, we know it's meant
5437 // to point to a NUL-terminated string, and thus can print it as a string.
5438
5439 #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
5440 template <> \
5441 class FormatForComparison<CharType*, OtherStringType> { \
5442 public: \
5443 static ::std::string Format(CharType* value) { \
5444 return ::testing::PrintToString(value); \
5445 } \
5446 }
5447
5448 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
5449 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
5450 #ifdef __cpp_char8_t
5451 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
5452 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
5453 #endif
5454 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
5455 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
5456 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
5457 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
5458
5459 #if GTEST_HAS_STD_WSTRING
5460 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
5461 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
5462 #endif
5463
5464 #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
5465
5466 // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
5467 // operand to be used in a failure message. The type (but not value)
5468 // of the other operand may affect the format. This allows us to
5469 // print a char* as a raw pointer when it is compared against another
5470 // char* or void*, and print it as a C string when it is compared
5471 // against an std::string object, for example.
5472 //
5473 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
5474 template <typename T1, typename T2>
5475 std::string FormatForComparisonFailureMessage(
5476 const T1& value, const T2& /* other_operand */) {
5477 return FormatForComparison<T1, T2>::Format(value);
5478 }
5479
5480 // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
5481 // value to the given ostream. The caller must ensure that
5482 // 'ostream_ptr' is not NULL, or the behavior is undefined.
5483 //
5484 // We define UniversalPrinter as a class template (as opposed to a
5485 // function template), as we need to partially specialize it for
5486 // reference types, which cannot be done with function templates.
5487 template <typename T>
5488 class UniversalPrinter;
5489
5490 // Prints the given value using the << operator if it has one;
5491 // otherwise prints the bytes in it. This is what
5492 // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
5493 // or overloaded for type T.
5494 //
5495 // A user can override this behavior for a class type Foo by defining
5496 // an overload of PrintTo() in the namespace where Foo is defined. We
5497 // give the user this option as sometimes defining a << operator for
5498 // Foo is not desirable (e.g. the coding style may prevent doing it,
5499 // or there is already a << operator but it doesn't do what the user
5500 // wants).
5501 template <typename T>
5502 void PrintTo(const T& value, ::std::ostream* os) {
5503 internal::PrintWithFallback(value, os);
5504 }
5505
5506 // The following list of PrintTo() overloads tells
5507 // UniversalPrinter<T>::Print() how to print standard types (built-in
5508 // types, strings, plain arrays, and pointers).
5509
5510 // Overloads for various char types.
5511 GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
5512 GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
5513 inline void PrintTo(char c, ::std::ostream* os) {
5514 // When printing a plain char, we always treat it as unsigned. This
5515 // way, the output won't be affected by whether the compiler thinks
5516 // char is signed or not.
5517 PrintTo(static_cast<unsigned char>(c), os);
5518 }
5519
5520 // Overloads for other simple built-in types.
5521 inline void PrintTo(bool x, ::std::ostream* os) {
5522 *os << (x ? "true" : "false");
5523 }
5524
5525 // Overload for wchar_t type.
5526 // Prints a wchar_t as a symbol if it is printable or as its internal
5527 // code otherwise and also as its decimal code (except for L'\0').
5528 // The L'\0' char is printed as "L'\\0'". The decimal code is printed
5529 // as signed integer when wchar_t is implemented by the compiler
5530 // as a signed type and is printed as an unsigned integer when wchar_t
5531 // is implemented as an unsigned type.
5532 GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
5533
5534 GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
5535 inline void PrintTo(char16_t c, ::std::ostream* os) {
5536 PrintTo(ImplicitCast_<char32_t>(c), os);
5537 }
5538 #ifdef __cpp_char8_t
5539 inline void PrintTo(char8_t c, ::std::ostream* os) {
5540 PrintTo(ImplicitCast_<char32_t>(c), os);
5541 }
5542 #endif
5543
5544 // Overloads for C strings.
5545 GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
5546 inline void PrintTo(char* s, ::std::ostream* os) {
5547 PrintTo(ImplicitCast_<const char*>(s), os);
5548 }
5549
5550 // signed/unsigned char is often used for representing binary data, so
5551 // we print pointers to it as void* to be safe.
5552 inline void PrintTo(const signed char* s, ::std::ostream* os) {
5553 PrintTo(ImplicitCast_<const void*>(s), os);
5554 }
5555 inline void PrintTo(signed char* s, ::std::ostream* os) {
5556 PrintTo(ImplicitCast_<const void*>(s), os);
5557 }
5558 inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
5559 PrintTo(ImplicitCast_<const void*>(s), os);
5560 }
5561 inline void PrintTo(unsigned char* s, ::std::ostream* os) {
5562 PrintTo(ImplicitCast_<const void*>(s), os);
5563 }
5564 #ifdef __cpp_char8_t
5565 // Overloads for u8 strings.
5566 GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
5567 inline void PrintTo(char8_t* s, ::std::ostream* os) {
5568 PrintTo(ImplicitCast_<const char8_t*>(s), os);
5569 }
5570 #endif
5571 // Overloads for u16 strings.
5572 GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);
5573 inline void PrintTo(char16_t* s, ::std::ostream* os) {
5574 PrintTo(ImplicitCast_<const char16_t*>(s), os);
5575 }
5576 // Overloads for u32 strings.
5577 GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);
5578 inline void PrintTo(char32_t* s, ::std::ostream* os) {
5579 PrintTo(ImplicitCast_<const char32_t*>(s), os);
5580 }
5581
5582 // MSVC can be configured to define wchar_t as a typedef of unsigned
5583 // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
5584 // type. When wchar_t is a typedef, defining an overload for const
5585 // wchar_t* would cause unsigned short* be printed as a wide string,
5586 // possibly causing invalid memory accesses.
5587 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
5588 // Overloads for wide C strings
5589 GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
5590 inline void PrintTo(wchar_t* s, ::std::ostream* os) {
5591 PrintTo(ImplicitCast_<const wchar_t*>(s), os);
5592 }
5593 #endif
5594
5595 // Overload for C arrays. Multi-dimensional arrays are printed
5596 // properly.
5597
5598 // Prints the given number of elements in an array, without printing
5599 // the curly braces.
5600 template <typename T>
5601 void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
5602 UniversalPrint(a[0], os);
5603 for (size_t i = 1; i != count; i++) {
5604 *os << ", ";
5605 UniversalPrint(a[i], os);
5606 }
5607 }
5608
5609 // Overloads for ::std::string.
5610 GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
5611 inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
5612 PrintStringTo(s, os);
5613 }
5614
5615 // Overloads for ::std::u8string
5616 #ifdef __cpp_char8_t
5617 GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
5618 inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
5619 PrintU8StringTo(s, os);
5620 }
5621 #endif
5622
5623 // Overloads for ::std::u16string
5624 GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
5625 inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
5626 PrintU16StringTo(s, os);
5627 }
5628
5629 // Overloads for ::std::u32string
5630 GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
5631 inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
5632 PrintU32StringTo(s, os);
5633 }
5634
5635 // Overloads for ::std::wstring.
5636 #if GTEST_HAS_STD_WSTRING
5637 GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
5638 inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
5639 PrintWideStringTo(s, os);
5640 }
5641 #endif // GTEST_HAS_STD_WSTRING
5642
5643 #if GTEST_INTERNAL_HAS_STRING_VIEW
5644 // Overload for internal::StringView.
5645 inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
5646 PrintTo(::std::string(sp), os);
5647 }
5648 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
5649
5650 inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
5651
5652 template <typename T>
5653 void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
5654 UniversalPrinter<T&>::Print(ref.get(), os);
5655 }
5656
5657 inline const void* VoidifyPointer(const void* p) { return p; }
5658 inline const void* VoidifyPointer(volatile const void* p) {
5659 return const_cast<const void*>(p);
5660 }
5661
5662 template <typename T, typename Ptr>
5663 void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
5664 if (ptr == nullptr) {
5665 *os << "(nullptr)";
5666 } else {
5667 // We can't print the value. Just print the pointer..
5668 *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
5669 }
5670 }
5671 template <typename T, typename Ptr,
5672 typename = typename std::enable_if<!std::is_void<T>::value &&
5673 !std::is_array<T>::value>::type>
5674 void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
5675 if (ptr == nullptr) {
5676 *os << "(nullptr)";
5677 } else {
5678 *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
5679 UniversalPrinter<T>::Print(*ptr, os);
5680 *os << ")";
5681 }
5682 }
5683
5684 template <typename T, typename D>
5685 void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
5686 (PrintSmartPointer<T>)(ptr, os, 0);
5687 }
5688
5689 template <typename T>
5690 void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
5691 (PrintSmartPointer<T>)(ptr, os, 0);
5692 }
5693
5694 // Helper function for printing a tuple. T must be instantiated with
5695 // a tuple type.
5696 template <typename T>
5697 void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
5698 ::std::ostream*) {}
5699
5700 template <typename T, size_t I>
5701 void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
5702 ::std::ostream* os) {
5703 PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
5704 GTEST_INTENTIONAL_CONST_COND_PUSH_()
5705 if (I > 1) {
5706 GTEST_INTENTIONAL_CONST_COND_POP_()
5707 *os << ", ";
5708 }
5709 UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
5710 std::get<I - 1>(t), os);
5711 }
5712
5713 template <typename... Types>
5714 void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
5715 *os << "(";
5716 PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
5717 *os << ")";
5718 }
5719
5720 // Overload for std::pair.
5721 template <typename T1, typename T2>
5722 void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
5723 *os << '(';
5724 // We cannot use UniversalPrint(value.first, os) here, as T1 may be
5725 // a reference type. The same for printing value.second.
5726 UniversalPrinter<T1>::Print(value.first, os);
5727 *os << ", ";
5728 UniversalPrinter<T2>::Print(value.second, os);
5729 *os << ')';
5730 }
5731
5732 // Implements printing a non-reference type T by letting the compiler
5733 // pick the right overload of PrintTo() for T.
5734 template <typename T>
5735 class UniversalPrinter {
5736 public:
5737 // MSVC warns about adding const to a function type, so we want to
5738 // disable the warning.
5739 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
5740
5741 // Note: we deliberately don't call this PrintTo(), as that name
5742 // conflicts with ::testing::internal::PrintTo in the body of the
5743 // function.
5744 static void Print(const T& value, ::std::ostream* os) {
5745 // By default, ::testing::internal::PrintTo() is used for printing
5746 // the value.
5747 //
5748 // Thanks to Koenig look-up, if T is a class and has its own
5749 // PrintTo() function defined in its namespace, that function will
5750 // be visible here. Since it is more specific than the generic ones
5751 // in ::testing::internal, it will be picked by the compiler in the
5752 // following statement - exactly what we want.
5753 PrintTo(value, os);
5754 }
5755
5756 GTEST_DISABLE_MSC_WARNINGS_POP_()
5757 };
5758
5759 // Remove any const-qualifiers before passing a type to UniversalPrinter.
5760 template <typename T>
5761 class UniversalPrinter<const T> : public UniversalPrinter<T> {};
5762
5763 #if GTEST_INTERNAL_HAS_ANY
5764
5765 // Printer for std::any / absl::any
5766
5767 template <>
5768 class UniversalPrinter<Any> {
5769 public:
5770 static void Print(const Any& value, ::std::ostream* os) {
5771 if (value.has_value()) {
5772 *os << "value of type " << GetTypeName(value);
5773 } else {
5774 *os << "no value";
5775 }
5776 }
5777
5778 private:
5779 static std::string GetTypeName(const Any& value) {
5780 #if GTEST_HAS_RTTI
5781 return internal::GetTypeName(value.type());
5782 #else
5783 static_cast<void>(value); // possibly unused
5784 return "<unknown_type>";
5785 #endif // GTEST_HAS_RTTI
5786 }
5787 };
5788
5789 #endif // GTEST_INTERNAL_HAS_ANY
5790
5791 #if GTEST_INTERNAL_HAS_OPTIONAL
5792
5793 // Printer for std::optional / absl::optional
5794
5795 template <typename T>
5796 class UniversalPrinter<Optional<T>> {
5797 public:
5798 static void Print(const Optional<T>& value, ::std::ostream* os) {
5799 *os << '(';
5800 if (!value) {
5801 *os << "nullopt";
5802 } else {
5803 UniversalPrint(*value, os);
5804 }
5805 *os << ')';
5806 }
5807 };
5808
5809 #endif // GTEST_INTERNAL_HAS_OPTIONAL
5810
5811 #if GTEST_INTERNAL_HAS_VARIANT
5812
5813 // Printer for std::variant / absl::variant
5814
5815 template <typename... T>
5816 class UniversalPrinter<Variant<T...>> {
5817 public:
5818 static void Print(const Variant<T...>& value, ::std::ostream* os) {
5819 *os << '(';
5820 #if GTEST_HAS_ABSL
5821 absl::visit(Visitor{os, value.index()}, value);
5822 #else
5823 std::visit(Visitor{os, value.index()}, value);
5824 #endif // GTEST_HAS_ABSL
5825 *os << ')';
5826 }
5827
5828 private:
5829 struct Visitor {
5830 template <typename U>
5831 void operator()(const U& u) const {
5832 *os << "'" << GetTypeName<U>() << "(index = " << index
5833 << ")' with value ";
5834 UniversalPrint(u, os);
5835 }
5836 ::std::ostream* os;
5837 std::size_t index;
5838 };
5839 };
5840
5841 #endif // GTEST_INTERNAL_HAS_VARIANT
5842
5843 // UniversalPrintArray(begin, len, os) prints an array of 'len'
5844 // elements, starting at address 'begin'.
5845 template <typename T>
5846 void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
5847 if (len == 0) {
5848 *os << "{}";
5849 } else {
5850 *os << "{ ";
5851 const size_t kThreshold = 18;
5852 const size_t kChunkSize = 8;
5853 // If the array has more than kThreshold elements, we'll have to
5854 // omit some details by printing only the first and the last
5855 // kChunkSize elements.
5856 if (len <= kThreshold) {
5857 PrintRawArrayTo(begin, len, os);
5858 } else {
5859 PrintRawArrayTo(begin, kChunkSize, os);
5860 *os << ", ..., ";
5861 PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
5862 }
5863 *os << " }";
5864 }
5865 }
5866 // This overload prints a (const) char array compactly.
5867 GTEST_API_ void UniversalPrintArray(
5868 const char* begin, size_t len, ::std::ostream* os);
5869
5870 #ifdef __cpp_char8_t
5871 // This overload prints a (const) char8_t array compactly.
5872 GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
5873 ::std::ostream* os);
5874 #endif
5875
5876 // This overload prints a (const) char16_t array compactly.
5877 GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
5878 ::std::ostream* os);
5879
5880 // This overload prints a (const) char32_t array compactly.
5881 GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
5882 ::std::ostream* os);
5883
5884 // This overload prints a (const) wchar_t array compactly.
5885 GTEST_API_ void UniversalPrintArray(
5886 const wchar_t* begin, size_t len, ::std::ostream* os);
5887
5888 // Implements printing an array type T[N].
5889 template <typename T, size_t N>
5890 class UniversalPrinter<T[N]> {
5891 public:
5892 // Prints the given array, omitting some elements when there are too
5893 // many.
5894 static void Print(const T (&a)[N], ::std::ostream* os) {
5895 UniversalPrintArray(a, N, os);
5896 }
5897 };
5898
5899 // Implements printing a reference type T&.
5900 template <typename T>
5901 class UniversalPrinter<T&> {
5902 public:
5903 // MSVC warns about adding const to a function type, so we want to
5904 // disable the warning.
5905 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
5906
5907 static void Print(const T& value, ::std::ostream* os) {
5908 // Prints the address of the value. We use reinterpret_cast here
5909 // as static_cast doesn't compile when T is a function type.
5910 *os << "@" << reinterpret_cast<const void*>(&value) << " ";
5911
5912 // Then prints the value itself.
5913 UniversalPrint(value, os);
5914 }
5915
5916 GTEST_DISABLE_MSC_WARNINGS_POP_()
5917 };
5918
5919 // Prints a value tersely: for a reference type, the referenced value
5920 // (but not the address) is printed; for a (const) char pointer, the
5921 // NUL-terminated string (but not the pointer) is printed.
5922
5923 template <typename T>
5924 class UniversalTersePrinter {
5925 public:
5926 static void Print(const T& value, ::std::ostream* os) {
5927 UniversalPrint(value, os);
5928 }
5929 };
5930 template <typename T>
5931 class UniversalTersePrinter<T&> {
5932 public:
5933 static void Print(const T& value, ::std::ostream* os) {
5934 UniversalPrint(value, os);
5935 }
5936 };
5937 template <typename T, size_t N>
5938 class UniversalTersePrinter<T[N]> {
5939 public:
5940 static void Print(const T (&value)[N], ::std::ostream* os) {
5941 UniversalPrinter<T[N]>::Print(value, os);
5942 }
5943 };
5944 template <>
5945 class UniversalTersePrinter<const char*> {
5946 public:
5947 static void Print(const char* str, ::std::ostream* os) {
5948 if (str == nullptr) {
5949 *os << "NULL";
5950 } else {
5951 UniversalPrint(std::string(str), os);
5952 }
5953 }
5954 };
5955 template <>
5956 class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
5957 };
5958
5959 #ifdef __cpp_char8_t
5960 template <>
5961 class UniversalTersePrinter<const char8_t*> {
5962 public:
5963 static void Print(const char8_t* str, ::std::ostream* os) {
5964 if (str == nullptr) {
5965 *os << "NULL";
5966 } else {
5967 UniversalPrint(::std::u8string(str), os);
5968 }
5969 }
5970 };
5971 template <>
5972 class UniversalTersePrinter<char8_t*>
5973 : public UniversalTersePrinter<const char8_t*> {};
5974 #endif
5975
5976 template <>
5977 class UniversalTersePrinter<const char16_t*> {
5978 public:
5979 static void Print(const char16_t* str, ::std::ostream* os) {
5980 if (str == nullptr) {
5981 *os << "NULL";
5982 } else {
5983 UniversalPrint(::std::u16string(str), os);
5984 }
5985 }
5986 };
5987 template <>
5988 class UniversalTersePrinter<char16_t*>
5989 : public UniversalTersePrinter<const char16_t*> {};
5990
5991 template <>
5992 class UniversalTersePrinter<const char32_t*> {
5993 public:
5994 static void Print(const char32_t* str, ::std::ostream* os) {
5995 if (str == nullptr) {
5996 *os << "NULL";
5997 } else {
5998 UniversalPrint(::std::u32string(str), os);
5999 }
6000 }
6001 };
6002 template <>
6003 class UniversalTersePrinter<char32_t*>
6004 : public UniversalTersePrinter<const char32_t*> {};
6005
6006 #if GTEST_HAS_STD_WSTRING
6007 template <>
6008 class UniversalTersePrinter<const wchar_t*> {
6009 public:
6010 static void Print(const wchar_t* str, ::std::ostream* os) {
6011 if (str == nullptr) {
6012 *os << "NULL";
6013 } else {
6014 UniversalPrint(::std::wstring(str), os);
6015 }
6016 }
6017 };
6018 #endif
6019
6020 template <>
6021 class UniversalTersePrinter<wchar_t*> {
6022 public:
6023 static void Print(wchar_t* str, ::std::ostream* os) {
6024 UniversalTersePrinter<const wchar_t*>::Print(str, os);
6025 }
6026 };
6027
6028 template <typename T>
6029 void UniversalTersePrint(const T& value, ::std::ostream* os) {
6030 UniversalTersePrinter<T>::Print(value, os);
6031 }
6032
6033 // Prints a value using the type inferred by the compiler. The
6034 // difference between this and UniversalTersePrint() is that for a
6035 // (const) char pointer, this prints both the pointer and the
6036 // NUL-terminated string.
6037 template <typename T>
6038 void UniversalPrint(const T& value, ::std::ostream* os) {
6039 // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
6040 // UniversalPrinter with T directly.
6041 typedef T T1;
6042 UniversalPrinter<T1>::Print(value, os);
6043 }
6044
6045 typedef ::std::vector< ::std::string> Strings;
6046
6047 // Tersely prints the first N fields of a tuple to a string vector,
6048 // one element for each field.
6049 template <typename Tuple>
6050 void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
6051 Strings*) {}
6052 template <typename Tuple, size_t I>
6053 void TersePrintPrefixToStrings(const Tuple& t,
6054 std::integral_constant<size_t, I>,
6055 Strings* strings) {
6056 TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
6057 strings);
6058 ::std::stringstream ss;
6059 UniversalTersePrint(std::get<I - 1>(t), &ss);
6060 strings->push_back(ss.str());
6061 }
6062
6063 // Prints the fields of a tuple tersely to a string vector, one
6064 // element for each field. See the comment before
6065 // UniversalTersePrint() for how we define "tersely".
6066 template <typename Tuple>
6067 Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
6068 Strings result;
6069 TersePrintPrefixToStrings(
6070 value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
6071 &result);
6072 return result;
6073 }
6074
6075 } // namespace internal
6076
6077 template <typename T>
6078 ::std::string PrintToString(const T& value) {
6079 ::std::stringstream ss;
6080 internal::UniversalTersePrinter<T>::Print(value, &ss);
6081 return ss.str();
6082 }
6083
6084 } // namespace testing
6085
6086 // Include any custom printer added by the local installation.
6087 // We must include this header at the end to make sure it can use the
6088 // declarations from this file.
6089 // Copyright 2015, Google Inc.
6090 // All rights reserved.
6091 //
6092 // Redistribution and use in source and binary forms, with or without
6093 // modification, are permitted provided that the following conditions are
6094 // met:
6095 //
6096 // * Redistributions of source code must retain the above copyright
6097 // notice, this list of conditions and the following disclaimer.
6098 // * Redistributions in binary form must reproduce the above
6099 // copyright notice, this list of conditions and the following disclaimer
6100 // in the documentation and/or other materials provided with the
6101 // distribution.
6102 // * Neither the name of Google Inc. nor the names of its
6103 // contributors may be used to endorse or promote products derived from
6104 // this software without specific prior written permission.
6105 //
6106 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6107 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6108 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6109 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6110 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6111 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6112 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6113 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6114 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6115 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6116 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6117 //
6118 // This file provides an injection point for custom printers in a local
6119 // installation of gTest.
6120 // It will be included from gtest-printers.h and the overrides in this file
6121 // will be visible to everyone.
6122 //
6123 // Injection point for custom user configurations. See README for details
6124 //
6125 // ** Custom implementation starts here **
6126
6127 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
6128 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
6129
6130 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
6131
6132 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
6133
6134 // MSVC warning C5046 is new as of VS2017 version 15.8.
6135 #if defined(_MSC_VER) && _MSC_VER >= 1915
6136 #define GTEST_MAYBE_5046_ 5046
6137 #else
6138 #define GTEST_MAYBE_5046_
6139 #endif
6140
6141 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
6142 4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
6143 clients of class B */
6144 /* Symbol involving type with internal linkage not defined */)
6145
6146 namespace testing {
6147
6148 // To implement a matcher Foo for type T, define:
6149 // 1. a class FooMatcherMatcher that implements the matcher interface:
6150 // using is_gtest_matcher = void;
6151 // bool MatchAndExplain(const T&, std::ostream*);
6152 // (MatchResultListener* can also be used instead of std::ostream*)
6153 // void DescribeTo(std::ostream*);
6154 // void DescribeNegationTo(std::ostream*);
6155 //
6156 // 2. a factory function that creates a Matcher<T> object from a
6157 // FooMatcherMatcher.
6158
6159 class MatchResultListener {
6160 public:
6161 // Creates a listener object with the given underlying ostream. The
6162 // listener does not own the ostream, and does not dereference it
6163 // in the constructor or destructor.
6164 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
6165 virtual ~MatchResultListener() = 0; // Makes this class abstract.
6166
6167 // Streams x to the underlying ostream; does nothing if the ostream
6168 // is NULL.
6169 template <typename T>
6170 MatchResultListener& operator<<(const T& x) {
6171 if (stream_ != nullptr) *stream_ << x;
6172 return *this;
6173 }
6174
6175 // Returns the underlying ostream.
6176 ::std::ostream* stream() { return stream_; }
6177
6178 // Returns true if and only if the listener is interested in an explanation
6179 // of the match result. A matcher's MatchAndExplain() method can use
6180 // this information to avoid generating the explanation when no one
6181 // intends to hear it.
6182 bool IsInterested() const { return stream_ != nullptr; }
6183
6184 private:
6185 ::std::ostream* const stream_;
6186
6187 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
6188 };
6189
6190 inline MatchResultListener::~MatchResultListener() {
6191 }
6192
6193 // An instance of a subclass of this knows how to describe itself as a
6194 // matcher.
6195 class GTEST_API_ MatcherDescriberInterface {
6196 public:
6197 virtual ~MatcherDescriberInterface() {}
6198
6199 // Describes this matcher to an ostream. The function should print
6200 // a verb phrase that describes the property a value matching this
6201 // matcher should have. The subject of the verb phrase is the value
6202 // being matched. For example, the DescribeTo() method of the Gt(7)
6203 // matcher prints "is greater than 7".
6204 virtual void DescribeTo(::std::ostream* os) const = 0;
6205
6206 // Describes the negation of this matcher to an ostream. For
6207 // example, if the description of this matcher is "is greater than
6208 // 7", the negated description could be "is not greater than 7".
6209 // You are not required to override this when implementing
6210 // MatcherInterface, but it is highly advised so that your matcher
6211 // can produce good error messages.
6212 virtual void DescribeNegationTo(::std::ostream* os) const {
6213 *os << "not (";
6214 DescribeTo(os);
6215 *os << ")";
6216 }
6217 };
6218
6219 // The implementation of a matcher.
6220 template <typename T>
6221 class MatcherInterface : public MatcherDescriberInterface {
6222 public:
6223 // Returns true if and only if the matcher matches x; also explains the
6224 // match result to 'listener' if necessary (see the next paragraph), in
6225 // the form of a non-restrictive relative clause ("which ...",
6226 // "whose ...", etc) that describes x. For example, the
6227 // MatchAndExplain() method of the Pointee(...) matcher should
6228 // generate an explanation like "which points to ...".
6229 //
6230 // Implementations of MatchAndExplain() should add an explanation of
6231 // the match result *if and only if* they can provide additional
6232 // information that's not already present (or not obvious) in the
6233 // print-out of x and the matcher's description. Whether the match
6234 // succeeds is not a factor in deciding whether an explanation is
6235 // needed, as sometimes the caller needs to print a failure message
6236 // when the match succeeds (e.g. when the matcher is used inside
6237 // Not()).
6238 //
6239 // For example, a "has at least 10 elements" matcher should explain
6240 // what the actual element count is, regardless of the match result,
6241 // as it is useful information to the reader; on the other hand, an
6242 // "is empty" matcher probably only needs to explain what the actual
6243 // size is when the match fails, as it's redundant to say that the
6244 // size is 0 when the value is already known to be empty.
6245 //
6246 // You should override this method when defining a new matcher.
6247 //
6248 // It's the responsibility of the caller (Google Test) to guarantee
6249 // that 'listener' is not NULL. This helps to simplify a matcher's
6250 // implementation when it doesn't care about the performance, as it
6251 // can talk to 'listener' without checking its validity first.
6252 // However, in order to implement dummy listeners efficiently,
6253 // listener->stream() may be NULL.
6254 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
6255
6256 // Inherits these methods from MatcherDescriberInterface:
6257 // virtual void DescribeTo(::std::ostream* os) const = 0;
6258 // virtual void DescribeNegationTo(::std::ostream* os) const;
6259 };
6260
6261 namespace internal {
6262
6263 struct AnyEq {
6264 template <typename A, typename B>
6265 bool operator()(const A& a, const B& b) const { return a == b; }
6266 };
6267 struct AnyNe {
6268 template <typename A, typename B>
6269 bool operator()(const A& a, const B& b) const { return a != b; }
6270 };
6271 struct AnyLt {
6272 template <typename A, typename B>
6273 bool operator()(const A& a, const B& b) const { return a < b; }
6274 };
6275 struct AnyGt {
6276 template <typename A, typename B>
6277 bool operator()(const A& a, const B& b) const { return a > b; }
6278 };
6279 struct AnyLe {
6280 template <typename A, typename B>
6281 bool operator()(const A& a, const B& b) const { return a <= b; }
6282 };
6283 struct AnyGe {
6284 template <typename A, typename B>
6285 bool operator()(const A& a, const B& b) const { return a >= b; }
6286 };
6287
6288 // A match result listener that ignores the explanation.
6289 class DummyMatchResultListener : public MatchResultListener {
6290 public:
6291 DummyMatchResultListener() : MatchResultListener(nullptr) {}
6292
6293 private:
6294 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
6295 };
6296
6297 // A match result listener that forwards the explanation to a given
6298 // ostream. The difference between this and MatchResultListener is
6299 // that the former is concrete.
6300 class StreamMatchResultListener : public MatchResultListener {
6301 public:
6302 explicit StreamMatchResultListener(::std::ostream* os)
6303 : MatchResultListener(os) {}
6304
6305 private:
6306 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
6307 };
6308
6309 struct SharedPayloadBase {
6310 std::atomic<int> ref{1};
6311 void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
6312 bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
6313 };
6314
6315 template <typename T>
6316 struct SharedPayload : SharedPayloadBase {
6317 explicit SharedPayload(const T& v) : value(v) {}
6318 explicit SharedPayload(T&& v) : value(std::move(v)) {}
6319
6320 static void Destroy(SharedPayloadBase* shared) {
6321 delete static_cast<SharedPayload*>(shared);
6322 }
6323
6324 T value;
6325 };
6326
6327 // An internal class for implementing Matcher<T>, which will derive
6328 // from it. We put functionalities common to all Matcher<T>
6329 // specializations here to avoid code duplication.
6330 template <typename T>
6331 class MatcherBase : private MatcherDescriberInterface {
6332 public:
6333 // Returns true if and only if the matcher matches x; also explains the
6334 // match result to 'listener'.
6335 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
6336 GTEST_CHECK_(vtable_ != nullptr);
6337 return vtable_->match_and_explain(*this, x, listener);
6338 }
6339
6340 // Returns true if and only if this matcher matches x.
6341 bool Matches(const T& x) const {
6342 DummyMatchResultListener dummy;
6343 return MatchAndExplain(x, &dummy);
6344 }
6345
6346 // Describes this matcher to an ostream.
6347 void DescribeTo(::std::ostream* os) const final {
6348 GTEST_CHECK_(vtable_ != nullptr);
6349 vtable_->describe(*this, os, false);
6350 }
6351
6352 // Describes the negation of this matcher to an ostream.
6353 void DescribeNegationTo(::std::ostream* os) const final {
6354 GTEST_CHECK_(vtable_ != nullptr);
6355 vtable_->describe(*this, os, true);
6356 }
6357
6358 // Explains why x matches, or doesn't match, the matcher.
6359 void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
6360 StreamMatchResultListener listener(os);
6361 MatchAndExplain(x, &listener);
6362 }
6363
6364 // Returns the describer for this matcher object; retains ownership
6365 // of the describer, which is only guaranteed to be alive when
6366 // this matcher object is alive.
6367 const MatcherDescriberInterface* GetDescriber() const {
6368 if (vtable_ == nullptr) return nullptr;
6369 return vtable_->get_describer(*this);
6370 }
6371
6372 protected:
6373 MatcherBase() : vtable_(nullptr) {}
6374
6375 // Constructs a matcher from its implementation.
6376 template <typename U>
6377 explicit MatcherBase(const MatcherInterface<U>* impl) {
6378 Init(impl);
6379 }
6380
6381 template <typename M, typename = typename std::remove_reference<
6382 M>::type::is_gtest_matcher>
6383 MatcherBase(M&& m) { // NOLINT
6384 Init(std::forward<M>(m));
6385 }
6386
6387 MatcherBase(const MatcherBase& other)
6388 : vtable_(other.vtable_), buffer_(other.buffer_) {
6389 if (IsShared()) buffer_.shared->Ref();
6390 }
6391
6392 MatcherBase& operator=(const MatcherBase& other) {
6393 if (this == &other) return *this;
6394 Destroy();
6395 vtable_ = other.vtable_;
6396 buffer_ = other.buffer_;
6397 if (IsShared()) buffer_.shared->Ref();
6398 return *this;
6399 }
6400
6401 MatcherBase(MatcherBase&& other)
6402 : vtable_(other.vtable_), buffer_(other.buffer_) {
6403 other.vtable_ = nullptr;
6404 }
6405
6406 MatcherBase& operator=(MatcherBase&& other) {
6407 if (this == &other) return *this;
6408 Destroy();
6409 vtable_ = other.vtable_;
6410 buffer_ = other.buffer_;
6411 other.vtable_ = nullptr;
6412 return *this;
6413 }
6414
6415 ~MatcherBase() override { Destroy(); }
6416
6417 private:
6418 struct VTable {
6419 bool (*match_and_explain)(const MatcherBase&, const T&,
6420 MatchResultListener*);
6421 void (*describe)(const MatcherBase&, std::ostream*, bool negation);
6422 // Returns the captured object if it implements the interface, otherwise
6423 // returns the MatcherBase itself.
6424 const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
6425 // Called on shared instances when the reference count reaches 0.
6426 void (*shared_destroy)(SharedPayloadBase*);
6427 };
6428
6429 bool IsShared() const {
6430 return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
6431 }
6432
6433 // If the implementation uses a listener, call that.
6434 template <typename P>
6435 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
6436 MatchResultListener* listener)
6437 -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
6438 return P::Get(m).MatchAndExplain(value, listener->stream());
6439 }
6440
6441 template <typename P>
6442 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
6443 MatchResultListener* listener)
6444 -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
6445 return P::Get(m).MatchAndExplain(value, listener);
6446 }
6447
6448 template <typename P>
6449 static void DescribeImpl(const MatcherBase& m, std::ostream* os,
6450 bool negation) {
6451 if (negation) {
6452 P::Get(m).DescribeNegationTo(os);
6453 } else {
6454 P::Get(m).DescribeTo(os);
6455 }
6456 }
6457
6458 template <typename P>
6459 static const MatcherDescriberInterface* GetDescriberImpl(
6460 const MatcherBase& m) {
6461 // If the impl is a MatcherDescriberInterface, then return it.
6462 // Otherwise use MatcherBase itself.
6463 // This allows us to implement the GetDescriber() function without support
6464 // from the impl, but some users really want to get their impl back when
6465 // they call GetDescriber().
6466 // We use std::get on a tuple as a workaround of not having `if constexpr`.
6467 return std::get<(
6468 std::is_convertible<decltype(&P::Get(m)),
6469 const MatcherDescriberInterface*>::value
6470 ? 1
6471 : 0)>(std::make_tuple(&m, &P::Get(m)));
6472 }
6473
6474 template <typename P>
6475 const VTable* GetVTable() {
6476 static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
6477 &DescribeImpl<P>, &GetDescriberImpl<P>,
6478 P::shared_destroy};
6479 return &kVTable;
6480 }
6481
6482 union Buffer {
6483 // Add some types to give Buffer some common alignment/size use cases.
6484 void* ptr;
6485 double d;
6486 int64_t i;
6487 // And add one for the out-of-line cases.
6488 SharedPayloadBase* shared;
6489 };
6490
6491 void Destroy() {
6492 if (IsShared() && buffer_.shared->Unref()) {
6493 vtable_->shared_destroy(buffer_.shared);
6494 }
6495 }
6496
6497 template <typename M>
6498 static constexpr bool IsInlined() {
6499 return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
6500 std::is_trivially_copy_constructible<M>::value &&
6501 std::is_trivially_destructible<M>::value;
6502 }
6503
6504 template <typename M, bool = MatcherBase::IsInlined<M>()>
6505 struct ValuePolicy {
6506 static const M& Get(const MatcherBase& m) {
6507 // When inlined along with Init, need to be explicit to avoid violating
6508 // strict aliasing rules.
6509 const M *ptr = static_cast<const M*>(
6510 static_cast<const void*>(&m.buffer_));
6511 return *ptr;
6512 }
6513 static void Init(MatcherBase& m, M impl) {
6514 ::new (static_cast<void*>(&m.buffer_)) M(impl);
6515 }
6516 static constexpr auto shared_destroy = nullptr;
6517 };
6518
6519 template <typename M>
6520 struct ValuePolicy<M, false> {
6521 using Shared = SharedPayload<M>;
6522 static const M& Get(const MatcherBase& m) {
6523 return static_cast<Shared*>(m.buffer_.shared)->value;
6524 }
6525 template <typename Arg>
6526 static void Init(MatcherBase& m, Arg&& arg) {
6527 m.buffer_.shared = new Shared(std::forward<Arg>(arg));
6528 }
6529 static constexpr auto shared_destroy = &Shared::Destroy;
6530 };
6531
6532 template <typename U, bool B>
6533 struct ValuePolicy<const MatcherInterface<U>*, B> {
6534 using M = const MatcherInterface<U>;
6535 using Shared = SharedPayload<std::unique_ptr<M>>;
6536 static const M& Get(const MatcherBase& m) {
6537 return *static_cast<Shared*>(m.buffer_.shared)->value;
6538 }
6539 static void Init(MatcherBase& m, M* impl) {
6540 m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
6541 }
6542
6543 static constexpr auto shared_destroy = &Shared::Destroy;
6544 };
6545
6546 template <typename M>
6547 void Init(M&& m) {
6548 using MM = typename std::decay<M>::type;
6549 using Policy = ValuePolicy<MM>;
6550 vtable_ = GetVTable<Policy>();
6551 Policy::Init(*this, std::forward<M>(m));
6552 }
6553
6554 const VTable* vtable_;
6555 Buffer buffer_;
6556 };
6557
6558 } // namespace internal
6559
6560 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
6561 // object that can check whether a value of type T matches. The
6562 // implementation of Matcher<T> is just a std::shared_ptr to const
6563 // MatcherInterface<T>. Don't inherit from Matcher!
6564 template <typename T>
6565 class Matcher : public internal::MatcherBase<T> {
6566 public:
6567 // Constructs a null matcher. Needed for storing Matcher objects in STL
6568 // containers. A default-constructed matcher is not yet initialized. You
6569 // cannot use it until a valid value has been assigned to it.
6570 explicit Matcher() {} // NOLINT
6571
6572 // Constructs a matcher from its implementation.
6573 explicit Matcher(const MatcherInterface<const T&>* impl)
6574 : internal::MatcherBase<T>(impl) {}
6575
6576 template <typename U>
6577 explicit Matcher(
6578 const MatcherInterface<U>* impl,
6579 typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
6580 nullptr)
6581 : internal::MatcherBase<T>(impl) {}
6582
6583 template <typename M, typename = typename std::remove_reference<
6584 M>::type::is_gtest_matcher>
6585 Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
6586
6587 // Implicit constructor here allows people to write
6588 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
6589 Matcher(T value); // NOLINT
6590 };
6591
6592 // The following two specializations allow the user to write str
6593 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
6594 // matcher is expected.
6595 template <>
6596 class GTEST_API_ Matcher<const std::string&>
6597 : public internal::MatcherBase<const std::string&> {
6598 public:
6599 Matcher() {}
6600
6601 explicit Matcher(const MatcherInterface<const std::string&>* impl)
6602 : internal::MatcherBase<const std::string&>(impl) {}
6603
6604 template <typename M, typename = typename std::remove_reference<
6605 M>::type::is_gtest_matcher>
6606 Matcher(M&& m) // NOLINT
6607 : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
6608
6609 // Allows the user to write str instead of Eq(str) sometimes, where
6610 // str is a std::string object.
6611 Matcher(const std::string& s); // NOLINT
6612
6613 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6614 Matcher(const char* s); // NOLINT
6615 };
6616
6617 template <>
6618 class GTEST_API_ Matcher<std::string>
6619 : public internal::MatcherBase<std::string> {
6620 public:
6621 Matcher() {}
6622
6623 explicit Matcher(const MatcherInterface<const std::string&>* impl)
6624 : internal::MatcherBase<std::string>(impl) {}
6625 explicit Matcher(const MatcherInterface<std::string>* impl)
6626 : internal::MatcherBase<std::string>(impl) {}
6627
6628 template <typename M, typename = typename std::remove_reference<
6629 M>::type::is_gtest_matcher>
6630 Matcher(M&& m) // NOLINT
6631 : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
6632
6633 // Allows the user to write str instead of Eq(str) sometimes, where
6634 // str is a string object.
6635 Matcher(const std::string& s); // NOLINT
6636
6637 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6638 Matcher(const char* s); // NOLINT
6639 };
6640
6641 #if GTEST_INTERNAL_HAS_STRING_VIEW
6642 // The following two specializations allow the user to write str
6643 // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
6644 // matcher is expected.
6645 template <>
6646 class GTEST_API_ Matcher<const internal::StringView&>
6647 : public internal::MatcherBase<const internal::StringView&> {
6648 public:
6649 Matcher() {}
6650
6651 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
6652 : internal::MatcherBase<const internal::StringView&>(impl) {}
6653
6654 template <typename M, typename = typename std::remove_reference<
6655 M>::type::is_gtest_matcher>
6656 Matcher(M&& m) // NOLINT
6657 : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
6658 }
6659
6660 // Allows the user to write str instead of Eq(str) sometimes, where
6661 // str is a std::string object.
6662 Matcher(const std::string& s); // NOLINT
6663
6664 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6665 Matcher(const char* s); // NOLINT
6666
6667 // Allows the user to pass absl::string_views or std::string_views directly.
6668 Matcher(internal::StringView s); // NOLINT
6669 };
6670
6671 template <>
6672 class GTEST_API_ Matcher<internal::StringView>
6673 : public internal::MatcherBase<internal::StringView> {
6674 public:
6675 Matcher() {}
6676
6677 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
6678 : internal::MatcherBase<internal::StringView>(impl) {}
6679 explicit Matcher(const MatcherInterface<internal::StringView>* impl)
6680 : internal::MatcherBase<internal::StringView>(impl) {}
6681
6682 template <typename M, typename = typename std::remove_reference<
6683 M>::type::is_gtest_matcher>
6684 Matcher(M&& m) // NOLINT
6685 : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
6686
6687 // Allows the user to write str instead of Eq(str) sometimes, where
6688 // str is a std::string object.
6689 Matcher(const std::string& s); // NOLINT
6690
6691 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6692 Matcher(const char* s); // NOLINT
6693
6694 // Allows the user to pass absl::string_views or std::string_views directly.
6695 Matcher(internal::StringView s); // NOLINT
6696 };
6697 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
6698
6699 // Prints a matcher in a human-readable format.
6700 template <typename T>
6701 std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
6702 matcher.DescribeTo(&os);
6703 return os;
6704 }
6705
6706 // The PolymorphicMatcher class template makes it easy to implement a
6707 // polymorphic matcher (i.e. a matcher that can match values of more
6708 // than one type, e.g. Eq(n) and NotNull()).
6709 //
6710 // To define a polymorphic matcher, a user should provide an Impl
6711 // class that has a DescribeTo() method and a DescribeNegationTo()
6712 // method, and define a member function (or member function template)
6713 //
6714 // bool MatchAndExplain(const Value& value,
6715 // MatchResultListener* listener) const;
6716 //
6717 // See the definition of NotNull() for a complete example.
6718 template <class Impl>
6719 class PolymorphicMatcher {
6720 public:
6721 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
6722
6723 // Returns a mutable reference to the underlying matcher
6724 // implementation object.
6725 Impl& mutable_impl() { return impl_; }
6726
6727 // Returns an immutable reference to the underlying matcher
6728 // implementation object.
6729 const Impl& impl() const { return impl_; }
6730
6731 template <typename T>
6732 operator Matcher<T>() const {
6733 return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
6734 }
6735
6736 private:
6737 template <typename T>
6738 class MonomorphicImpl : public MatcherInterface<T> {
6739 public:
6740 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
6741
6742 void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
6743
6744 void DescribeNegationTo(::std::ostream* os) const override {
6745 impl_.DescribeNegationTo(os);
6746 }
6747
6748 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
6749 return impl_.MatchAndExplain(x, listener);
6750 }
6751
6752 private:
6753 const Impl impl_;
6754 };
6755
6756 Impl impl_;
6757 };
6758
6759 // Creates a matcher from its implementation.
6760 // DEPRECATED: Especially in the generic code, prefer:
6761 // Matcher<T>(new MyMatcherImpl<const T&>(...));
6762 //
6763 // MakeMatcher may create a Matcher that accepts its argument by value, which
6764 // leads to unnecessary copies & lack of support for non-copyable types.
6765 template <typename T>
6766 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
6767 return Matcher<T>(impl);
6768 }
6769
6770 // Creates a polymorphic matcher from its implementation. This is
6771 // easier to use than the PolymorphicMatcher<Impl> constructor as it
6772 // doesn't require you to explicitly write the template argument, e.g.
6773 //
6774 // MakePolymorphicMatcher(foo);
6775 // vs
6776 // PolymorphicMatcher<TypeOfFoo>(foo);
6777 template <class Impl>
6778 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
6779 return PolymorphicMatcher<Impl>(impl);
6780 }
6781
6782 namespace internal {
6783 // Implements a matcher that compares a given value with a
6784 // pre-supplied value using one of the ==, <=, <, etc, operators. The
6785 // two values being compared don't have to have the same type.
6786 //
6787 // The matcher defined here is polymorphic (for example, Eq(5) can be
6788 // used to match an int, a short, a double, etc). Therefore we use
6789 // a template type conversion operator in the implementation.
6790 //
6791 // The following template definition assumes that the Rhs parameter is
6792 // a "bare" type (i.e. neither 'const T' nor 'T&').
6793 template <typename D, typename Rhs, typename Op>
6794 class ComparisonBase {
6795 public:
6796 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
6797
6798 using is_gtest_matcher = void;
6799
6800 template <typename Lhs>
6801 bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
6802 return Op()(lhs, Unwrap(rhs_));
6803 }
6804 void DescribeTo(std::ostream* os) const {
6805 *os << D::Desc() << " ";
6806 UniversalPrint(Unwrap(rhs_), os);
6807 }
6808 void DescribeNegationTo(std::ostream* os) const {
6809 *os << D::NegatedDesc() << " ";
6810 UniversalPrint(Unwrap(rhs_), os);
6811 }
6812
6813 private:
6814 template <typename T>
6815 static const T& Unwrap(const T& v) {
6816 return v;
6817 }
6818 template <typename T>
6819 static const T& Unwrap(std::reference_wrapper<T> v) {
6820 return v;
6821 }
6822
6823 Rhs rhs_;
6824 };
6825
6826 template <typename Rhs>
6827 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
6828 public:
6829 explicit EqMatcher(const Rhs& rhs)
6830 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
6831 static const char* Desc() { return "is equal to"; }
6832 static const char* NegatedDesc() { return "isn't equal to"; }
6833 };
6834 template <typename Rhs>
6835 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
6836 public:
6837 explicit NeMatcher(const Rhs& rhs)
6838 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
6839 static const char* Desc() { return "isn't equal to"; }
6840 static const char* NegatedDesc() { return "is equal to"; }
6841 };
6842 template <typename Rhs>
6843 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
6844 public:
6845 explicit LtMatcher(const Rhs& rhs)
6846 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
6847 static const char* Desc() { return "is <"; }
6848 static const char* NegatedDesc() { return "isn't <"; }
6849 };
6850 template <typename Rhs>
6851 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
6852 public:
6853 explicit GtMatcher(const Rhs& rhs)
6854 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
6855 static const char* Desc() { return "is >"; }
6856 static const char* NegatedDesc() { return "isn't >"; }
6857 };
6858 template <typename Rhs>
6859 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
6860 public:
6861 explicit LeMatcher(const Rhs& rhs)
6862 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
6863 static const char* Desc() { return "is <="; }
6864 static const char* NegatedDesc() { return "isn't <="; }
6865 };
6866 template <typename Rhs>
6867 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
6868 public:
6869 explicit GeMatcher(const Rhs& rhs)
6870 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
6871 static const char* Desc() { return "is >="; }
6872 static const char* NegatedDesc() { return "isn't >="; }
6873 };
6874
6875 template <typename T, typename = typename std::enable_if<
6876 std::is_constructible<std::string, T>::value>::type>
6877 using StringLike = T;
6878
6879 // Implements polymorphic matchers MatchesRegex(regex) and
6880 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
6881 // T can be converted to a string.
6882 class MatchesRegexMatcher {
6883 public:
6884 MatchesRegexMatcher(const RE* regex, bool full_match)
6885 : regex_(regex), full_match_(full_match) {}
6886
6887 #if GTEST_INTERNAL_HAS_STRING_VIEW
6888 bool MatchAndExplain(const internal::StringView& s,
6889 MatchResultListener* listener) const {
6890 return MatchAndExplain(std::string(s), listener);
6891 }
6892 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
6893
6894 // Accepts pointer types, particularly:
6895 // const char*
6896 // char*
6897 // const wchar_t*
6898 // wchar_t*
6899 template <typename CharType>
6900 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
6901 return s != nullptr && MatchAndExplain(std::string(s), listener);
6902 }
6903
6904 // Matches anything that can convert to std::string.
6905 //
6906 // This is a template, not just a plain function with const std::string&,
6907 // because absl::string_view has some interfering non-explicit constructors.
6908 template <class MatcheeStringType>
6909 bool MatchAndExplain(const MatcheeStringType& s,
6910 MatchResultListener* /* listener */) const {
6911 const std::string& s2(s);
6912 return full_match_ ? RE::FullMatch(s2, *regex_)
6913 : RE::PartialMatch(s2, *regex_);
6914 }
6915
6916 void DescribeTo(::std::ostream* os) const {
6917 *os << (full_match_ ? "matches" : "contains") << " regular expression ";
6918 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
6919 }
6920
6921 void DescribeNegationTo(::std::ostream* os) const {
6922 *os << "doesn't " << (full_match_ ? "match" : "contain")
6923 << " regular expression ";
6924 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
6925 }
6926
6927 private:
6928 const std::shared_ptr<const RE> regex_;
6929 const bool full_match_;
6930 };
6931 } // namespace internal
6932
6933 // Matches a string that fully matches regular expression 'regex'.
6934 // The matcher takes ownership of 'regex'.
6935 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
6936 const internal::RE* regex) {
6937 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
6938 }
6939 template <typename T = std::string>
6940 PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
6941 const internal::StringLike<T>& regex) {
6942 return MatchesRegex(new internal::RE(std::string(regex)));
6943 }
6944
6945 // Matches a string that contains regular expression 'regex'.
6946 // The matcher takes ownership of 'regex'.
6947 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
6948 const internal::RE* regex) {
6949 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
6950 }
6951 template <typename T = std::string>
6952 PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
6953 const internal::StringLike<T>& regex) {
6954 return ContainsRegex(new internal::RE(std::string(regex)));
6955 }
6956
6957 // Creates a polymorphic matcher that matches anything equal to x.
6958 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
6959 // wouldn't compile.
6960 template <typename T>
6961 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
6962
6963 // Constructs a Matcher<T> from a 'value' of type T. The constructed
6964 // matcher matches any value that's equal to 'value'.
6965 template <typename T>
6966 Matcher<T>::Matcher(T value) { *this = Eq(value); }
6967
6968 // Creates a monomorphic matcher that matches anything with type Lhs
6969 // and equal to rhs. A user may need to use this instead of Eq(...)
6970 // in order to resolve an overloading ambiguity.
6971 //
6972 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
6973 // or Matcher<T>(x), but more readable than the latter.
6974 //
6975 // We could define similar monomorphic matchers for other comparison
6976 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
6977 // it yet as those are used much less than Eq() in practice. A user
6978 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
6979 // for example.
6980 template <typename Lhs, typename Rhs>
6981 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
6982
6983 // Creates a polymorphic matcher that matches anything >= x.
6984 template <typename Rhs>
6985 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
6986 return internal::GeMatcher<Rhs>(x);
6987 }
6988
6989 // Creates a polymorphic matcher that matches anything > x.
6990 template <typename Rhs>
6991 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
6992 return internal::GtMatcher<Rhs>(x);
6993 }
6994
6995 // Creates a polymorphic matcher that matches anything <= x.
6996 template <typename Rhs>
6997 inline internal::LeMatcher<Rhs> Le(Rhs x) {
6998 return internal::LeMatcher<Rhs>(x);
6999 }
7000
7001 // Creates a polymorphic matcher that matches anything < x.
7002 template <typename Rhs>
7003 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
7004 return internal::LtMatcher<Rhs>(x);
7005 }
7006
7007 // Creates a polymorphic matcher that matches anything != x.
7008 template <typename Rhs>
7009 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
7010 return internal::NeMatcher<Rhs>(x);
7011 }
7012 } // namespace testing
7013
7014 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
7015
7016 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
7017
7018 #include <stdio.h>
7019 #include <memory>
7020
7021 namespace testing {
7022 namespace internal {
7023
7024 GTEST_DECLARE_string_(internal_run_death_test);
7025
7026 // Names of the flags (needed for parsing Google Test flags).
7027 const char kDeathTestStyleFlag[] = "death_test_style";
7028 const char kDeathTestUseFork[] = "death_test_use_fork";
7029 const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
7030
7031 #if GTEST_HAS_DEATH_TEST
7032
7033 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
7034 /* class A needs to have dll-interface to be used by clients of class B */)
7035
7036 // DeathTest is a class that hides much of the complexity of the
7037 // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
7038 // returns a concrete class that depends on the prevailing death test
7039 // style, as defined by the --gtest_death_test_style and/or
7040 // --gtest_internal_run_death_test flags.
7041
7042 // In describing the results of death tests, these terms are used with
7043 // the corresponding definitions:
7044 //
7045 // exit status: The integer exit information in the format specified
7046 // by wait(2)
7047 // exit code: The integer code passed to exit(3), _exit(2), or
7048 // returned from main()
7049 class GTEST_API_ DeathTest {
7050 public:
7051 // Create returns false if there was an error determining the
7052 // appropriate action to take for the current death test; for example,
7053 // if the gtest_death_test_style flag is set to an invalid value.
7054 // The LastMessage method will return a more detailed message in that
7055 // case. Otherwise, the DeathTest pointer pointed to by the "test"
7056 // argument is set. If the death test should be skipped, the pointer
7057 // is set to NULL; otherwise, it is set to the address of a new concrete
7058 // DeathTest object that controls the execution of the current test.
7059 static bool Create(const char* statement, Matcher<const std::string&> matcher,
7060 const char* file, int line, DeathTest** test);
7061 DeathTest();
7062 virtual ~DeathTest() { }
7063
7064 // A helper class that aborts a death test when it's deleted.
7065 class ReturnSentinel {
7066 public:
7067 explicit ReturnSentinel(DeathTest* test) : test_(test) { }
7068 ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
7069 private:
7070 DeathTest* const test_;
7071 GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
7072 } GTEST_ATTRIBUTE_UNUSED_;
7073
7074 // An enumeration of possible roles that may be taken when a death
7075 // test is encountered. EXECUTE means that the death test logic should
7076 // be executed immediately. OVERSEE means that the program should prepare
7077 // the appropriate environment for a child process to execute the death
7078 // test, then wait for it to complete.
7079 enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
7080
7081 // An enumeration of the three reasons that a test might be aborted.
7082 enum AbortReason {
7083 TEST_ENCOUNTERED_RETURN_STATEMENT,
7084 TEST_THREW_EXCEPTION,
7085 TEST_DID_NOT_DIE
7086 };
7087
7088 // Assumes one of the above roles.
7089 virtual TestRole AssumeRole() = 0;
7090
7091 // Waits for the death test to finish and returns its status.
7092 virtual int Wait() = 0;
7093
7094 // Returns true if the death test passed; that is, the test process
7095 // exited during the test, its exit status matches a user-supplied
7096 // predicate, and its stderr output matches a user-supplied regular
7097 // expression.
7098 // The user-supplied predicate may be a macro expression rather
7099 // than a function pointer or functor, or else Wait and Passed could
7100 // be combined.
7101 virtual bool Passed(bool exit_status_ok) = 0;
7102
7103 // Signals that the death test did not die as expected.
7104 virtual void Abort(AbortReason reason) = 0;
7105
7106 // Returns a human-readable outcome message regarding the outcome of
7107 // the last death test.
7108 static const char* LastMessage();
7109
7110 static void set_last_death_test_message(const std::string& message);
7111
7112 private:
7113 // A string containing a description of the outcome of the last death test.
7114 static std::string last_death_test_message_;
7115
7116 GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
7117 };
7118
7119 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
7120
7121 // Factory interface for death tests. May be mocked out for testing.
7122 class DeathTestFactory {
7123 public:
7124 virtual ~DeathTestFactory() { }
7125 virtual bool Create(const char* statement,
7126 Matcher<const std::string&> matcher, const char* file,
7127 int line, DeathTest** test) = 0;
7128 };
7129
7130 // A concrete DeathTestFactory implementation for normal use.
7131 class DefaultDeathTestFactory : public DeathTestFactory {
7132 public:
7133 bool Create(const char* statement, Matcher<const std::string&> matcher,
7134 const char* file, int line, DeathTest** test) override;
7135 };
7136
7137 // Returns true if exit_status describes a process that was terminated
7138 // by a signal, or exited normally with a nonzero exit code.
7139 GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
7140
7141 // A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
7142 // and interpreted as a regex (rather than an Eq matcher) for legacy
7143 // compatibility.
7144 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7145 ::testing::internal::RE regex) {
7146 return ContainsRegex(regex.pattern());
7147 }
7148 inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
7149 return ContainsRegex(regex);
7150 }
7151 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7152 const ::std::string& regex) {
7153 return ContainsRegex(regex);
7154 }
7155
7156 // If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
7157 // used directly.
7158 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7159 Matcher<const ::std::string&> matcher) {
7160 return matcher;
7161 }
7162
7163 // Traps C++ exceptions escaping statement and reports them as test
7164 // failures. Note that trapping SEH exceptions is not implemented here.
7165 # if GTEST_HAS_EXCEPTIONS
7166 # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
7167 try { \
7168 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7169 } catch (const ::std::exception& gtest_exception) { \
7170 fprintf(\
7171 stderr, \
7172 "\n%s: Caught std::exception-derived exception escaping the " \
7173 "death test statement. Exception message: %s\n", \
7174 ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
7175 gtest_exception.what()); \
7176 fflush(stderr); \
7177 death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
7178 } catch (...) { \
7179 death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
7180 }
7181
7182 # else
7183 # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
7184 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
7185
7186 # endif
7187
7188 // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
7189 // ASSERT_EXIT*, and EXPECT_EXIT*.
7190 #define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \
7191 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7192 if (::testing::internal::AlwaysTrue()) { \
7193 ::testing::internal::DeathTest* gtest_dt; \
7194 if (!::testing::internal::DeathTest::Create( \
7195 #statement, \
7196 ::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \
7197 __FILE__, __LINE__, >est_dt)) { \
7198 goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
7199 } \
7200 if (gtest_dt != nullptr) { \
7201 std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
7202 switch (gtest_dt->AssumeRole()) { \
7203 case ::testing::internal::DeathTest::OVERSEE_TEST: \
7204 if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
7205 goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
7206 } \
7207 break; \
7208 case ::testing::internal::DeathTest::EXECUTE_TEST: { \
7209 ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
7210 gtest_dt); \
7211 GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
7212 gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
7213 break; \
7214 } \
7215 } \
7216 } \
7217 } else \
7218 GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
7219 : fail(::testing::internal::DeathTest::LastMessage())
7220 // The symbol "fail" here expands to something into which a message
7221 // can be streamed.
7222
7223 // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
7224 // NDEBUG mode. In this case we need the statements to be executed and the macro
7225 // must accept a streamed message even though the message is never printed.
7226 // The regex object is not evaluated, but it is used to prevent "unused"
7227 // warnings and to avoid an expression that doesn't compile in debug mode.
7228 #define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
7229 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7230 if (::testing::internal::AlwaysTrue()) { \
7231 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7232 } else if (!::testing::internal::AlwaysTrue()) { \
7233 ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
7234 } else \
7235 ::testing::Message()
7236
7237 // A class representing the parsed contents of the
7238 // --gtest_internal_run_death_test flag, as it existed when
7239 // RUN_ALL_TESTS was called.
7240 class InternalRunDeathTestFlag {
7241 public:
7242 InternalRunDeathTestFlag(const std::string& a_file,
7243 int a_line,
7244 int an_index,
7245 int a_write_fd)
7246 : file_(a_file), line_(a_line), index_(an_index),
7247 write_fd_(a_write_fd) {}
7248
7249 ~InternalRunDeathTestFlag() {
7250 if (write_fd_ >= 0)
7251 posix::Close(write_fd_);
7252 }
7253
7254 const std::string& file() const { return file_; }
7255 int line() const { return line_; }
7256 int index() const { return index_; }
7257 int write_fd() const { return write_fd_; }
7258
7259 private:
7260 std::string file_;
7261 int line_;
7262 int index_;
7263 int write_fd_;
7264
7265 GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
7266 };
7267
7268 // Returns a newly created InternalRunDeathTestFlag object with fields
7269 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7270 // the flag is specified; otherwise returns NULL.
7271 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
7272
7273 #endif // GTEST_HAS_DEATH_TEST
7274
7275 } // namespace internal
7276 } // namespace testing
7277
7278 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
7279
7280 namespace testing {
7281
7282 // This flag controls the style of death tests. Valid values are "threadsafe",
7283 // meaning that the death test child process will re-execute the test binary
7284 // from the start, running only a single death test, or "fast",
7285 // meaning that the child process will execute the test logic immediately
7286 // after forking.
7287 GTEST_DECLARE_string_(death_test_style);
7288
7289 #if GTEST_HAS_DEATH_TEST
7290
7291 namespace internal {
7292
7293 // Returns a Boolean value indicating whether the caller is currently
7294 // executing in the context of the death test child process. Tools such as
7295 // Valgrind heap checkers may need this to modify their behavior in death
7296 // tests. IMPORTANT: This is an internal utility. Using it may break the
7297 // implementation of death tests. User code MUST NOT use it.
7298 GTEST_API_ bool InDeathTestChild();
7299
7300 } // namespace internal
7301
7302 // The following macros are useful for writing death tests.
7303
7304 // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
7305 // executed:
7306 //
7307 // 1. It generates a warning if there is more than one active
7308 // thread. This is because it's safe to fork() or clone() only
7309 // when there is a single thread.
7310 //
7311 // 2. The parent process clone()s a sub-process and runs the death
7312 // test in it; the sub-process exits with code 0 at the end of the
7313 // death test, if it hasn't exited already.
7314 //
7315 // 3. The parent process waits for the sub-process to terminate.
7316 //
7317 // 4. The parent process checks the exit code and error message of
7318 // the sub-process.
7319 //
7320 // Examples:
7321 //
7322 // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
7323 // for (int i = 0; i < 5; i++) {
7324 // EXPECT_DEATH(server.ProcessRequest(i),
7325 // "Invalid request .* in ProcessRequest()")
7326 // << "Failed to die on request " << i;
7327 // }
7328 //
7329 // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
7330 //
7331 // bool KilledBySIGHUP(int exit_code) {
7332 // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
7333 // }
7334 //
7335 // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
7336 //
7337 // The final parameter to each of these macros is a matcher applied to any data
7338 // the sub-process wrote to stderr. For compatibility with existing tests, a
7339 // bare string is interpreted as a regular expression matcher.
7340 //
7341 // On the regular expressions used in death tests:
7342 //
7343 // GOOGLETEST_CM0005 DO NOT DELETE
7344 // On POSIX-compliant systems (*nix), we use the <regex.h> library,
7345 // which uses the POSIX extended regex syntax.
7346 //
7347 // On other platforms (e.g. Windows or Mac), we only support a simple regex
7348 // syntax implemented as part of Google Test. This limited
7349 // implementation should be enough most of the time when writing
7350 // death tests; though it lacks many features you can find in PCRE
7351 // or POSIX extended regex syntax. For example, we don't support
7352 // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
7353 // repetition count ("x{5,7}"), among others.
7354 //
7355 // Below is the syntax that we do support. We chose it to be a
7356 // subset of both PCRE and POSIX extended regex, so it's easy to
7357 // learn wherever you come from. In the following: 'A' denotes a
7358 // literal character, period (.), or a single \\ escape sequence;
7359 // 'x' and 'y' denote regular expressions; 'm' and 'n' are for
7360 // natural numbers.
7361 //
7362 // c matches any literal character c
7363 // \\d matches any decimal digit
7364 // \\D matches any character that's not a decimal digit
7365 // \\f matches \f
7366 // \\n matches \n
7367 // \\r matches \r
7368 // \\s matches any ASCII whitespace, including \n
7369 // \\S matches any character that's not a whitespace
7370 // \\t matches \t
7371 // \\v matches \v
7372 // \\w matches any letter, _, or decimal digit
7373 // \\W matches any character that \\w doesn't match
7374 // \\c matches any literal character c, which must be a punctuation
7375 // . matches any single character except \n
7376 // A? matches 0 or 1 occurrences of A
7377 // A* matches 0 or many occurrences of A
7378 // A+ matches 1 or many occurrences of A
7379 // ^ matches the beginning of a string (not that of each line)
7380 // $ matches the end of a string (not that of each line)
7381 // xy matches x followed by y
7382 //
7383 // If you accidentally use PCRE or POSIX extended regex features
7384 // not implemented by us, you will get a run-time failure. In that
7385 // case, please try to rewrite your regular expression within the
7386 // above syntax.
7387 //
7388 // This implementation is *not* meant to be as highly tuned or robust
7389 // as a compiled regex library, but should perform well enough for a
7390 // death test, which already incurs significant overhead by launching
7391 // a child process.
7392 //
7393 // Known caveats:
7394 //
7395 // A "threadsafe" style death test obtains the path to the test
7396 // program from argv[0] and re-executes it in the sub-process. For
7397 // simplicity, the current implementation doesn't search the PATH
7398 // when launching the sub-process. This means that the user must
7399 // invoke the test program via a path that contains at least one
7400 // path separator (e.g. path/to/foo_test and
7401 // /absolute/path/to/bar_test are fine, but foo_test is not). This
7402 // is rarely a problem as people usually don't put the test binary
7403 // directory in PATH.
7404 //
7405
7406 // Asserts that a given `statement` causes the program to exit, with an
7407 // integer exit status that satisfies `predicate`, and emitting error output
7408 // that matches `matcher`.
7409 # define ASSERT_EXIT(statement, predicate, matcher) \
7410 GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)
7411
7412 // Like `ASSERT_EXIT`, but continues on to successive tests in the
7413 // test suite, if any:
7414 # define EXPECT_EXIT(statement, predicate, matcher) \
7415 GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)
7416
7417 // Asserts that a given `statement` causes the program to exit, either by
7418 // explicitly exiting with a nonzero exit code or being killed by a
7419 // signal, and emitting error output that matches `matcher`.
7420 # define ASSERT_DEATH(statement, matcher) \
7421 ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
7422
7423 // Like `ASSERT_DEATH`, but continues on to successive tests in the
7424 // test suite, if any:
7425 # define EXPECT_DEATH(statement, matcher) \
7426 EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
7427
7428 // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
7429
7430 // Tests that an exit code describes a normal exit with a given exit code.
7431 class GTEST_API_ ExitedWithCode {
7432 public:
7433 explicit ExitedWithCode(int exit_code);
7434 ExitedWithCode(const ExitedWithCode&) = default;
7435 void operator=(const ExitedWithCode& other) = delete;
7436 bool operator()(int exit_status) const;
7437 private:
7438 const int exit_code_;
7439 };
7440
7441 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7442 // Tests that an exit code describes an exit due to termination by a
7443 // given signal.
7444 // GOOGLETEST_CM0006 DO NOT DELETE
7445 class GTEST_API_ KilledBySignal {
7446 public:
7447 explicit KilledBySignal(int signum);
7448 bool operator()(int exit_status) const;
7449 private:
7450 const int signum_;
7451 };
7452 # endif // !GTEST_OS_WINDOWS
7453
7454 // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
7455 // The death testing framework causes this to have interesting semantics,
7456 // since the sideeffects of the call are only visible in opt mode, and not
7457 // in debug mode.
7458 //
7459 // In practice, this can be used to test functions that utilize the
7460 // LOG(DFATAL) macro using the following style:
7461 //
7462 // int DieInDebugOr12(int* sideeffect) {
7463 // if (sideeffect) {
7464 // *sideeffect = 12;
7465 // }
7466 // LOG(DFATAL) << "death";
7467 // return 12;
7468 // }
7469 //
7470 // TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
7471 // int sideeffect = 0;
7472 // // Only asserts in dbg.
7473 // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
7474 //
7475 // #ifdef NDEBUG
7476 // // opt-mode has sideeffect visible.
7477 // EXPECT_EQ(12, sideeffect);
7478 // #else
7479 // // dbg-mode no visible sideeffect.
7480 // EXPECT_EQ(0, sideeffect);
7481 // #endif
7482 // }
7483 //
7484 // This will assert that DieInDebugReturn12InOpt() crashes in debug
7485 // mode, usually due to a DCHECK or LOG(DFATAL), but returns the
7486 // appropriate fallback value (12 in this case) in opt mode. If you
7487 // need to test that a function has appropriate side-effects in opt
7488 // mode, include assertions against the side-effects. A general
7489 // pattern for this is:
7490 //
7491 // EXPECT_DEBUG_DEATH({
7492 // // Side-effects here will have an effect after this statement in
7493 // // opt mode, but none in debug mode.
7494 // EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
7495 // }, "death");
7496 //
7497 # ifdef NDEBUG
7498
7499 # define EXPECT_DEBUG_DEATH(statement, regex) \
7500 GTEST_EXECUTE_STATEMENT_(statement, regex)
7501
7502 # define ASSERT_DEBUG_DEATH(statement, regex) \
7503 GTEST_EXECUTE_STATEMENT_(statement, regex)
7504
7505 # else
7506
7507 # define EXPECT_DEBUG_DEATH(statement, regex) \
7508 EXPECT_DEATH(statement, regex)
7509
7510 # define ASSERT_DEBUG_DEATH(statement, regex) \
7511 ASSERT_DEATH(statement, regex)
7512
7513 # endif // NDEBUG for EXPECT_DEBUG_DEATH
7514 #endif // GTEST_HAS_DEATH_TEST
7515
7516 // This macro is used for implementing macros such as
7517 // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
7518 // death tests are not supported. Those macros must compile on such systems
7519 // if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
7520 // on systems that support death tests. This allows one to write such a macro on
7521 // a system that does not support death tests and be sure that it will compile
7522 // on a death-test supporting system. It is exposed publicly so that systems
7523 // that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
7524 // can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
7525 // ASSERT_DEATH_IF_SUPPORTED.
7526 //
7527 // Parameters:
7528 // statement - A statement that a macro such as EXPECT_DEATH would test
7529 // for program termination. This macro has to make sure this
7530 // statement is compiled but not executed, to ensure that
7531 // EXPECT_DEATH_IF_SUPPORTED compiles with a certain
7532 // parameter if and only if EXPECT_DEATH compiles with it.
7533 // regex - A regex that a macro such as EXPECT_DEATH would use to test
7534 // the output of statement. This parameter has to be
7535 // compiled but not evaluated by this macro, to ensure that
7536 // this macro only accepts expressions that a macro such as
7537 // EXPECT_DEATH would accept.
7538 // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
7539 // and a return statement for ASSERT_DEATH_IF_SUPPORTED.
7540 // This ensures that ASSERT_DEATH_IF_SUPPORTED will not
7541 // compile inside functions where ASSERT_DEATH doesn't
7542 // compile.
7543 //
7544 // The branch that has an always false condition is used to ensure that
7545 // statement and regex are compiled (and thus syntactically correct) but
7546 // never executed. The unreachable code macro protects the terminator
7547 // statement from generating an 'unreachable code' warning in case
7548 // statement unconditionally returns or throws. The Message constructor at
7549 // the end allows the syntax of streaming additional messages into the
7550 // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
7551 # define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
7552 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7553 if (::testing::internal::AlwaysTrue()) { \
7554 GTEST_LOG_(WARNING) \
7555 << "Death tests are not supported on this platform.\n" \
7556 << "Statement '" #statement "' cannot be verified."; \
7557 } else if (::testing::internal::AlwaysFalse()) { \
7558 ::testing::internal::RE::PartialMatch(".*", (regex)); \
7559 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7560 terminator; \
7561 } else \
7562 ::testing::Message()
7563
7564 // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
7565 // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
7566 // death tests are supported; otherwise they just issue a warning. This is
7567 // useful when you are combining death test assertions with normal test
7568 // assertions in one test.
7569 #if GTEST_HAS_DEATH_TEST
7570 # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
7571 EXPECT_DEATH(statement, regex)
7572 # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
7573 ASSERT_DEATH(statement, regex)
7574 #else
7575 # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
7576 GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
7577 # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
7578 GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
7579 #endif
7580
7581 } // namespace testing
7582
7583 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
7584 // Copyright 2008, Google Inc.
7585 // All rights reserved.
7586 //
7587 // Redistribution and use in source and binary forms, with or without
7588 // modification, are permitted provided that the following conditions are
7589 // met:
7590 //
7591 // * Redistributions of source code must retain the above copyright
7592 // notice, this list of conditions and the following disclaimer.
7593 // * Redistributions in binary form must reproduce the above
7594 // copyright notice, this list of conditions and the following disclaimer
7595 // in the documentation and/or other materials provided with the
7596 // distribution.
7597 // * Neither the name of Google Inc. nor the names of its
7598 // contributors may be used to endorse or promote products derived from
7599 // this software without specific prior written permission.
7600 //
7601 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7602 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7603 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7604 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7605 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7606 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7607 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7608 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7609 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7610 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7611 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7612 //
7613 // Macros and functions for implementing parameterized tests
7614 // in Google C++ Testing and Mocking Framework (Google Test)
7615 //
7616 // GOOGLETEST_CM0001 DO NOT DELETE
7617 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
7618 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
7619
7620 // Value-parameterized tests allow you to test your code with different
7621 // parameters without writing multiple copies of the same test.
7622 //
7623 // Here is how you use value-parameterized tests:
7624
7625 #if 0
7626
7627 // To write value-parameterized tests, first you should define a fixture
7628 // class. It is usually derived from testing::TestWithParam<T> (see below for
7629 // another inheritance scheme that's sometimes useful in more complicated
7630 // class hierarchies), where the type of your parameter values.
7631 // TestWithParam<T> is itself derived from testing::Test. T can be any
7632 // copyable type. If it's a raw pointer, you are responsible for managing the
7633 // lifespan of the pointed values.
7634
7635 class FooTest : public ::testing::TestWithParam<const char*> {
7636 // You can implement all the usual class fixture members here.
7637 };
7638
7639 // Then, use the TEST_P macro to define as many parameterized tests
7640 // for this fixture as you want. The _P suffix is for "parameterized"
7641 // or "pattern", whichever you prefer to think.
7642
7643 TEST_P(FooTest, DoesBlah) {
7644 // Inside a test, access the test parameter with the GetParam() method
7645 // of the TestWithParam<T> class:
7646 EXPECT_TRUE(foo.Blah(GetParam()));
7647 ...
7648 }
7649
7650 TEST_P(FooTest, HasBlahBlah) {
7651 ...
7652 }
7653
7654 // Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test
7655 // case with any set of parameters you want. Google Test defines a number
7656 // of functions for generating test parameters. They return what we call
7657 // (surprise!) parameter generators. Here is a summary of them, which
7658 // are all in the testing namespace:
7659 //
7660 //
7661 // Range(begin, end [, step]) - Yields values {begin, begin+step,
7662 // begin+step+step, ...}. The values do not
7663 // include end. step defaults to 1.
7664 // Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}.
7665 // ValuesIn(container) - Yields values from a C-style array, an STL
7666 // ValuesIn(begin,end) container, or an iterator range [begin, end).
7667 // Bool() - Yields sequence {false, true}.
7668 // Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product
7669 // for the math savvy) of the values generated
7670 // by the N generators.
7671 //
7672 // For more details, see comments at the definitions of these functions below
7673 // in this file.
7674 //
7675 // The following statement will instantiate tests from the FooTest test suite
7676 // each with parameter values "meeny", "miny", and "moe".
7677
7678 INSTANTIATE_TEST_SUITE_P(InstantiationName,
7679 FooTest,
7680 Values("meeny", "miny", "moe"));
7681
7682 // To distinguish different instances of the pattern, (yes, you
7683 // can instantiate it more than once) the first argument to the
7684 // INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
7685 // actual test suite name. Remember to pick unique prefixes for different
7686 // instantiations. The tests from the instantiation above will have
7687 // these names:
7688 //
7689 // * InstantiationName/FooTest.DoesBlah/0 for "meeny"
7690 // * InstantiationName/FooTest.DoesBlah/1 for "miny"
7691 // * InstantiationName/FooTest.DoesBlah/2 for "moe"
7692 // * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
7693 // * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
7694 // * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
7695 //
7696 // You can use these names in --gtest_filter.
7697 //
7698 // This statement will instantiate all tests from FooTest again, each
7699 // with parameter values "cat" and "dog":
7700
7701 const char* pets[] = {"cat", "dog"};
7702 INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
7703
7704 // The tests from the instantiation above will have these names:
7705 //
7706 // * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
7707 // * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
7708 // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
7709 // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
7710 //
7711 // Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests
7712 // in the given test suite, whether their definitions come before or
7713 // AFTER the INSTANTIATE_TEST_SUITE_P statement.
7714 //
7715 // Please also note that generator expressions (including parameters to the
7716 // generators) are evaluated in InitGoogleTest(), after main() has started.
7717 // This allows the user on one hand, to adjust generator parameters in order
7718 // to dynamically determine a set of tests to run and on the other hand,
7719 // give the user a chance to inspect the generated tests with Google Test
7720 // reflection API before RUN_ALL_TESTS() is executed.
7721 //
7722 // You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
7723 // for more examples.
7724 //
7725 // In the future, we plan to publish the API for defining new parameter
7726 // generators. But for now this interface remains part of the internal
7727 // implementation and is subject to change.
7728 //
7729 //
7730 // A parameterized test fixture must be derived from testing::Test and from
7731 // testing::WithParamInterface<T>, where T is the type of the parameter
7732 // values. Inheriting from TestWithParam<T> satisfies that requirement because
7733 // TestWithParam<T> inherits from both Test and WithParamInterface. In more
7734 // complicated hierarchies, however, it is occasionally useful to inherit
7735 // separately from Test and WithParamInterface. For example:
7736
7737 class BaseTest : public ::testing::Test {
7738 // You can inherit all the usual members for a non-parameterized test
7739 // fixture here.
7740 };
7741
7742 class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
7743 // The usual test fixture members go here too.
7744 };
7745
7746 TEST_F(BaseTest, HasFoo) {
7747 // This is an ordinary non-parameterized test.
7748 }
7749
7750 TEST_P(DerivedTest, DoesBlah) {
7751 // GetParam works just the same here as if you inherit from TestWithParam.
7752 EXPECT_TRUE(foo.Blah(GetParam()));
7753 }
7754
7755 #endif // 0
7756
7757 #include <iterator>
7758 #include <utility>
7759
7760 // Copyright 2008 Google Inc.
7761 // All Rights Reserved.
7762 //
7763 // Redistribution and use in source and binary forms, with or without
7764 // modification, are permitted provided that the following conditions are
7765 // met:
7766 //
7767 // * Redistributions of source code must retain the above copyright
7768 // notice, this list of conditions and the following disclaimer.
7769 // * Redistributions in binary form must reproduce the above
7770 // copyright notice, this list of conditions and the following disclaimer
7771 // in the documentation and/or other materials provided with the
7772 // distribution.
7773 // * Neither the name of Google Inc. nor the names of its
7774 // contributors may be used to endorse or promote products derived from
7775 // this software without specific prior written permission.
7776 //
7777 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7778 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7779 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7780 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7781 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7782 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7783 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7784 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7785 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7786 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7787 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7788
7789
7790 // Type and function utilities for implementing parameterized tests.
7791
7792 // GOOGLETEST_CM0001 DO NOT DELETE
7793
7794 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
7795 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
7796
7797 #include <ctype.h>
7798
7799 #include <cassert>
7800 #include <iterator>
7801 #include <memory>
7802 #include <set>
7803 #include <tuple>
7804 #include <type_traits>
7805 #include <utility>
7806 #include <vector>
7807
7808 // Copyright 2008, Google Inc.
7809 // All rights reserved.
7810 //
7811 // Redistribution and use in source and binary forms, with or without
7812 // modification, are permitted provided that the following conditions are
7813 // met:
7814 //
7815 // * Redistributions of source code must retain the above copyright
7816 // notice, this list of conditions and the following disclaimer.
7817 // * Redistributions in binary form must reproduce the above
7818 // copyright notice, this list of conditions and the following disclaimer
7819 // in the documentation and/or other materials provided with the
7820 // distribution.
7821 // * Neither the name of Google Inc. nor the names of its
7822 // contributors may be used to endorse or promote products derived from
7823 // this software without specific prior written permission.
7824 //
7825 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7826 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7827 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7828 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7829 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7830 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7831 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7832 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7833 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7834 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7835 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7836 //
7837 // GOOGLETEST_CM0001 DO NOT DELETE
7838
7839 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7840 #define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7841
7842 #include <iosfwd>
7843 #include <vector>
7844
7845 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
7846 /* class A needs to have dll-interface to be used by clients of class B */)
7847
7848 namespace testing {
7849
7850 // A copyable object representing the result of a test part (i.e. an
7851 // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
7852 //
7853 // Don't inherit from TestPartResult as its destructor is not virtual.
7854 class GTEST_API_ TestPartResult {
7855 public:
7856 // The possible outcomes of a test part (i.e. an assertion or an
7857 // explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
7858 enum Type {
7859 kSuccess, // Succeeded.
7860 kNonFatalFailure, // Failed but the test can continue.
7861 kFatalFailure, // Failed and the test should be terminated.
7862 kSkip // Skipped.
7863 };
7864
7865 // C'tor. TestPartResult does NOT have a default constructor.
7866 // Always use this constructor (with parameters) to create a
7867 // TestPartResult object.
7868 TestPartResult(Type a_type, const char* a_file_name, int a_line_number,
7869 const char* a_message)
7870 : type_(a_type),
7871 file_name_(a_file_name == nullptr ? "" : a_file_name),
7872 line_number_(a_line_number),
7873 summary_(ExtractSummary(a_message)),
7874 message_(a_message) {}
7875
7876 // Gets the outcome of the test part.
7877 Type type() const { return type_; }
7878
7879 // Gets the name of the source file where the test part took place, or
7880 // NULL if it's unknown.
7881 const char* file_name() const {
7882 return file_name_.empty() ? nullptr : file_name_.c_str();
7883 }
7884
7885 // Gets the line in the source file where the test part took place,
7886 // or -1 if it's unknown.
7887 int line_number() const { return line_number_; }
7888
7889 // Gets the summary of the failure message.
7890 const char* summary() const { return summary_.c_str(); }
7891
7892 // Gets the message associated with the test part.
7893 const char* message() const { return message_.c_str(); }
7894
7895 // Returns true if and only if the test part was skipped.
7896 bool skipped() const { return type_ == kSkip; }
7897
7898 // Returns true if and only if the test part passed.
7899 bool passed() const { return type_ == kSuccess; }
7900
7901 // Returns true if and only if the test part non-fatally failed.
7902 bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
7903
7904 // Returns true if and only if the test part fatally failed.
7905 bool fatally_failed() const { return type_ == kFatalFailure; }
7906
7907 // Returns true if and only if the test part failed.
7908 bool failed() const { return fatally_failed() || nonfatally_failed(); }
7909
7910 private:
7911 Type type_;
7912
7913 // Gets the summary of the failure message by omitting the stack
7914 // trace in it.
7915 static std::string ExtractSummary(const char* message);
7916
7917 // The name of the source file where the test part took place, or
7918 // "" if the source file is unknown.
7919 std::string file_name_;
7920 // The line in the source file where the test part took place, or -1
7921 // if the line number is unknown.
7922 int line_number_;
7923 std::string summary_; // The test failure summary.
7924 std::string message_; // The test failure message.
7925 };
7926
7927 // Prints a TestPartResult object.
7928 std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
7929
7930 // An array of TestPartResult objects.
7931 //
7932 // Don't inherit from TestPartResultArray as its destructor is not
7933 // virtual.
7934 class GTEST_API_ TestPartResultArray {
7935 public:
7936 TestPartResultArray() {}
7937
7938 // Appends the given TestPartResult to the array.
7939 void Append(const TestPartResult& result);
7940
7941 // Returns the TestPartResult at the given index (0-based).
7942 const TestPartResult& GetTestPartResult(int index) const;
7943
7944 // Returns the number of TestPartResult objects in the array.
7945 int size() const;
7946
7947 private:
7948 std::vector<TestPartResult> array_;
7949
7950 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
7951 };
7952
7953 // This interface knows how to report a test part result.
7954 class GTEST_API_ TestPartResultReporterInterface {
7955 public:
7956 virtual ~TestPartResultReporterInterface() {}
7957
7958 virtual void ReportTestPartResult(const TestPartResult& result) = 0;
7959 };
7960
7961 namespace internal {
7962
7963 // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
7964 // statement generates new fatal failures. To do so it registers itself as the
7965 // current test part result reporter. Besides checking if fatal failures were
7966 // reported, it only delegates the reporting to the former result reporter.
7967 // The original result reporter is restored in the destructor.
7968 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
7969 class GTEST_API_ HasNewFatalFailureHelper
7970 : public TestPartResultReporterInterface {
7971 public:
7972 HasNewFatalFailureHelper();
7973 ~HasNewFatalFailureHelper() override;
7974 void ReportTestPartResult(const TestPartResult& result) override;
7975 bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
7976 private:
7977 bool has_new_fatal_failure_;
7978 TestPartResultReporterInterface* original_reporter_;
7979
7980 GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
7981 };
7982
7983 } // namespace internal
7984
7985 } // namespace testing
7986
7987 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
7988
7989 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7990
7991 namespace testing {
7992 // Input to a parameterized test name generator, describing a test parameter.
7993 // Consists of the parameter value and the integer parameter index.
7994 template <class ParamType>
7995 struct TestParamInfo {
7996 TestParamInfo(const ParamType& a_param, size_t an_index) :
7997 param(a_param),
7998 index(an_index) {}
7999 ParamType param;
8000 size_t index;
8001 };
8002
8003 // A builtin parameterized test name generator which returns the result of
8004 // testing::PrintToString.
8005 struct PrintToStringParamName {
8006 template <class ParamType>
8007 std::string operator()(const TestParamInfo<ParamType>& info) const {
8008 return PrintToString(info.param);
8009 }
8010 };
8011
8012 namespace internal {
8013
8014 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8015 // Utility Functions
8016
8017 // Outputs a message explaining invalid registration of different
8018 // fixture class for the same test suite. This may happen when
8019 // TEST_P macro is used to define two tests with the same name
8020 // but in different namespaces.
8021 GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
8022 CodeLocation code_location);
8023
8024 template <typename> class ParamGeneratorInterface;
8025 template <typename> class ParamGenerator;
8026
8027 // Interface for iterating over elements provided by an implementation
8028 // of ParamGeneratorInterface<T>.
8029 template <typename T>
8030 class ParamIteratorInterface {
8031 public:
8032 virtual ~ParamIteratorInterface() {}
8033 // A pointer to the base generator instance.
8034 // Used only for the purposes of iterator comparison
8035 // to make sure that two iterators belong to the same generator.
8036 virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
8037 // Advances iterator to point to the next element
8038 // provided by the generator. The caller is responsible
8039 // for not calling Advance() on an iterator equal to
8040 // BaseGenerator()->End().
8041 virtual void Advance() = 0;
8042 // Clones the iterator object. Used for implementing copy semantics
8043 // of ParamIterator<T>.
8044 virtual ParamIteratorInterface* Clone() const = 0;
8045 // Dereferences the current iterator and provides (read-only) access
8046 // to the pointed value. It is the caller's responsibility not to call
8047 // Current() on an iterator equal to BaseGenerator()->End().
8048 // Used for implementing ParamGenerator<T>::operator*().
8049 virtual const T* Current() const = 0;
8050 // Determines whether the given iterator and other point to the same
8051 // element in the sequence generated by the generator.
8052 // Used for implementing ParamGenerator<T>::operator==().
8053 virtual bool Equals(const ParamIteratorInterface& other) const = 0;
8054 };
8055
8056 // Class iterating over elements provided by an implementation of
8057 // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
8058 // and implements the const forward iterator concept.
8059 template <typename T>
8060 class ParamIterator {
8061 public:
8062 typedef T value_type;
8063 typedef const T& reference;
8064 typedef ptrdiff_t difference_type;
8065
8066 // ParamIterator assumes ownership of the impl_ pointer.
8067 ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
8068 ParamIterator& operator=(const ParamIterator& other) {
8069 if (this != &other)
8070 impl_.reset(other.impl_->Clone());
8071 return *this;
8072 }
8073
8074 const T& operator*() const { return *impl_->Current(); }
8075 const T* operator->() const { return impl_->Current(); }
8076 // Prefix version of operator++.
8077 ParamIterator& operator++() {
8078 impl_->Advance();
8079 return *this;
8080 }
8081 // Postfix version of operator++.
8082 ParamIterator operator++(int /*unused*/) {
8083 ParamIteratorInterface<T>* clone = impl_->Clone();
8084 impl_->Advance();
8085 return ParamIterator(clone);
8086 }
8087 bool operator==(const ParamIterator& other) const {
8088 return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
8089 }
8090 bool operator!=(const ParamIterator& other) const {
8091 return !(*this == other);
8092 }
8093
8094 private:
8095 friend class ParamGenerator<T>;
8096 explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
8097 std::unique_ptr<ParamIteratorInterface<T> > impl_;
8098 };
8099
8100 // ParamGeneratorInterface<T> is the binary interface to access generators
8101 // defined in other translation units.
8102 template <typename T>
8103 class ParamGeneratorInterface {
8104 public:
8105 typedef T ParamType;
8106
8107 virtual ~ParamGeneratorInterface() {}
8108
8109 // Generator interface definition
8110 virtual ParamIteratorInterface<T>* Begin() const = 0;
8111 virtual ParamIteratorInterface<T>* End() const = 0;
8112 };
8113
8114 // Wraps ParamGeneratorInterface<T> and provides general generator syntax
8115 // compatible with the STL Container concept.
8116 // This class implements copy initialization semantics and the contained
8117 // ParamGeneratorInterface<T> instance is shared among all copies
8118 // of the original object. This is possible because that instance is immutable.
8119 template<typename T>
8120 class ParamGenerator {
8121 public:
8122 typedef ParamIterator<T> iterator;
8123
8124 explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
8125 ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
8126
8127 ParamGenerator& operator=(const ParamGenerator& other) {
8128 impl_ = other.impl_;
8129 return *this;
8130 }
8131
8132 iterator begin() const { return iterator(impl_->Begin()); }
8133 iterator end() const { return iterator(impl_->End()); }
8134
8135 private:
8136 std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
8137 };
8138
8139 // Generates values from a range of two comparable values. Can be used to
8140 // generate sequences of user-defined types that implement operator+() and
8141 // operator<().
8142 // This class is used in the Range() function.
8143 template <typename T, typename IncrementT>
8144 class RangeGenerator : public ParamGeneratorInterface<T> {
8145 public:
8146 RangeGenerator(T begin, T end, IncrementT step)
8147 : begin_(begin), end_(end),
8148 step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
8149 ~RangeGenerator() override {}
8150
8151 ParamIteratorInterface<T>* Begin() const override {
8152 return new Iterator(this, begin_, 0, step_);
8153 }
8154 ParamIteratorInterface<T>* End() const override {
8155 return new Iterator(this, end_, end_index_, step_);
8156 }
8157
8158 private:
8159 class Iterator : public ParamIteratorInterface<T> {
8160 public:
8161 Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
8162 IncrementT step)
8163 : base_(base), value_(value), index_(index), step_(step) {}
8164 ~Iterator() override {}
8165
8166 const ParamGeneratorInterface<T>* BaseGenerator() const override {
8167 return base_;
8168 }
8169 void Advance() override {
8170 value_ = static_cast<T>(value_ + step_);
8171 index_++;
8172 }
8173 ParamIteratorInterface<T>* Clone() const override {
8174 return new Iterator(*this);
8175 }
8176 const T* Current() const override { return &value_; }
8177 bool Equals(const ParamIteratorInterface<T>& other) const override {
8178 // Having the same base generator guarantees that the other
8179 // iterator is of the same type and we can downcast.
8180 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8181 << "The program attempted to compare iterators "
8182 << "from different generators." << std::endl;
8183 const int other_index =
8184 CheckedDowncastToActualType<const Iterator>(&other)->index_;
8185 return index_ == other_index;
8186 }
8187
8188 private:
8189 Iterator(const Iterator& other)
8190 : ParamIteratorInterface<T>(),
8191 base_(other.base_), value_(other.value_), index_(other.index_),
8192 step_(other.step_) {}
8193
8194 // No implementation - assignment is unsupported.
8195 void operator=(const Iterator& other);
8196
8197 const ParamGeneratorInterface<T>* const base_;
8198 T value_;
8199 int index_;
8200 const IncrementT step_;
8201 }; // class RangeGenerator::Iterator
8202
8203 static int CalculateEndIndex(const T& begin,
8204 const T& end,
8205 const IncrementT& step) {
8206 int end_index = 0;
8207 for (T i = begin; i < end; i = static_cast<T>(i + step))
8208 end_index++;
8209 return end_index;
8210 }
8211
8212 // No implementation - assignment is unsupported.
8213 void operator=(const RangeGenerator& other);
8214
8215 const T begin_;
8216 const T end_;
8217 const IncrementT step_;
8218 // The index for the end() iterator. All the elements in the generated
8219 // sequence are indexed (0-based) to aid iterator comparison.
8220 const int end_index_;
8221 }; // class RangeGenerator
8222
8223
8224 // Generates values from a pair of STL-style iterators. Used in the
8225 // ValuesIn() function. The elements are copied from the source range
8226 // since the source can be located on the stack, and the generator
8227 // is likely to persist beyond that stack frame.
8228 template <typename T>
8229 class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
8230 public:
8231 template <typename ForwardIterator>
8232 ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
8233 : container_(begin, end) {}
8234 ~ValuesInIteratorRangeGenerator() override {}
8235
8236 ParamIteratorInterface<T>* Begin() const override {
8237 return new Iterator(this, container_.begin());
8238 }
8239 ParamIteratorInterface<T>* End() const override {
8240 return new Iterator(this, container_.end());
8241 }
8242
8243 private:
8244 typedef typename ::std::vector<T> ContainerType;
8245
8246 class Iterator : public ParamIteratorInterface<T> {
8247 public:
8248 Iterator(const ParamGeneratorInterface<T>* base,
8249 typename ContainerType::const_iterator iterator)
8250 : base_(base), iterator_(iterator) {}
8251 ~Iterator() override {}
8252
8253 const ParamGeneratorInterface<T>* BaseGenerator() const override {
8254 return base_;
8255 }
8256 void Advance() override {
8257 ++iterator_;
8258 value_.reset();
8259 }
8260 ParamIteratorInterface<T>* Clone() const override {
8261 return new Iterator(*this);
8262 }
8263 // We need to use cached value referenced by iterator_ because *iterator_
8264 // can return a temporary object (and of type other then T), so just
8265 // having "return &*iterator_;" doesn't work.
8266 // value_ is updated here and not in Advance() because Advance()
8267 // can advance iterator_ beyond the end of the range, and we cannot
8268 // detect that fact. The client code, on the other hand, is
8269 // responsible for not calling Current() on an out-of-range iterator.
8270 const T* Current() const override {
8271 if (value_.get() == nullptr) value_.reset(new T(*iterator_));
8272 return value_.get();
8273 }
8274 bool Equals(const ParamIteratorInterface<T>& other) const override {
8275 // Having the same base generator guarantees that the other
8276 // iterator is of the same type and we can downcast.
8277 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8278 << "The program attempted to compare iterators "
8279 << "from different generators." << std::endl;
8280 return iterator_ ==
8281 CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
8282 }
8283
8284 private:
8285 Iterator(const Iterator& other)
8286 // The explicit constructor call suppresses a false warning
8287 // emitted by gcc when supplied with the -Wextra option.
8288 : ParamIteratorInterface<T>(),
8289 base_(other.base_),
8290 iterator_(other.iterator_) {}
8291
8292 const ParamGeneratorInterface<T>* const base_;
8293 typename ContainerType::const_iterator iterator_;
8294 // A cached value of *iterator_. We keep it here to allow access by
8295 // pointer in the wrapping iterator's operator->().
8296 // value_ needs to be mutable to be accessed in Current().
8297 // Use of std::unique_ptr helps manage cached value's lifetime,
8298 // which is bound by the lifespan of the iterator itself.
8299 mutable std::unique_ptr<const T> value_;
8300 }; // class ValuesInIteratorRangeGenerator::Iterator
8301
8302 // No implementation - assignment is unsupported.
8303 void operator=(const ValuesInIteratorRangeGenerator& other);
8304
8305 const ContainerType container_;
8306 }; // class ValuesInIteratorRangeGenerator
8307
8308 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8309 //
8310 // Default parameterized test name generator, returns a string containing the
8311 // integer test parameter index.
8312 template <class ParamType>
8313 std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
8314 Message name_stream;
8315 name_stream << info.index;
8316 return name_stream.GetString();
8317 }
8318
8319 template <typename T = int>
8320 void TestNotEmpty() {
8321 static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");
8322 }
8323 template <typename T = int>
8324 void TestNotEmpty(const T&) {}
8325
8326 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8327 //
8328 // Stores a parameter value and later creates tests parameterized with that
8329 // value.
8330 template <class TestClass>
8331 class ParameterizedTestFactory : public TestFactoryBase {
8332 public:
8333 typedef typename TestClass::ParamType ParamType;
8334 explicit ParameterizedTestFactory(ParamType parameter) :
8335 parameter_(parameter) {}
8336 Test* CreateTest() override {
8337 TestClass::SetParam(¶meter_);
8338 return new TestClass();
8339 }
8340
8341 private:
8342 const ParamType parameter_;
8343
8344 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
8345 };
8346
8347 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8348 //
8349 // TestMetaFactoryBase is a base class for meta-factories that create
8350 // test factories for passing into MakeAndRegisterTestInfo function.
8351 template <class ParamType>
8352 class TestMetaFactoryBase {
8353 public:
8354 virtual ~TestMetaFactoryBase() {}
8355
8356 virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
8357 };
8358
8359 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8360 //
8361 // TestMetaFactory creates test factories for passing into
8362 // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
8363 // ownership of test factory pointer, same factory object cannot be passed
8364 // into that method twice. But ParameterizedTestSuiteInfo is going to call
8365 // it for each Test/Parameter value combination. Thus it needs meta factory
8366 // creator class.
8367 template <class TestSuite>
8368 class TestMetaFactory
8369 : public TestMetaFactoryBase<typename TestSuite::ParamType> {
8370 public:
8371 using ParamType = typename TestSuite::ParamType;
8372
8373 TestMetaFactory() {}
8374
8375 TestFactoryBase* CreateTestFactory(ParamType parameter) override {
8376 return new ParameterizedTestFactory<TestSuite>(parameter);
8377 }
8378
8379 private:
8380 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
8381 };
8382
8383 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8384 //
8385 // ParameterizedTestSuiteInfoBase is a generic interface
8386 // to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase
8387 // accumulates test information provided by TEST_P macro invocations
8388 // and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations
8389 // and uses that information to register all resulting test instances
8390 // in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
8391 // a collection of pointers to the ParameterizedTestSuiteInfo objects
8392 // and calls RegisterTests() on each of them when asked.
8393 class ParameterizedTestSuiteInfoBase {
8394 public:
8395 virtual ~ParameterizedTestSuiteInfoBase() {}
8396
8397 // Base part of test suite name for display purposes.
8398 virtual const std::string& GetTestSuiteName() const = 0;
8399 // Test suite id to verify identity.
8400 virtual TypeId GetTestSuiteTypeId() const = 0;
8401 // UnitTest class invokes this method to register tests in this
8402 // test suite right before running them in RUN_ALL_TESTS macro.
8403 // This method should not be called more than once on any single
8404 // instance of a ParameterizedTestSuiteInfoBase derived class.
8405 virtual void RegisterTests() = 0;
8406
8407 protected:
8408 ParameterizedTestSuiteInfoBase() {}
8409
8410 private:
8411 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
8412 };
8413
8414 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8415 //
8416 // Report a the name of a test_suit as safe to ignore
8417 // as the side effect of construction of this type.
8418 struct GTEST_API_ MarkAsIgnored {
8419 explicit MarkAsIgnored(const char* test_suite);
8420 };
8421
8422 GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
8423 CodeLocation location, bool has_test_p);
8424
8425 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8426 //
8427 // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
8428 // macro invocations for a particular test suite and generators
8429 // obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that
8430 // test suite. It registers tests with all values generated by all
8431 // generators when asked.
8432 template <class TestSuite>
8433 class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
8434 public:
8435 // ParamType and GeneratorCreationFunc are private types but are required
8436 // for declarations of public methods AddTestPattern() and
8437 // AddTestSuiteInstantiation().
8438 using ParamType = typename TestSuite::ParamType;
8439 // A function that returns an instance of appropriate generator type.
8440 typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
8441 using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
8442
8443 explicit ParameterizedTestSuiteInfo(const char* name,
8444 CodeLocation code_location)
8445 : test_suite_name_(name), code_location_(code_location) {}
8446
8447 // Test suite base name for display purposes.
8448 const std::string& GetTestSuiteName() const override {
8449 return test_suite_name_;
8450 }
8451 // Test suite id to verify identity.
8452 TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
8453 // TEST_P macro uses AddTestPattern() to record information
8454 // about a single test in a LocalTestInfo structure.
8455 // test_suite_name is the base name of the test suite (without invocation
8456 // prefix). test_base_name is the name of an individual test without
8457 // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
8458 // test suite base name and DoBar is test base name.
8459 void AddTestPattern(const char* test_suite_name, const char* test_base_name,
8460 TestMetaFactoryBase<ParamType>* meta_factory,
8461 CodeLocation code_location) {
8462 tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
8463 test_suite_name, test_base_name, meta_factory, code_location)));
8464 }
8465 // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
8466 // about a generator.
8467 int AddTestSuiteInstantiation(const std::string& instantiation_name,
8468 GeneratorCreationFunc* func,
8469 ParamNameGeneratorFunc* name_func,
8470 const char* file, int line) {
8471 instantiations_.push_back(
8472 InstantiationInfo(instantiation_name, func, name_func, file, line));
8473 return 0; // Return value used only to run this method in namespace scope.
8474 }
8475 // UnitTest class invokes this method to register tests in this test suite
8476 // right before running tests in RUN_ALL_TESTS macro.
8477 // This method should not be called more than once on any single
8478 // instance of a ParameterizedTestSuiteInfoBase derived class.
8479 // UnitTest has a guard to prevent from calling this method more than once.
8480 void RegisterTests() override {
8481 bool generated_instantiations = false;
8482
8483 for (typename TestInfoContainer::iterator test_it = tests_.begin();
8484 test_it != tests_.end(); ++test_it) {
8485 std::shared_ptr<TestInfo> test_info = *test_it;
8486 for (typename InstantiationContainer::iterator gen_it =
8487 instantiations_.begin(); gen_it != instantiations_.end();
8488 ++gen_it) {
8489 const std::string& instantiation_name = gen_it->name;
8490 ParamGenerator<ParamType> generator((*gen_it->generator)());
8491 ParamNameGeneratorFunc* name_func = gen_it->name_func;
8492 const char* file = gen_it->file;
8493 int line = gen_it->line;
8494
8495 std::string test_suite_name;
8496 if ( !instantiation_name.empty() )
8497 test_suite_name = instantiation_name + "/";
8498 test_suite_name += test_info->test_suite_base_name;
8499
8500 size_t i = 0;
8501 std::set<std::string> test_param_names;
8502 for (typename ParamGenerator<ParamType>::iterator param_it =
8503 generator.begin();
8504 param_it != generator.end(); ++param_it, ++i) {
8505 generated_instantiations = true;
8506
8507 Message test_name_stream;
8508
8509 std::string param_name = name_func(
8510 TestParamInfo<ParamType>(*param_it, i));
8511
8512 GTEST_CHECK_(IsValidParamName(param_name))
8513 << "Parameterized test name '" << param_name
8514 << "' is invalid, in " << file
8515 << " line " << line << std::endl;
8516
8517 GTEST_CHECK_(test_param_names.count(param_name) == 0)
8518 << "Duplicate parameterized test name '" << param_name
8519 << "', in " << file << " line " << line << std::endl;
8520
8521 test_param_names.insert(param_name);
8522
8523 if (!test_info->test_base_name.empty()) {
8524 test_name_stream << test_info->test_base_name << "/";
8525 }
8526 test_name_stream << param_name;
8527 MakeAndRegisterTestInfo(
8528 test_suite_name.c_str(), test_name_stream.GetString().c_str(),
8529 nullptr, // No type parameter.
8530 PrintToString(*param_it).c_str(), test_info->code_location,
8531 GetTestSuiteTypeId(),
8532 SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
8533 SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
8534 test_info->test_meta_factory->CreateTestFactory(*param_it));
8535 } // for param_it
8536 } // for gen_it
8537 } // for test_it
8538
8539 if (!generated_instantiations) {
8540 // There are no generaotrs, or they all generate nothing ...
8541 InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
8542 !tests_.empty());
8543 }
8544 } // RegisterTests
8545
8546 private:
8547 // LocalTestInfo structure keeps information about a single test registered
8548 // with TEST_P macro.
8549 struct TestInfo {
8550 TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
8551 TestMetaFactoryBase<ParamType>* a_test_meta_factory,
8552 CodeLocation a_code_location)
8553 : test_suite_base_name(a_test_suite_base_name),
8554 test_base_name(a_test_base_name),
8555 test_meta_factory(a_test_meta_factory),
8556 code_location(a_code_location) {}
8557
8558 const std::string test_suite_base_name;
8559 const std::string test_base_name;
8560 const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
8561 const CodeLocation code_location;
8562 };
8563 using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
8564 // Records data received from INSTANTIATE_TEST_SUITE_P macros:
8565 // <Instantiation name, Sequence generator creation function,
8566 // Name generator function, Source file, Source line>
8567 struct InstantiationInfo {
8568 InstantiationInfo(const std::string &name_in,
8569 GeneratorCreationFunc* generator_in,
8570 ParamNameGeneratorFunc* name_func_in,
8571 const char* file_in,
8572 int line_in)
8573 : name(name_in),
8574 generator(generator_in),
8575 name_func(name_func_in),
8576 file(file_in),
8577 line(line_in) {}
8578
8579 std::string name;
8580 GeneratorCreationFunc* generator;
8581 ParamNameGeneratorFunc* name_func;
8582 const char* file;
8583 int line;
8584 };
8585 typedef ::std::vector<InstantiationInfo> InstantiationContainer;
8586
8587 static bool IsValidParamName(const std::string& name) {
8588 // Check for empty string
8589 if (name.empty())
8590 return false;
8591
8592 // Check for invalid characters
8593 for (std::string::size_type index = 0; index < name.size(); ++index) {
8594 if (!IsAlNum(name[index]) && name[index] != '_')
8595 return false;
8596 }
8597
8598 return true;
8599 }
8600
8601 const std::string test_suite_name_;
8602 CodeLocation code_location_;
8603 TestInfoContainer tests_;
8604 InstantiationContainer instantiations_;
8605
8606 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
8607 }; // class ParameterizedTestSuiteInfo
8608
8609 // Legacy API is deprecated but still available
8610 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8611 template <class TestCase>
8612 using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
8613 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8614
8615 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8616 //
8617 // ParameterizedTestSuiteRegistry contains a map of
8618 // ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
8619 // and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
8620 // ParameterizedTestSuiteInfo descriptors.
8621 class ParameterizedTestSuiteRegistry {
8622 public:
8623 ParameterizedTestSuiteRegistry() {}
8624 ~ParameterizedTestSuiteRegistry() {
8625 for (auto& test_suite_info : test_suite_infos_) {
8626 delete test_suite_info;
8627 }
8628 }
8629
8630 // Looks up or creates and returns a structure containing information about
8631 // tests and instantiations of a particular test suite.
8632 template <class TestSuite>
8633 ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
8634 const char* test_suite_name, CodeLocation code_location) {
8635 ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
8636 for (auto& test_suite_info : test_suite_infos_) {
8637 if (test_suite_info->GetTestSuiteName() == test_suite_name) {
8638 if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
8639 // Complain about incorrect usage of Google Test facilities
8640 // and terminate the program since we cannot guaranty correct
8641 // test suite setup and tear-down in this case.
8642 ReportInvalidTestSuiteType(test_suite_name, code_location);
8643 posix::Abort();
8644 } else {
8645 // At this point we are sure that the object we found is of the same
8646 // type we are looking for, so we downcast it to that type
8647 // without further checks.
8648 typed_test_info = CheckedDowncastToActualType<
8649 ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
8650 }
8651 break;
8652 }
8653 }
8654 if (typed_test_info == nullptr) {
8655 typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
8656 test_suite_name, code_location);
8657 test_suite_infos_.push_back(typed_test_info);
8658 }
8659 return typed_test_info;
8660 }
8661 void RegisterTests() {
8662 for (auto& test_suite_info : test_suite_infos_) {
8663 test_suite_info->RegisterTests();
8664 }
8665 }
8666 // Legacy API is deprecated but still available
8667 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8668 template <class TestCase>
8669 ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
8670 const char* test_case_name, CodeLocation code_location) {
8671 return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
8672 }
8673
8674 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8675
8676 private:
8677 using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
8678
8679 TestSuiteInfoContainer test_suite_infos_;
8680
8681 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
8682 };
8683
8684 // Keep track of what type-parameterized test suite are defined and
8685 // where as well as which are intatiated. This allows susequently
8686 // identifying suits that are defined but never used.
8687 class TypeParameterizedTestSuiteRegistry {
8688 public:
8689 // Add a suite definition
8690 void RegisterTestSuite(const char* test_suite_name,
8691 CodeLocation code_location);
8692
8693 // Add an instantiation of a suit.
8694 void RegisterInstantiation(const char* test_suite_name);
8695
8696 // For each suit repored as defined but not reported as instantiation,
8697 // emit a test that reports that fact (configurably, as an error).
8698 void CheckForInstantiations();
8699
8700 private:
8701 struct TypeParameterizedTestSuiteInfo {
8702 explicit TypeParameterizedTestSuiteInfo(CodeLocation c)
8703 : code_location(c), instantiated(false) {}
8704
8705 CodeLocation code_location;
8706 bool instantiated;
8707 };
8708
8709 std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;
8710 };
8711
8712 } // namespace internal
8713
8714 // Forward declarations of ValuesIn(), which is implemented in
8715 // include/gtest/gtest-param-test.h.
8716 template <class Container>
8717 internal::ParamGenerator<typename Container::value_type> ValuesIn(
8718 const Container& container);
8719
8720 namespace internal {
8721 // Used in the Values() function to provide polymorphic capabilities.
8722
8723 #ifdef _MSC_VER
8724 #pragma warning(push)
8725 #pragma warning(disable : 4100)
8726 #endif
8727
8728 template <typename... Ts>
8729 class ValueArray {
8730 public:
8731 explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
8732
8733 template <typename T>
8734 operator ParamGenerator<T>() const { // NOLINT
8735 return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
8736 }
8737
8738 private:
8739 template <typename T, size_t... I>
8740 std::vector<T> MakeVector(IndexSequence<I...>) const {
8741 return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
8742 }
8743
8744 FlatTuple<Ts...> v_;
8745 };
8746
8747 #ifdef _MSC_VER
8748 #pragma warning(pop)
8749 #endif
8750
8751 template <typename... T>
8752 class CartesianProductGenerator
8753 : public ParamGeneratorInterface<::std::tuple<T...>> {
8754 public:
8755 typedef ::std::tuple<T...> ParamType;
8756
8757 CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
8758 : generators_(g) {}
8759 ~CartesianProductGenerator() override {}
8760
8761 ParamIteratorInterface<ParamType>* Begin() const override {
8762 return new Iterator(this, generators_, false);
8763 }
8764 ParamIteratorInterface<ParamType>* End() const override {
8765 return new Iterator(this, generators_, true);
8766 }
8767
8768 private:
8769 template <class I>
8770 class IteratorImpl;
8771 template <size_t... I>
8772 class IteratorImpl<IndexSequence<I...>>
8773 : public ParamIteratorInterface<ParamType> {
8774 public:
8775 IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
8776 const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
8777 : base_(base),
8778 begin_(std::get<I>(generators).begin()...),
8779 end_(std::get<I>(generators).end()...),
8780 current_(is_end ? end_ : begin_) {
8781 ComputeCurrentValue();
8782 }
8783 ~IteratorImpl() override {}
8784
8785 const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
8786 return base_;
8787 }
8788 // Advance should not be called on beyond-of-range iterators
8789 // so no component iterators must be beyond end of range, either.
8790 void Advance() override {
8791 assert(!AtEnd());
8792 // Advance the last iterator.
8793 ++std::get<sizeof...(T) - 1>(current_);
8794 // if that reaches end, propagate that up.
8795 AdvanceIfEnd<sizeof...(T) - 1>();
8796 ComputeCurrentValue();
8797 }
8798 ParamIteratorInterface<ParamType>* Clone() const override {
8799 return new IteratorImpl(*this);
8800 }
8801
8802 const ParamType* Current() const override { return current_value_.get(); }
8803
8804 bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
8805 // Having the same base generator guarantees that the other
8806 // iterator is of the same type and we can downcast.
8807 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8808 << "The program attempted to compare iterators "
8809 << "from different generators." << std::endl;
8810 const IteratorImpl* typed_other =
8811 CheckedDowncastToActualType<const IteratorImpl>(&other);
8812
8813 // We must report iterators equal if they both point beyond their
8814 // respective ranges. That can happen in a variety of fashions,
8815 // so we have to consult AtEnd().
8816 if (AtEnd() && typed_other->AtEnd()) return true;
8817
8818 bool same = true;
8819 bool dummy[] = {
8820 (same = same && std::get<I>(current_) ==
8821 std::get<I>(typed_other->current_))...};
8822 (void)dummy;
8823 return same;
8824 }
8825
8826 private:
8827 template <size_t ThisI>
8828 void AdvanceIfEnd() {
8829 if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
8830
8831 bool last = ThisI == 0;
8832 if (last) {
8833 // We are done. Nothing else to propagate.
8834 return;
8835 }
8836
8837 constexpr size_t NextI = ThisI - (ThisI != 0);
8838 std::get<ThisI>(current_) = std::get<ThisI>(begin_);
8839 ++std::get<NextI>(current_);
8840 AdvanceIfEnd<NextI>();
8841 }
8842
8843 void ComputeCurrentValue() {
8844 if (!AtEnd())
8845 current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
8846 }
8847 bool AtEnd() const {
8848 bool at_end = false;
8849 bool dummy[] = {
8850 (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
8851 (void)dummy;
8852 return at_end;
8853 }
8854
8855 const ParamGeneratorInterface<ParamType>* const base_;
8856 std::tuple<typename ParamGenerator<T>::iterator...> begin_;
8857 std::tuple<typename ParamGenerator<T>::iterator...> end_;
8858 std::tuple<typename ParamGenerator<T>::iterator...> current_;
8859 std::shared_ptr<ParamType> current_value_;
8860 };
8861
8862 using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
8863
8864 std::tuple<ParamGenerator<T>...> generators_;
8865 };
8866
8867 template <class... Gen>
8868 class CartesianProductHolder {
8869 public:
8870 CartesianProductHolder(const Gen&... g) : generators_(g...) {}
8871 template <typename... T>
8872 operator ParamGenerator<::std::tuple<T...>>() const {
8873 return ParamGenerator<::std::tuple<T...>>(
8874 new CartesianProductGenerator<T...>(generators_));
8875 }
8876
8877 private:
8878 std::tuple<Gen...> generators_;
8879 };
8880
8881 } // namespace internal
8882 } // namespace testing
8883
8884 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
8885
8886 namespace testing {
8887
8888 // Functions producing parameter generators.
8889 //
8890 // Google Test uses these generators to produce parameters for value-
8891 // parameterized tests. When a parameterized test suite is instantiated
8892 // with a particular generator, Google Test creates and runs tests
8893 // for each element in the sequence produced by the generator.
8894 //
8895 // In the following sample, tests from test suite FooTest are instantiated
8896 // each three times with parameter values 3, 5, and 8:
8897 //
8898 // class FooTest : public TestWithParam<int> { ... };
8899 //
8900 // TEST_P(FooTest, TestThis) {
8901 // }
8902 // TEST_P(FooTest, TestThat) {
8903 // }
8904 // INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));
8905 //
8906
8907 // Range() returns generators providing sequences of values in a range.
8908 //
8909 // Synopsis:
8910 // Range(start, end)
8911 // - returns a generator producing a sequence of values {start, start+1,
8912 // start+2, ..., }.
8913 // Range(start, end, step)
8914 // - returns a generator producing a sequence of values {start, start+step,
8915 // start+step+step, ..., }.
8916 // Notes:
8917 // * The generated sequences never include end. For example, Range(1, 5)
8918 // returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
8919 // returns a generator producing {1, 3, 5, 7}.
8920 // * start and end must have the same type. That type may be any integral or
8921 // floating-point type or a user defined type satisfying these conditions:
8922 // * It must be assignable (have operator=() defined).
8923 // * It must have operator+() (operator+(int-compatible type) for
8924 // two-operand version).
8925 // * It must have operator<() defined.
8926 // Elements in the resulting sequences will also have that type.
8927 // * Condition start < end must be satisfied in order for resulting sequences
8928 // to contain any elements.
8929 //
8930 template <typename T, typename IncrementT>
8931 internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
8932 return internal::ParamGenerator<T>(
8933 new internal::RangeGenerator<T, IncrementT>(start, end, step));
8934 }
8935
8936 template <typename T>
8937 internal::ParamGenerator<T> Range(T start, T end) {
8938 return Range(start, end, 1);
8939 }
8940
8941 // ValuesIn() function allows generation of tests with parameters coming from
8942 // a container.
8943 //
8944 // Synopsis:
8945 // ValuesIn(const T (&array)[N])
8946 // - returns a generator producing sequences with elements from
8947 // a C-style array.
8948 // ValuesIn(const Container& container)
8949 // - returns a generator producing sequences with elements from
8950 // an STL-style container.
8951 // ValuesIn(Iterator begin, Iterator end)
8952 // - returns a generator producing sequences with elements from
8953 // a range [begin, end) defined by a pair of STL-style iterators. These
8954 // iterators can also be plain C pointers.
8955 //
8956 // Please note that ValuesIn copies the values from the containers
8957 // passed in and keeps them to generate tests in RUN_ALL_TESTS().
8958 //
8959 // Examples:
8960 //
8961 // This instantiates tests from test suite StringTest
8962 // each with C-string values of "foo", "bar", and "baz":
8963 //
8964 // const char* strings[] = {"foo", "bar", "baz"};
8965 // INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));
8966 //
8967 // This instantiates tests from test suite StlStringTest
8968 // each with STL strings with values "a" and "b":
8969 //
8970 // ::std::vector< ::std::string> GetParameterStrings() {
8971 // ::std::vector< ::std::string> v;
8972 // v.push_back("a");
8973 // v.push_back("b");
8974 // return v;
8975 // }
8976 //
8977 // INSTANTIATE_TEST_SUITE_P(CharSequence,
8978 // StlStringTest,
8979 // ValuesIn(GetParameterStrings()));
8980 //
8981 //
8982 // This will also instantiate tests from CharTest
8983 // each with parameter values 'a' and 'b':
8984 //
8985 // ::std::list<char> GetParameterChars() {
8986 // ::std::list<char> list;
8987 // list.push_back('a');
8988 // list.push_back('b');
8989 // return list;
8990 // }
8991 // ::std::list<char> l = GetParameterChars();
8992 // INSTANTIATE_TEST_SUITE_P(CharSequence2,
8993 // CharTest,
8994 // ValuesIn(l.begin(), l.end()));
8995 //
8996 template <typename ForwardIterator>
8997 internal::ParamGenerator<
8998 typename std::iterator_traits<ForwardIterator>::value_type>
8999 ValuesIn(ForwardIterator begin, ForwardIterator end) {
9000 typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;
9001 return internal::ParamGenerator<ParamType>(
9002 new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
9003 }
9004
9005 template <typename T, size_t N>
9006 internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
9007 return ValuesIn(array, array + N);
9008 }
9009
9010 template <class Container>
9011 internal::ParamGenerator<typename Container::value_type> ValuesIn(
9012 const Container& container) {
9013 return ValuesIn(container.begin(), container.end());
9014 }
9015
9016 // Values() allows generating tests from explicitly specified list of
9017 // parameters.
9018 //
9019 // Synopsis:
9020 // Values(T v1, T v2, ..., T vN)
9021 // - returns a generator producing sequences with elements v1, v2, ..., vN.
9022 //
9023 // For example, this instantiates tests from test suite BarTest each
9024 // with values "one", "two", and "three":
9025 //
9026 // INSTANTIATE_TEST_SUITE_P(NumSequence,
9027 // BarTest,
9028 // Values("one", "two", "three"));
9029 //
9030 // This instantiates tests from test suite BazTest each with values 1, 2, 3.5.
9031 // The exact type of values will depend on the type of parameter in BazTest.
9032 //
9033 // INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
9034 //
9035 //
9036 template <typename... T>
9037 internal::ValueArray<T...> Values(T... v) {
9038 return internal::ValueArray<T...>(std::move(v)...);
9039 }
9040
9041 // Bool() allows generating tests with parameters in a set of (false, true).
9042 //
9043 // Synopsis:
9044 // Bool()
9045 // - returns a generator producing sequences with elements {false, true}.
9046 //
9047 // It is useful when testing code that depends on Boolean flags. Combinations
9048 // of multiple flags can be tested when several Bool()'s are combined using
9049 // Combine() function.
9050 //
9051 // In the following example all tests in the test suite FlagDependentTest
9052 // will be instantiated twice with parameters false and true.
9053 //
9054 // class FlagDependentTest : public testing::TestWithParam<bool> {
9055 // virtual void SetUp() {
9056 // external_flag = GetParam();
9057 // }
9058 // }
9059 // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
9060 //
9061 inline internal::ParamGenerator<bool> Bool() {
9062 return Values(false, true);
9063 }
9064
9065 // Combine() allows the user to combine two or more sequences to produce
9066 // values of a Cartesian product of those sequences' elements.
9067 //
9068 // Synopsis:
9069 // Combine(gen1, gen2, ..., genN)
9070 // - returns a generator producing sequences with elements coming from
9071 // the Cartesian product of elements from the sequences generated by
9072 // gen1, gen2, ..., genN. The sequence elements will have a type of
9073 // std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
9074 // of elements from sequences produces by gen1, gen2, ..., genN.
9075 //
9076 // Example:
9077 //
9078 // This will instantiate tests in test suite AnimalTest each one with
9079 // the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
9080 // tuple("dog", BLACK), and tuple("dog", WHITE):
9081 //
9082 // enum Color { BLACK, GRAY, WHITE };
9083 // class AnimalTest
9084 // : public testing::TestWithParam<std::tuple<const char*, Color> > {...};
9085 //
9086 // TEST_P(AnimalTest, AnimalLooksNice) {...}
9087 //
9088 // INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
9089 // Combine(Values("cat", "dog"),
9090 // Values(BLACK, WHITE)));
9091 //
9092 // This will instantiate tests in FlagDependentTest with all variations of two
9093 // Boolean flags:
9094 //
9095 // class FlagDependentTest
9096 // : public testing::TestWithParam<std::tuple<bool, bool> > {
9097 // virtual void SetUp() {
9098 // // Assigns external_flag_1 and external_flag_2 values from the tuple.
9099 // std::tie(external_flag_1, external_flag_2) = GetParam();
9100 // }
9101 // };
9102 //
9103 // TEST_P(FlagDependentTest, TestFeature1) {
9104 // // Test your code using external_flag_1 and external_flag_2 here.
9105 // }
9106 // INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,
9107 // Combine(Bool(), Bool()));
9108 //
9109 template <typename... Generator>
9110 internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
9111 return internal::CartesianProductHolder<Generator...>(g...);
9112 }
9113
9114 #define TEST_P(test_suite_name, test_name) \
9115 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
9116 : public test_suite_name { \
9117 public: \
9118 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
9119 void TestBody() override; \
9120 \
9121 private: \
9122 static int AddToRegistry() { \
9123 ::testing::UnitTest::GetInstance() \
9124 ->parameterized_test_registry() \
9125 .GetTestSuitePatternHolder<test_suite_name>( \
9126 GTEST_STRINGIFY_(test_suite_name), \
9127 ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
9128 ->AddTestPattern( \
9129 GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
9130 new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
9131 test_suite_name, test_name)>(), \
9132 ::testing::internal::CodeLocation(__FILE__, __LINE__)); \
9133 return 0; \
9134 } \
9135 static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
9136 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
9137 test_name)); \
9138 }; \
9139 int GTEST_TEST_CLASS_NAME_(test_suite_name, \
9140 test_name)::gtest_registering_dummy_ = \
9141 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \
9142 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
9143
9144 // The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify
9145 // generator and an optional function or functor that generates custom test name
9146 // suffixes based on the test parameters. Such a function or functor should
9147 // accept one argument of type testing::TestParamInfo<class ParamType>, and
9148 // return std::string.
9149 //
9150 // testing::PrintToStringParamName is a builtin test suffix generator that
9151 // returns the value of testing::PrintToString(GetParam()).
9152 //
9153 // Note: test names must be non-empty, unique, and may only contain ASCII
9154 // alphanumeric characters or underscore. Because PrintToString adds quotes
9155 // to std::string and C strings, it won't work for these types.
9156
9157 #define GTEST_EXPAND_(arg) arg
9158 #define GTEST_GET_FIRST_(first, ...) first
9159 #define GTEST_GET_SECOND_(first, second, ...) second
9160
9161 #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
9162 static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
9163 gtest_##prefix##test_suite_name##_EvalGenerator_() { \
9164 return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
9165 } \
9166 static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
9167 const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
9168 if (::testing::internal::AlwaysFalse()) { \
9169 ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
9170 __VA_ARGS__, \
9171 ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
9172 DUMMY_PARAM_))); \
9173 auto t = std::make_tuple(__VA_ARGS__); \
9174 static_assert(std::tuple_size<decltype(t)>::value <= 2, \
9175 "Too Many Args!"); \
9176 } \
9177 return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
9178 __VA_ARGS__, \
9179 ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
9180 DUMMY_PARAM_))))(info); \
9181 } \
9182 static int gtest_##prefix##test_suite_name##_dummy_ \
9183 GTEST_ATTRIBUTE_UNUSED_ = \
9184 ::testing::UnitTest::GetInstance() \
9185 ->parameterized_test_registry() \
9186 .GetTestSuitePatternHolder<test_suite_name>( \
9187 GTEST_STRINGIFY_(test_suite_name), \
9188 ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
9189 ->AddTestSuiteInstantiation( \
9190 GTEST_STRINGIFY_(prefix), \
9191 >est_##prefix##test_suite_name##_EvalGenerator_, \
9192 >est_##prefix##test_suite_name##_EvalGenerateName_, \
9193 __FILE__, __LINE__)
9194
9195
9196 // Allow Marking a Parameterized test class as not needing to be instantiated.
9197 #define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
9198 namespace gtest_do_not_use_outside_namespace_scope {} \
9199 static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
9200 GTEST_STRINGIFY_(T))
9201
9202 // Legacy API is deprecated but still available
9203 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9204 #define INSTANTIATE_TEST_CASE_P \
9205 static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \
9206 ""); \
9207 INSTANTIATE_TEST_SUITE_P
9208 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9209
9210 } // namespace testing
9211
9212 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
9213 // Copyright 2006, Google Inc.
9214 // All rights reserved.
9215 //
9216 // Redistribution and use in source and binary forms, with or without
9217 // modification, are permitted provided that the following conditions are
9218 // met:
9219 //
9220 // * Redistributions of source code must retain the above copyright
9221 // notice, this list of conditions and the following disclaimer.
9222 // * Redistributions in binary form must reproduce the above
9223 // copyright notice, this list of conditions and the following disclaimer
9224 // in the documentation and/or other materials provided with the
9225 // distribution.
9226 // * Neither the name of Google Inc. nor the names of its
9227 // contributors may be used to endorse or promote products derived from
9228 // this software without specific prior written permission.
9229 //
9230 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9231 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9232 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9233 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9234 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9235 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9236 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9237 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9238 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9239 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9240 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9241
9242 //
9243 // Google C++ Testing and Mocking Framework definitions useful in production code.
9244 // GOOGLETEST_CM0003 DO NOT DELETE
9245
9246 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9247 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9248
9249 // When you need to test the private or protected members of a class,
9250 // use the FRIEND_TEST macro to declare your tests as friends of the
9251 // class. For example:
9252 //
9253 // class MyClass {
9254 // private:
9255 // void PrivateMethod();
9256 // FRIEND_TEST(MyClassTest, PrivateMethodWorks);
9257 // };
9258 //
9259 // class MyClassTest : public testing::Test {
9260 // // ...
9261 // };
9262 //
9263 // TEST_F(MyClassTest, PrivateMethodWorks) {
9264 // // Can call MyClass::PrivateMethod() here.
9265 // }
9266 //
9267 // Note: The test class must be in the same namespace as the class being tested.
9268 // For example, putting MyClassTest in an anonymous namespace will not work.
9269
9270 #define FRIEND_TEST(test_case_name, test_name)\
9271 friend class test_case_name##_##test_name##_Test
9272
9273 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9274 // Copyright 2008 Google Inc.
9275 // All Rights Reserved.
9276 //
9277 // Redistribution and use in source and binary forms, with or without
9278 // modification, are permitted provided that the following conditions are
9279 // met:
9280 //
9281 // * Redistributions of source code must retain the above copyright
9282 // notice, this list of conditions and the following disclaimer.
9283 // * Redistributions in binary form must reproduce the above
9284 // copyright notice, this list of conditions and the following disclaimer
9285 // in the documentation and/or other materials provided with the
9286 // distribution.
9287 // * Neither the name of Google Inc. nor the names of its
9288 // contributors may be used to endorse or promote products derived from
9289 // this software without specific prior written permission.
9290 //
9291 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9292 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9293 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9294 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9295 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9296 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9297 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9298 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9299 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9300 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9301 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9302
9303 // GOOGLETEST_CM0001 DO NOT DELETE
9304
9305 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9306 #define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9307
9308 // This header implements typed tests and type-parameterized tests.
9309
9310 // Typed (aka type-driven) tests repeat the same test for types in a
9311 // list. You must know which types you want to test with when writing
9312 // typed tests. Here's how you do it:
9313
9314 #if 0
9315
9316 // First, define a fixture class template. It should be parameterized
9317 // by a type. Remember to derive it from testing::Test.
9318 template <typename T>
9319 class FooTest : public testing::Test {
9320 public:
9321 ...
9322 typedef std::list<T> List;
9323 static T shared_;
9324 T value_;
9325 };
9326
9327 // Next, associate a list of types with the test suite, which will be
9328 // repeated for each type in the list. The typedef is necessary for
9329 // the macro to parse correctly.
9330 typedef testing::Types<char, int, unsigned int> MyTypes;
9331 TYPED_TEST_SUITE(FooTest, MyTypes);
9332
9333 // If the type list contains only one type, you can write that type
9334 // directly without Types<...>:
9335 // TYPED_TEST_SUITE(FooTest, int);
9336
9337 // Then, use TYPED_TEST() instead of TEST_F() to define as many typed
9338 // tests for this test suite as you want.
9339 TYPED_TEST(FooTest, DoesBlah) {
9340 // Inside a test, refer to the special name TypeParam to get the type
9341 // parameter. Since we are inside a derived class template, C++ requires
9342 // us to visit the members of FooTest via 'this'.
9343 TypeParam n = this->value_;
9344
9345 // To visit static members of the fixture, add the TestFixture::
9346 // prefix.
9347 n += TestFixture::shared_;
9348
9349 // To refer to typedefs in the fixture, add the "typename
9350 // TestFixture::" prefix.
9351 typename TestFixture::List values;
9352 values.push_back(n);
9353 ...
9354 }
9355
9356 TYPED_TEST(FooTest, HasPropertyA) { ... }
9357
9358 // TYPED_TEST_SUITE takes an optional third argument which allows to specify a
9359 // class that generates custom test name suffixes based on the type. This should
9360 // be a class which has a static template function GetName(int index) returning
9361 // a string for each type. The provided integer index equals the index of the
9362 // type in the provided type list. In many cases the index can be ignored.
9363 //
9364 // For example:
9365 // class MyTypeNames {
9366 // public:
9367 // template <typename T>
9368 // static std::string GetName(int) {
9369 // if (std::is_same<T, char>()) return "char";
9370 // if (std::is_same<T, int>()) return "int";
9371 // if (std::is_same<T, unsigned int>()) return "unsignedInt";
9372 // }
9373 // };
9374 // TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);
9375
9376 #endif // 0
9377
9378 // Type-parameterized tests are abstract test patterns parameterized
9379 // by a type. Compared with typed tests, type-parameterized tests
9380 // allow you to define the test pattern without knowing what the type
9381 // parameters are. The defined pattern can be instantiated with
9382 // different types any number of times, in any number of translation
9383 // units.
9384 //
9385 // If you are designing an interface or concept, you can define a
9386 // suite of type-parameterized tests to verify properties that any
9387 // valid implementation of the interface/concept should have. Then,
9388 // each implementation can easily instantiate the test suite to verify
9389 // that it conforms to the requirements, without having to write
9390 // similar tests repeatedly. Here's an example:
9391
9392 #if 0
9393
9394 // First, define a fixture class template. It should be parameterized
9395 // by a type. Remember to derive it from testing::Test.
9396 template <typename T>
9397 class FooTest : public testing::Test {
9398 ...
9399 };
9400
9401 // Next, declare that you will define a type-parameterized test suite
9402 // (the _P suffix is for "parameterized" or "pattern", whichever you
9403 // prefer):
9404 TYPED_TEST_SUITE_P(FooTest);
9405
9406 // Then, use TYPED_TEST_P() to define as many type-parameterized tests
9407 // for this type-parameterized test suite as you want.
9408 TYPED_TEST_P(FooTest, DoesBlah) {
9409 // Inside a test, refer to TypeParam to get the type parameter.
9410 TypeParam n = 0;
9411 ...
9412 }
9413
9414 TYPED_TEST_P(FooTest, HasPropertyA) { ... }
9415
9416 // Now the tricky part: you need to register all test patterns before
9417 // you can instantiate them. The first argument of the macro is the
9418 // test suite name; the rest are the names of the tests in this test
9419 // case.
9420 REGISTER_TYPED_TEST_SUITE_P(FooTest,
9421 DoesBlah, HasPropertyA);
9422
9423 // Finally, you are free to instantiate the pattern with the types you
9424 // want. If you put the above code in a header file, you can #include
9425 // it in multiple C++ source files and instantiate it multiple times.
9426 //
9427 // To distinguish different instances of the pattern, the first
9428 // argument to the INSTANTIATE_* macro is a prefix that will be added
9429 // to the actual test suite name. Remember to pick unique prefixes for
9430 // different instances.
9431 typedef testing::Types<char, int, unsigned int> MyTypes;
9432 INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
9433
9434 // If the type list contains only one type, you can write that type
9435 // directly without Types<...>:
9436 // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
9437 //
9438 // Similar to the optional argument of TYPED_TEST_SUITE above,
9439 // INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to
9440 // generate custom names.
9441 // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);
9442
9443 #endif // 0
9444
9445
9446 // Implements typed tests.
9447
9448 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9449 //
9450 // Expands to the name of the typedef for the type parameters of the
9451 // given test suite.
9452 #define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_
9453
9454 // Expands to the name of the typedef for the NameGenerator, responsible for
9455 // creating the suffixes of the name.
9456 #define GTEST_NAME_GENERATOR_(TestSuiteName) \
9457 gtest_type_params_##TestSuiteName##_NameGenerator
9458
9459 #define TYPED_TEST_SUITE(CaseName, Types, ...) \
9460 typedef ::testing::internal::GenerateTypeList<Types>::type \
9461 GTEST_TYPE_PARAMS_(CaseName); \
9462 typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
9463 GTEST_NAME_GENERATOR_(CaseName)
9464
9465 #define TYPED_TEST(CaseName, TestName) \
9466 static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \
9467 "test-name must not be empty"); \
9468 template <typename gtest_TypeParam_> \
9469 class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
9470 : public CaseName<gtest_TypeParam_> { \
9471 private: \
9472 typedef CaseName<gtest_TypeParam_> TestFixture; \
9473 typedef gtest_TypeParam_ TypeParam; \
9474 void TestBody() override; \
9475 }; \
9476 static bool gtest_##CaseName##_##TestName##_registered_ \
9477 GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \
9478 CaseName, \
9479 ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
9480 TestName)>, \
9481 GTEST_TYPE_PARAMS_( \
9482 CaseName)>::Register("", \
9483 ::testing::internal::CodeLocation( \
9484 __FILE__, __LINE__), \
9485 GTEST_STRINGIFY_(CaseName), \
9486 GTEST_STRINGIFY_(TestName), 0, \
9487 ::testing::internal::GenerateNames< \
9488 GTEST_NAME_GENERATOR_(CaseName), \
9489 GTEST_TYPE_PARAMS_(CaseName)>()); \
9490 template <typename gtest_TypeParam_> \
9491 void GTEST_TEST_CLASS_NAME_(CaseName, \
9492 TestName)<gtest_TypeParam_>::TestBody()
9493
9494 // Legacy API is deprecated but still available
9495 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9496 #define TYPED_TEST_CASE \
9497 static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \
9498 TYPED_TEST_SUITE
9499 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9500
9501 // Implements type-parameterized tests.
9502
9503 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9504 //
9505 // Expands to the namespace name that the type-parameterized tests for
9506 // the given type-parameterized test suite are defined in. The exact
9507 // name of the namespace is subject to change without notice.
9508 #define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_
9509
9510 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9511 //
9512 // Expands to the name of the variable used to remember the names of
9513 // the defined tests in the given test suite.
9514 #define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \
9515 gtest_typed_test_suite_p_state_##TestSuiteName##_
9516
9517 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
9518 //
9519 // Expands to the name of the variable used to remember the names of
9520 // the registered tests in the given test suite.
9521 #define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \
9522 gtest_registered_test_names_##TestSuiteName##_
9523
9524 // The variables defined in the type-parameterized test macros are
9525 // static as typically these macros are used in a .h file that can be
9526 // #included in multiple translation units linked together.
9527 #define TYPED_TEST_SUITE_P(SuiteName) \
9528 static ::testing::internal::TypedTestSuitePState \
9529 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
9530
9531 // Legacy API is deprecated but still available
9532 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9533 #define TYPED_TEST_CASE_P \
9534 static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \
9535 TYPED_TEST_SUITE_P
9536 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9537
9538 #define TYPED_TEST_P(SuiteName, TestName) \
9539 namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
9540 template <typename gtest_TypeParam_> \
9541 class TestName : public SuiteName<gtest_TypeParam_> { \
9542 private: \
9543 typedef SuiteName<gtest_TypeParam_> TestFixture; \
9544 typedef gtest_TypeParam_ TypeParam; \
9545 void TestBody() override; \
9546 }; \
9547 static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
9548 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
9549 __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
9550 GTEST_STRINGIFY_(TestName)); \
9551 } \
9552 template <typename gtest_TypeParam_> \
9553 void GTEST_SUITE_NAMESPACE_( \
9554 SuiteName)::TestName<gtest_TypeParam_>::TestBody()
9555
9556 // Note: this won't work correctly if the trailing arguments are macros.
9557 #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
9558 namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
9559 typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
9560 } \
9561 static const char* const GTEST_REGISTERED_TEST_NAMES_( \
9562 SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
9563 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
9564 GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
9565
9566 // Legacy API is deprecated but still available
9567 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9568 #define REGISTER_TYPED_TEST_CASE_P \
9569 static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \
9570 ""); \
9571 REGISTER_TYPED_TEST_SUITE_P
9572 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9573
9574 #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
9575 static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \
9576 "test-suit-prefix must not be empty"); \
9577 static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
9578 ::testing::internal::TypeParameterizedTestSuite< \
9579 SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
9580 ::testing::internal::GenerateTypeList<Types>::type>:: \
9581 Register(GTEST_STRINGIFY_(Prefix), \
9582 ::testing::internal::CodeLocation(__FILE__, __LINE__), \
9583 >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \
9584 GTEST_STRINGIFY_(SuiteName), \
9585 GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
9586 ::testing::internal::GenerateNames< \
9587 ::testing::internal::NameGeneratorSelector< \
9588 __VA_ARGS__>::type, \
9589 ::testing::internal::GenerateTypeList<Types>::type>())
9590
9591 // Legacy API is deprecated but still available
9592 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9593 #define INSTANTIATE_TYPED_TEST_CASE_P \
9594 static_assert( \
9595 ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \
9596 INSTANTIATE_TYPED_TEST_SUITE_P
9597 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9598
9599 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9600
9601 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
9602 /* class A needs to have dll-interface to be used by clients of class B */)
9603
9604 namespace testing {
9605
9606 // Silence C4100 (unreferenced formal parameter) and 4805
9607 // unsafe mix of type 'const int' and type 'const bool'
9608 #ifdef _MSC_VER
9609 # pragma warning(push)
9610 # pragma warning(disable:4805)
9611 # pragma warning(disable:4100)
9612 #endif
9613
9614
9615 // Declares the flags.
9616
9617 // This flag temporary enables the disabled tests.
9618 GTEST_DECLARE_bool_(also_run_disabled_tests);
9619
9620 // This flag brings the debugger on an assertion failure.
9621 GTEST_DECLARE_bool_(break_on_failure);
9622
9623 // This flag controls whether Google Test catches all test-thrown exceptions
9624 // and logs them as failures.
9625 GTEST_DECLARE_bool_(catch_exceptions);
9626
9627 // This flag enables using colors in terminal output. Available values are
9628 // "yes" to enable colors, "no" (disable colors), or "auto" (the default)
9629 // to let Google Test decide.
9630 GTEST_DECLARE_string_(color);
9631
9632 // This flag controls whether the test runner should continue execution past
9633 // first failure.
9634 GTEST_DECLARE_bool_(fail_fast);
9635
9636 // This flag sets up the filter to select by name using a glob pattern
9637 // the tests to run. If the filter is not given all tests are executed.
9638 GTEST_DECLARE_string_(filter);
9639
9640 // This flag controls whether Google Test installs a signal handler that dumps
9641 // debugging information when fatal signals are raised.
9642 GTEST_DECLARE_bool_(install_failure_signal_handler);
9643
9644 // This flag causes the Google Test to list tests. None of the tests listed
9645 // are actually run if the flag is provided.
9646 GTEST_DECLARE_bool_(list_tests);
9647
9648 // This flag controls whether Google Test emits a detailed XML report to a file
9649 // in addition to its normal textual output.
9650 GTEST_DECLARE_string_(output);
9651
9652 // This flags control whether Google Test prints only test failures.
9653 GTEST_DECLARE_bool_(brief);
9654
9655 // This flags control whether Google Test prints the elapsed time for each
9656 // test.
9657 GTEST_DECLARE_bool_(print_time);
9658
9659 // This flags control whether Google Test prints UTF8 characters as text.
9660 GTEST_DECLARE_bool_(print_utf8);
9661
9662 // This flag specifies the random number seed.
9663 GTEST_DECLARE_int32_(random_seed);
9664
9665 // This flag sets how many times the tests are repeated. The default value
9666 // is 1. If the value is -1 the tests are repeating forever.
9667 GTEST_DECLARE_int32_(repeat);
9668
9669 // This flag controls whether Google Test includes Google Test internal
9670 // stack frames in failure stack traces.
9671 GTEST_DECLARE_bool_(show_internal_stack_frames);
9672
9673 // When this flag is specified, tests' order is randomized on every iteration.
9674 GTEST_DECLARE_bool_(shuffle);
9675
9676 // This flag specifies the maximum number of stack frames to be
9677 // printed in a failure message.
9678 GTEST_DECLARE_int32_(stack_trace_depth);
9679
9680 // When this flag is specified, a failed assertion will throw an
9681 // exception if exceptions are enabled, or exit the program with a
9682 // non-zero code otherwise. For use with an external test framework.
9683 GTEST_DECLARE_bool_(throw_on_failure);
9684
9685 // When this flag is set with a "host:port" string, on supported
9686 // platforms test results are streamed to the specified port on
9687 // the specified host machine.
9688 GTEST_DECLARE_string_(stream_result_to);
9689
9690 #if GTEST_USE_OWN_FLAGFILE_FLAG_
9691 GTEST_DECLARE_string_(flagfile);
9692 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
9693
9694 // The upper limit for valid stack trace depths.
9695 const int kMaxStackTraceDepth = 100;
9696
9697 namespace internal {
9698
9699 class AssertHelper;
9700 class DefaultGlobalTestPartResultReporter;
9701 class ExecDeathTest;
9702 class NoExecDeathTest;
9703 class FinalSuccessChecker;
9704 class GTestFlagSaver;
9705 class StreamingListenerTest;
9706 class TestResultAccessor;
9707 class TestEventListenersAccessor;
9708 class TestEventRepeater;
9709 class UnitTestRecordPropertyTestHelper;
9710 class WindowsDeathTest;
9711 class FuchsiaDeathTest;
9712 class UnitTestImpl* GetUnitTestImpl();
9713 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
9714 const std::string& message);
9715 std::set<std::string>* GetIgnoredParameterizedTestSuites();
9716
9717 } // namespace internal
9718
9719 // The friend relationship of some of these classes is cyclic.
9720 // If we don't forward declare them the compiler might confuse the classes
9721 // in friendship clauses with same named classes on the scope.
9722 class Test;
9723 class TestSuite;
9724
9725 // Old API is still available but deprecated
9726 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9727 using TestCase = TestSuite;
9728 #endif
9729 class TestInfo;
9730 class UnitTest;
9731
9732 // A class for indicating whether an assertion was successful. When
9733 // the assertion wasn't successful, the AssertionResult object
9734 // remembers a non-empty message that describes how it failed.
9735 //
9736 // To create an instance of this class, use one of the factory functions
9737 // (AssertionSuccess() and AssertionFailure()).
9738 //
9739 // This class is useful for two purposes:
9740 // 1. Defining predicate functions to be used with Boolean test assertions
9741 // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
9742 // 2. Defining predicate-format functions to be
9743 // used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
9744 //
9745 // For example, if you define IsEven predicate:
9746 //
9747 // testing::AssertionResult IsEven(int n) {
9748 // if ((n % 2) == 0)
9749 // return testing::AssertionSuccess();
9750 // else
9751 // return testing::AssertionFailure() << n << " is odd";
9752 // }
9753 //
9754 // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
9755 // will print the message
9756 //
9757 // Value of: IsEven(Fib(5))
9758 // Actual: false (5 is odd)
9759 // Expected: true
9760 //
9761 // instead of a more opaque
9762 //
9763 // Value of: IsEven(Fib(5))
9764 // Actual: false
9765 // Expected: true
9766 //
9767 // in case IsEven is a simple Boolean predicate.
9768 //
9769 // If you expect your predicate to be reused and want to support informative
9770 // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
9771 // about half as often as positive ones in our tests), supply messages for
9772 // both success and failure cases:
9773 //
9774 // testing::AssertionResult IsEven(int n) {
9775 // if ((n % 2) == 0)
9776 // return testing::AssertionSuccess() << n << " is even";
9777 // else
9778 // return testing::AssertionFailure() << n << " is odd";
9779 // }
9780 //
9781 // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
9782 //
9783 // Value of: IsEven(Fib(6))
9784 // Actual: true (8 is even)
9785 // Expected: false
9786 //
9787 // NB: Predicates that support negative Boolean assertions have reduced
9788 // performance in positive ones so be careful not to use them in tests
9789 // that have lots (tens of thousands) of positive Boolean assertions.
9790 //
9791 // To use this class with EXPECT_PRED_FORMAT assertions such as:
9792 //
9793 // // Verifies that Foo() returns an even number.
9794 // EXPECT_PRED_FORMAT1(IsEven, Foo());
9795 //
9796 // you need to define:
9797 //
9798 // testing::AssertionResult IsEven(const char* expr, int n) {
9799 // if ((n % 2) == 0)
9800 // return testing::AssertionSuccess();
9801 // else
9802 // return testing::AssertionFailure()
9803 // << "Expected: " << expr << " is even\n Actual: it's " << n;
9804 // }
9805 //
9806 // If Foo() returns 5, you will see the following message:
9807 //
9808 // Expected: Foo() is even
9809 // Actual: it's 5
9810 //
9811 class GTEST_API_ AssertionResult {
9812 public:
9813 // Copy constructor.
9814 // Used in EXPECT_TRUE/FALSE(assertion_result).
9815 AssertionResult(const AssertionResult& other);
9816
9817 // C4800 is a level 3 warning in Visual Studio 2015 and earlier.
9818 // This warning is not emitted in Visual Studio 2017.
9819 // This warning is off by default starting in Visual Studio 2019 but can be
9820 // enabled with command-line options.
9821 #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
9822 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
9823 #endif
9824
9825 // Used in the EXPECT_TRUE/FALSE(bool_expression).
9826 //
9827 // T must be contextually convertible to bool.
9828 //
9829 // The second parameter prevents this overload from being considered if
9830 // the argument is implicitly convertible to AssertionResult. In that case
9831 // we want AssertionResult's copy constructor to be used.
9832 template <typename T>
9833 explicit AssertionResult(
9834 const T& success,
9835 typename std::enable_if<
9836 !std::is_convertible<T, AssertionResult>::value>::type*
9837 /*enabler*/
9838 = nullptr)
9839 : success_(success) {}
9840
9841 #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
9842 GTEST_DISABLE_MSC_WARNINGS_POP_()
9843 #endif
9844
9845 // Assignment operator.
9846 AssertionResult& operator=(AssertionResult other) {
9847 swap(other);
9848 return *this;
9849 }
9850
9851 // Returns true if and only if the assertion succeeded.
9852 operator bool() const { return success_; } // NOLINT
9853
9854 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
9855 AssertionResult operator!() const;
9856
9857 // Returns the text streamed into this AssertionResult. Test assertions
9858 // use it when they fail (i.e., the predicate's outcome doesn't match the
9859 // assertion's expectation). When nothing has been streamed into the
9860 // object, returns an empty string.
9861 const char* message() const {
9862 return message_.get() != nullptr ? message_->c_str() : "";
9863 }
9864 // Deprecated; please use message() instead.
9865 const char* failure_message() const { return message(); }
9866
9867 // Streams a custom failure message into this object.
9868 template <typename T> AssertionResult& operator<<(const T& value) {
9869 AppendMessage(Message() << value);
9870 return *this;
9871 }
9872
9873 // Allows streaming basic output manipulators such as endl or flush into
9874 // this object.
9875 AssertionResult& operator<<(
9876 ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
9877 AppendMessage(Message() << basic_manipulator);
9878 return *this;
9879 }
9880
9881 private:
9882 // Appends the contents of message to message_.
9883 void AppendMessage(const Message& a_message) {
9884 if (message_.get() == nullptr) message_.reset(new ::std::string);
9885 message_->append(a_message.GetString().c_str());
9886 }
9887
9888 // Swap the contents of this AssertionResult with other.
9889 void swap(AssertionResult& other);
9890
9891 // Stores result of the assertion predicate.
9892 bool success_;
9893 // Stores the message describing the condition in case the expectation
9894 // construct is not satisfied with the predicate's outcome.
9895 // Referenced via a pointer to avoid taking too much stack frame space
9896 // with test assertions.
9897 std::unique_ptr< ::std::string> message_;
9898 };
9899
9900 // Makes a successful assertion result.
9901 GTEST_API_ AssertionResult AssertionSuccess();
9902
9903 // Makes a failed assertion result.
9904 GTEST_API_ AssertionResult AssertionFailure();
9905
9906 // Makes a failed assertion result with the given failure message.
9907 // Deprecated; use AssertionFailure() << msg.
9908 GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
9909
9910 } // namespace testing
9911
9912 // Includes the auto-generated header that implements a family of generic
9913 // predicate assertion macros. This include comes late because it relies on
9914 // APIs declared above.
9915 // Copyright 2006, Google Inc.
9916 // All rights reserved.
9917 //
9918 // Redistribution and use in source and binary forms, with or without
9919 // modification, are permitted provided that the following conditions are
9920 // met:
9921 //
9922 // * Redistributions of source code must retain the above copyright
9923 // notice, this list of conditions and the following disclaimer.
9924 // * Redistributions in binary form must reproduce the above
9925 // copyright notice, this list of conditions and the following disclaimer
9926 // in the documentation and/or other materials provided with the
9927 // distribution.
9928 // * Neither the name of Google Inc. nor the names of its
9929 // contributors may be used to endorse or promote products derived from
9930 // this software without specific prior written permission.
9931 //
9932 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9933 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9934 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9935 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9936 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9937 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9938 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9939 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9940 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9941 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9942 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9943
9944 // This file is AUTOMATICALLY GENERATED on 01/02/2019 by command
9945 // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
9946 //
9947 // Implements a family of generic predicate assertion macros.
9948 // GOOGLETEST_CM0001 DO NOT DELETE
9949
9950 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
9951 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
9952
9953
9954 namespace testing {
9955
9956 // This header implements a family of generic predicate assertion
9957 // macros:
9958 //
9959 // ASSERT_PRED_FORMAT1(pred_format, v1)
9960 // ASSERT_PRED_FORMAT2(pred_format, v1, v2)
9961 // ...
9962 //
9963 // where pred_format is a function or functor that takes n (in the
9964 // case of ASSERT_PRED_FORMATn) values and their source expression
9965 // text, and returns a testing::AssertionResult. See the definition
9966 // of ASSERT_EQ in gtest.h for an example.
9967 //
9968 // If you don't care about formatting, you can use the more
9969 // restrictive version:
9970 //
9971 // ASSERT_PRED1(pred, v1)
9972 // ASSERT_PRED2(pred, v1, v2)
9973 // ...
9974 //
9975 // where pred is an n-ary function or functor that returns bool,
9976 // and the values v1, v2, ..., must support the << operator for
9977 // streaming to std::ostream.
9978 //
9979 // We also define the EXPECT_* variations.
9980 //
9981 // For now we only support predicates whose arity is at most 5.
9982 // Please email googletestframework@googlegroups.com if you need
9983 // support for higher arities.
9984
9985 // GTEST_ASSERT_ is the basic statement to which all of the assertions
9986 // in this file reduce. Don't use this in your code.
9987
9988 #define GTEST_ASSERT_(expression, on_failure) \
9989 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
9990 if (const ::testing::AssertionResult gtest_ar = (expression)) \
9991 ; \
9992 else \
9993 on_failure(gtest_ar.failure_message())
9994
9995
9996 // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
9997 // this in your code.
9998 template <typename Pred,
9999 typename T1>
10000 AssertionResult AssertPred1Helper(const char* pred_text,
10001 const char* e1,
10002 Pred pred,
10003 const T1& v1) {
10004 if (pred(v1)) return AssertionSuccess();
10005
10006 return AssertionFailure()
10007 << pred_text << "(" << e1 << ") evaluates to false, where"
10008 << "\n"
10009 << e1 << " evaluates to " << ::testing::PrintToString(v1);
10010 }
10011
10012 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
10013 // Don't use this in your code.
10014 #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
10015 GTEST_ASSERT_(pred_format(#v1, v1), \
10016 on_failure)
10017
10018 // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
10019 // this in your code.
10020 #define GTEST_PRED1_(pred, v1, on_failure)\
10021 GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
10022 #v1, \
10023 pred, \
10024 v1), on_failure)
10025
10026 // Unary predicate assertion macros.
10027 #define EXPECT_PRED_FORMAT1(pred_format, v1) \
10028 GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
10029 #define EXPECT_PRED1(pred, v1) \
10030 GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
10031 #define ASSERT_PRED_FORMAT1(pred_format, v1) \
10032 GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
10033 #define ASSERT_PRED1(pred, v1) \
10034 GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
10035
10036
10037
10038 // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
10039 // this in your code.
10040 template <typename Pred,
10041 typename T1,
10042 typename T2>
10043 AssertionResult AssertPred2Helper(const char* pred_text,
10044 const char* e1,
10045 const char* e2,
10046 Pred pred,
10047 const T1& v1,
10048 const T2& v2) {
10049 if (pred(v1, v2)) return AssertionSuccess();
10050
10051 return AssertionFailure()
10052 << pred_text << "(" << e1 << ", " << e2
10053 << ") evaluates to false, where"
10054 << "\n"
10055 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10056 << e2 << " evaluates to " << ::testing::PrintToString(v2);
10057 }
10058
10059 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
10060 // Don't use this in your code.
10061 #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
10062 GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
10063 on_failure)
10064
10065 // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
10066 // this in your code.
10067 #define GTEST_PRED2_(pred, v1, v2, on_failure)\
10068 GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
10069 #v1, \
10070 #v2, \
10071 pred, \
10072 v1, \
10073 v2), on_failure)
10074
10075 // Binary predicate assertion macros.
10076 #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
10077 GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
10078 #define EXPECT_PRED2(pred, v1, v2) \
10079 GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
10080 #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
10081 GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
10082 #define ASSERT_PRED2(pred, v1, v2) \
10083 GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
10084
10085
10086
10087 // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
10088 // this in your code.
10089 template <typename Pred,
10090 typename T1,
10091 typename T2,
10092 typename T3>
10093 AssertionResult AssertPred3Helper(const char* pred_text,
10094 const char* e1,
10095 const char* e2,
10096 const char* e3,
10097 Pred pred,
10098 const T1& v1,
10099 const T2& v2,
10100 const T3& v3) {
10101 if (pred(v1, v2, v3)) return AssertionSuccess();
10102
10103 return AssertionFailure()
10104 << pred_text << "(" << e1 << ", " << e2 << ", " << e3
10105 << ") evaluates to false, where"
10106 << "\n"
10107 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10108 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10109 << e3 << " evaluates to " << ::testing::PrintToString(v3);
10110 }
10111
10112 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
10113 // Don't use this in your code.
10114 #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
10115 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
10116 on_failure)
10117
10118 // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
10119 // this in your code.
10120 #define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
10121 GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
10122 #v1, \
10123 #v2, \
10124 #v3, \
10125 pred, \
10126 v1, \
10127 v2, \
10128 v3), on_failure)
10129
10130 // Ternary predicate assertion macros.
10131 #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
10132 GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
10133 #define EXPECT_PRED3(pred, v1, v2, v3) \
10134 GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
10135 #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
10136 GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
10137 #define ASSERT_PRED3(pred, v1, v2, v3) \
10138 GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
10139
10140
10141
10142 // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
10143 // this in your code.
10144 template <typename Pred,
10145 typename T1,
10146 typename T2,
10147 typename T3,
10148 typename T4>
10149 AssertionResult AssertPred4Helper(const char* pred_text,
10150 const char* e1,
10151 const char* e2,
10152 const char* e3,
10153 const char* e4,
10154 Pred pred,
10155 const T1& v1,
10156 const T2& v2,
10157 const T3& v3,
10158 const T4& v4) {
10159 if (pred(v1, v2, v3, v4)) return AssertionSuccess();
10160
10161 return AssertionFailure()
10162 << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
10163 << ") evaluates to false, where"
10164 << "\n"
10165 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10166 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10167 << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
10168 << e4 << " evaluates to " << ::testing::PrintToString(v4);
10169 }
10170
10171 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
10172 // Don't use this in your code.
10173 #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
10174 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
10175 on_failure)
10176
10177 // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
10178 // this in your code.
10179 #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
10180 GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
10181 #v1, \
10182 #v2, \
10183 #v3, \
10184 #v4, \
10185 pred, \
10186 v1, \
10187 v2, \
10188 v3, \
10189 v4), on_failure)
10190
10191 // 4-ary predicate assertion macros.
10192 #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
10193 GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
10194 #define EXPECT_PRED4(pred, v1, v2, v3, v4) \
10195 GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
10196 #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
10197 GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
10198 #define ASSERT_PRED4(pred, v1, v2, v3, v4) \
10199 GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
10200
10201
10202
10203 // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
10204 // this in your code.
10205 template <typename Pred,
10206 typename T1,
10207 typename T2,
10208 typename T3,
10209 typename T4,
10210 typename T5>
10211 AssertionResult AssertPred5Helper(const char* pred_text,
10212 const char* e1,
10213 const char* e2,
10214 const char* e3,
10215 const char* e4,
10216 const char* e5,
10217 Pred pred,
10218 const T1& v1,
10219 const T2& v2,
10220 const T3& v3,
10221 const T4& v4,
10222 const T5& v5) {
10223 if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
10224
10225 return AssertionFailure()
10226 << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
10227 << ", " << e5 << ") evaluates to false, where"
10228 << "\n"
10229 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10230 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10231 << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
10232 << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n"
10233 << e5 << " evaluates to " << ::testing::PrintToString(v5);
10234 }
10235
10236 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
10237 // Don't use this in your code.
10238 #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
10239 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
10240 on_failure)
10241
10242 // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
10243 // this in your code.
10244 #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
10245 GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
10246 #v1, \
10247 #v2, \
10248 #v3, \
10249 #v4, \
10250 #v5, \
10251 pred, \
10252 v1, \
10253 v2, \
10254 v3, \
10255 v4, \
10256 v5), on_failure)
10257
10258 // 5-ary predicate assertion macros.
10259 #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
10260 GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
10261 #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
10262 GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
10263 #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
10264 GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
10265 #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
10266 GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
10267
10268
10269
10270 } // namespace testing
10271
10272 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
10273
10274 namespace testing {
10275
10276 // The abstract class that all tests inherit from.
10277 //
10278 // In Google Test, a unit test program contains one or many TestSuites, and
10279 // each TestSuite contains one or many Tests.
10280 //
10281 // When you define a test using the TEST macro, you don't need to
10282 // explicitly derive from Test - the TEST macro automatically does
10283 // this for you.
10284 //
10285 // The only time you derive from Test is when defining a test fixture
10286 // to be used in a TEST_F. For example:
10287 //
10288 // class FooTest : public testing::Test {
10289 // protected:
10290 // void SetUp() override { ... }
10291 // void TearDown() override { ... }
10292 // ...
10293 // };
10294 //
10295 // TEST_F(FooTest, Bar) { ... }
10296 // TEST_F(FooTest, Baz) { ... }
10297 //
10298 // Test is not copyable.
10299 class GTEST_API_ Test {
10300 public:
10301 friend class TestInfo;
10302
10303 // The d'tor is virtual as we intend to inherit from Test.
10304 virtual ~Test();
10305
10306 // Sets up the stuff shared by all tests in this test suite.
10307 //
10308 // Google Test will call Foo::SetUpTestSuite() before running the first
10309 // test in test suite Foo. Hence a sub-class can define its own
10310 // SetUpTestSuite() method to shadow the one defined in the super
10311 // class.
10312 static void SetUpTestSuite() {}
10313
10314 // Tears down the stuff shared by all tests in this test suite.
10315 //
10316 // Google Test will call Foo::TearDownTestSuite() after running the last
10317 // test in test suite Foo. Hence a sub-class can define its own
10318 // TearDownTestSuite() method to shadow the one defined in the super
10319 // class.
10320 static void TearDownTestSuite() {}
10321
10322 // Legacy API is deprecated but still available. Use SetUpTestSuite and
10323 // TearDownTestSuite instead.
10324 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10325 static void TearDownTestCase() {}
10326 static void SetUpTestCase() {}
10327 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10328
10329 // Returns true if and only if the current test has a fatal failure.
10330 static bool HasFatalFailure();
10331
10332 // Returns true if and only if the current test has a non-fatal failure.
10333 static bool HasNonfatalFailure();
10334
10335 // Returns true if and only if the current test was skipped.
10336 static bool IsSkipped();
10337
10338 // Returns true if and only if the current test has a (either fatal or
10339 // non-fatal) failure.
10340 static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
10341
10342 // Logs a property for the current test, test suite, or for the entire
10343 // invocation of the test program when used outside of the context of a
10344 // test suite. Only the last value for a given key is remembered. These
10345 // are public static so they can be called from utility functions that are
10346 // not members of the test fixture. Calls to RecordProperty made during
10347 // lifespan of the test (from the moment its constructor starts to the
10348 // moment its destructor finishes) will be output in XML as attributes of
10349 // the <testcase> element. Properties recorded from fixture's
10350 // SetUpTestSuite or TearDownTestSuite are logged as attributes of the
10351 // corresponding <testsuite> element. Calls to RecordProperty made in the
10352 // global context (before or after invocation of RUN_ALL_TESTS and from
10353 // SetUp/TearDown method of Environment objects registered with Google
10354 // Test) will be output as attributes of the <testsuites> element.
10355 static void RecordProperty(const std::string& key, const std::string& value);
10356 static void RecordProperty(const std::string& key, int value);
10357
10358 protected:
10359 // Creates a Test object.
10360 Test();
10361
10362 // Sets up the test fixture.
10363 virtual void SetUp();
10364
10365 // Tears down the test fixture.
10366 virtual void TearDown();
10367
10368 private:
10369 // Returns true if and only if the current test has the same fixture class
10370 // as the first test in the current test suite.
10371 static bool HasSameFixtureClass();
10372
10373 // Runs the test after the test fixture has been set up.
10374 //
10375 // A sub-class must implement this to define the test logic.
10376 //
10377 // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
10378 // Instead, use the TEST or TEST_F macro.
10379 virtual void TestBody() = 0;
10380
10381 // Sets up, executes, and tears down the test.
10382 void Run();
10383
10384 // Deletes self. We deliberately pick an unusual name for this
10385 // internal method to avoid clashing with names used in user TESTs.
10386 void DeleteSelf_() { delete this; }
10387
10388 const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;
10389
10390 // Often a user misspells SetUp() as Setup() and spends a long time
10391 // wondering why it is never called by Google Test. The declaration of
10392 // the following method is solely for catching such an error at
10393 // compile time:
10394 //
10395 // - The return type is deliberately chosen to be not void, so it
10396 // will be a conflict if void Setup() is declared in the user's
10397 // test fixture.
10398 //
10399 // - This method is private, so it will be another compiler error
10400 // if the method is called from the user's test fixture.
10401 //
10402 // DO NOT OVERRIDE THIS FUNCTION.
10403 //
10404 // If you see an error about overriding the following function or
10405 // about it being private, you have mis-spelled SetUp() as Setup().
10406 struct Setup_should_be_spelled_SetUp {};
10407 virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
10408
10409 // We disallow copying Tests.
10410 GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
10411 };
10412
10413 typedef internal::TimeInMillis TimeInMillis;
10414
10415 // A copyable object representing a user specified test property which can be
10416 // output as a key/value string pair.
10417 //
10418 // Don't inherit from TestProperty as its destructor is not virtual.
10419 class TestProperty {
10420 public:
10421 // C'tor. TestProperty does NOT have a default constructor.
10422 // Always use this constructor (with parameters) to create a
10423 // TestProperty object.
10424 TestProperty(const std::string& a_key, const std::string& a_value) :
10425 key_(a_key), value_(a_value) {
10426 }
10427
10428 // Gets the user supplied key.
10429 const char* key() const {
10430 return key_.c_str();
10431 }
10432
10433 // Gets the user supplied value.
10434 const char* value() const {
10435 return value_.c_str();
10436 }
10437
10438 // Sets a new value, overriding the one supplied in the constructor.
10439 void SetValue(const std::string& new_value) {
10440 value_ = new_value;
10441 }
10442
10443 private:
10444 // The key supplied by the user.
10445 std::string key_;
10446 // The value supplied by the user.
10447 std::string value_;
10448 };
10449
10450 // The result of a single Test. This includes a list of
10451 // TestPartResults, a list of TestProperties, a count of how many
10452 // death tests there are in the Test, and how much time it took to run
10453 // the Test.
10454 //
10455 // TestResult is not copyable.
10456 class GTEST_API_ TestResult {
10457 public:
10458 // Creates an empty TestResult.
10459 TestResult();
10460
10461 // D'tor. Do not inherit from TestResult.
10462 ~TestResult();
10463
10464 // Gets the number of all test parts. This is the sum of the number
10465 // of successful test parts and the number of failed test parts.
10466 int total_part_count() const;
10467
10468 // Returns the number of the test properties.
10469 int test_property_count() const;
10470
10471 // Returns true if and only if the test passed (i.e. no test part failed).
10472 bool Passed() const { return !Skipped() && !Failed(); }
10473
10474 // Returns true if and only if the test was skipped.
10475 bool Skipped() const;
10476
10477 // Returns true if and only if the test failed.
10478 bool Failed() const;
10479
10480 // Returns true if and only if the test fatally failed.
10481 bool HasFatalFailure() const;
10482
10483 // Returns true if and only if the test has a non-fatal failure.
10484 bool HasNonfatalFailure() const;
10485
10486 // Returns the elapsed time, in milliseconds.
10487 TimeInMillis elapsed_time() const { return elapsed_time_; }
10488
10489 // Gets the time of the test case start, in ms from the start of the
10490 // UNIX epoch.
10491 TimeInMillis start_timestamp() const { return start_timestamp_; }
10492
10493 // Returns the i-th test part result among all the results. i can range from 0
10494 // to total_part_count() - 1. If i is not in that range, aborts the program.
10495 const TestPartResult& GetTestPartResult(int i) const;
10496
10497 // Returns the i-th test property. i can range from 0 to
10498 // test_property_count() - 1. If i is not in that range, aborts the
10499 // program.
10500 const TestProperty& GetTestProperty(int i) const;
10501
10502 private:
10503 friend class TestInfo;
10504 friend class TestSuite;
10505 friend class UnitTest;
10506 friend class internal::DefaultGlobalTestPartResultReporter;
10507 friend class internal::ExecDeathTest;
10508 friend class internal::TestResultAccessor;
10509 friend class internal::UnitTestImpl;
10510 friend class internal::WindowsDeathTest;
10511 friend class internal::FuchsiaDeathTest;
10512
10513 // Gets the vector of TestPartResults.
10514 const std::vector<TestPartResult>& test_part_results() const {
10515 return test_part_results_;
10516 }
10517
10518 // Gets the vector of TestProperties.
10519 const std::vector<TestProperty>& test_properties() const {
10520 return test_properties_;
10521 }
10522
10523 // Sets the start time.
10524 void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }
10525
10526 // Sets the elapsed time.
10527 void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
10528
10529 // Adds a test property to the list. The property is validated and may add
10530 // a non-fatal failure if invalid (e.g., if it conflicts with reserved
10531 // key names). If a property is already recorded for the same key, the
10532 // value will be updated, rather than storing multiple values for the same
10533 // key. xml_element specifies the element for which the property is being
10534 // recorded and is used for validation.
10535 void RecordProperty(const std::string& xml_element,
10536 const TestProperty& test_property);
10537
10538 // Adds a failure if the key is a reserved attribute of Google Test
10539 // testsuite tags. Returns true if the property is valid.
10540 // FIXME: Validate attribute names are legal and human readable.
10541 static bool ValidateTestProperty(const std::string& xml_element,
10542 const TestProperty& test_property);
10543
10544 // Adds a test part result to the list.
10545 void AddTestPartResult(const TestPartResult& test_part_result);
10546
10547 // Returns the death test count.
10548 int death_test_count() const { return death_test_count_; }
10549
10550 // Increments the death test count, returning the new count.
10551 int increment_death_test_count() { return ++death_test_count_; }
10552
10553 // Clears the test part results.
10554 void ClearTestPartResults();
10555
10556 // Clears the object.
10557 void Clear();
10558
10559 // Protects mutable state of the property vector and of owned
10560 // properties, whose values may be updated.
10561 internal::Mutex test_properties_mutex_;
10562
10563 // The vector of TestPartResults
10564 std::vector<TestPartResult> test_part_results_;
10565 // The vector of TestProperties
10566 std::vector<TestProperty> test_properties_;
10567 // Running count of death tests.
10568 int death_test_count_;
10569 // The start time, in milliseconds since UNIX Epoch.
10570 TimeInMillis start_timestamp_;
10571 // The elapsed time, in milliseconds.
10572 TimeInMillis elapsed_time_;
10573
10574 // We disallow copying TestResult.
10575 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
10576 }; // class TestResult
10577
10578 // A TestInfo object stores the following information about a test:
10579 //
10580 // Test suite name
10581 // Test name
10582 // Whether the test should be run
10583 // A function pointer that creates the test object when invoked
10584 // Test result
10585 //
10586 // The constructor of TestInfo registers itself with the UnitTest
10587 // singleton such that the RUN_ALL_TESTS() macro knows which tests to
10588 // run.
10589 class GTEST_API_ TestInfo {
10590 public:
10591 // Destructs a TestInfo object. This function is not virtual, so
10592 // don't inherit from TestInfo.
10593 ~TestInfo();
10594
10595 // Returns the test suite name.
10596 const char* test_suite_name() const { return test_suite_name_.c_str(); }
10597
10598 // Legacy API is deprecated but still available
10599 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10600 const char* test_case_name() const { return test_suite_name(); }
10601 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10602
10603 // Returns the test name.
10604 const char* name() const { return name_.c_str(); }
10605
10606 // Returns the name of the parameter type, or NULL if this is not a typed
10607 // or a type-parameterized test.
10608 const char* type_param() const {
10609 if (type_param_.get() != nullptr) return type_param_->c_str();
10610 return nullptr;
10611 }
10612
10613 // Returns the text representation of the value parameter, or NULL if this
10614 // is not a value-parameterized test.
10615 const char* value_param() const {
10616 if (value_param_.get() != nullptr) return value_param_->c_str();
10617 return nullptr;
10618 }
10619
10620 // Returns the file name where this test is defined.
10621 const char* file() const { return location_.file.c_str(); }
10622
10623 // Returns the line where this test is defined.
10624 int line() const { return location_.line; }
10625
10626 // Return true if this test should not be run because it's in another shard.
10627 bool is_in_another_shard() const { return is_in_another_shard_; }
10628
10629 // Returns true if this test should run, that is if the test is not
10630 // disabled (or it is disabled but the also_run_disabled_tests flag has
10631 // been specified) and its full name matches the user-specified filter.
10632 //
10633 // Google Test allows the user to filter the tests by their full names.
10634 // The full name of a test Bar in test suite Foo is defined as
10635 // "Foo.Bar". Only the tests that match the filter will run.
10636 //
10637 // A filter is a colon-separated list of glob (not regex) patterns,
10638 // optionally followed by a '-' and a colon-separated list of
10639 // negative patterns (tests to exclude). A test is run if it
10640 // matches one of the positive patterns and does not match any of
10641 // the negative patterns.
10642 //
10643 // For example, *A*:Foo.* is a filter that matches any string that
10644 // contains the character 'A' or starts with "Foo.".
10645 bool should_run() const { return should_run_; }
10646
10647 // Returns true if and only if this test will appear in the XML report.
10648 bool is_reportable() const {
10649 // The XML report includes tests matching the filter, excluding those
10650 // run in other shards.
10651 return matches_filter_ && !is_in_another_shard_;
10652 }
10653
10654 // Returns the result of the test.
10655 const TestResult* result() const { return &result_; }
10656
10657 private:
10658 #if GTEST_HAS_DEATH_TEST
10659 friend class internal::DefaultDeathTestFactory;
10660 #endif // GTEST_HAS_DEATH_TEST
10661 friend class Test;
10662 friend class TestSuite;
10663 friend class internal::UnitTestImpl;
10664 friend class internal::StreamingListenerTest;
10665 friend TestInfo* internal::MakeAndRegisterTestInfo(
10666 const char* test_suite_name, const char* name, const char* type_param,
10667 const char* value_param, internal::CodeLocation code_location,
10668 internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
10669 internal::TearDownTestSuiteFunc tear_down_tc,
10670 internal::TestFactoryBase* factory);
10671
10672 // Constructs a TestInfo object. The newly constructed instance assumes
10673 // ownership of the factory object.
10674 TestInfo(const std::string& test_suite_name, const std::string& name,
10675 const char* a_type_param, // NULL if not a type-parameterized test
10676 const char* a_value_param, // NULL if not a value-parameterized test
10677 internal::CodeLocation a_code_location,
10678 internal::TypeId fixture_class_id,
10679 internal::TestFactoryBase* factory);
10680
10681 // Increments the number of death tests encountered in this test so
10682 // far.
10683 int increment_death_test_count() {
10684 return result_.increment_death_test_count();
10685 }
10686
10687 // Creates the test object, runs it, records its result, and then
10688 // deletes it.
10689 void Run();
10690
10691 // Skip and records the test result for this object.
10692 void Skip();
10693
10694 static void ClearTestResult(TestInfo* test_info) {
10695 test_info->result_.Clear();
10696 }
10697
10698 // These fields are immutable properties of the test.
10699 const std::string test_suite_name_; // test suite name
10700 const std::string name_; // Test name
10701 // Name of the parameter type, or NULL if this is not a typed or a
10702 // type-parameterized test.
10703 const std::unique_ptr<const ::std::string> type_param_;
10704 // Text representation of the value parameter, or NULL if this is not a
10705 // value-parameterized test.
10706 const std::unique_ptr<const ::std::string> value_param_;
10707 internal::CodeLocation location_;
10708 const internal::TypeId fixture_class_id_; // ID of the test fixture class
10709 bool should_run_; // True if and only if this test should run
10710 bool is_disabled_; // True if and only if this test is disabled
10711 bool matches_filter_; // True if this test matches the
10712 // user-specified filter.
10713 bool is_in_another_shard_; // Will be run in another shard.
10714 internal::TestFactoryBase* const factory_; // The factory that creates
10715 // the test object
10716
10717 // This field is mutable and needs to be reset before running the
10718 // test for the second time.
10719 TestResult result_;
10720
10721 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
10722 };
10723
10724 // A test suite, which consists of a vector of TestInfos.
10725 //
10726 // TestSuite is not copyable.
10727 class GTEST_API_ TestSuite {
10728 public:
10729 // Creates a TestSuite with the given name.
10730 //
10731 // TestSuite does NOT have a default constructor. Always use this
10732 // constructor to create a TestSuite object.
10733 //
10734 // Arguments:
10735 //
10736 // name: name of the test suite
10737 // a_type_param: the name of the test's type parameter, or NULL if
10738 // this is not a type-parameterized test.
10739 // set_up_tc: pointer to the function that sets up the test suite
10740 // tear_down_tc: pointer to the function that tears down the test suite
10741 TestSuite(const char* name, const char* a_type_param,
10742 internal::SetUpTestSuiteFunc set_up_tc,
10743 internal::TearDownTestSuiteFunc tear_down_tc);
10744
10745 // Destructor of TestSuite.
10746 virtual ~TestSuite();
10747
10748 // Gets the name of the TestSuite.
10749 const char* name() const { return name_.c_str(); }
10750
10751 // Returns the name of the parameter type, or NULL if this is not a
10752 // type-parameterized test suite.
10753 const char* type_param() const {
10754 if (type_param_.get() != nullptr) return type_param_->c_str();
10755 return nullptr;
10756 }
10757
10758 // Returns true if any test in this test suite should run.
10759 bool should_run() const { return should_run_; }
10760
10761 // Gets the number of successful tests in this test suite.
10762 int successful_test_count() const;
10763
10764 // Gets the number of skipped tests in this test suite.
10765 int skipped_test_count() const;
10766
10767 // Gets the number of failed tests in this test suite.
10768 int failed_test_count() const;
10769
10770 // Gets the number of disabled tests that will be reported in the XML report.
10771 int reportable_disabled_test_count() const;
10772
10773 // Gets the number of disabled tests in this test suite.
10774 int disabled_test_count() const;
10775
10776 // Gets the number of tests to be printed in the XML report.
10777 int reportable_test_count() const;
10778
10779 // Get the number of tests in this test suite that should run.
10780 int test_to_run_count() const;
10781
10782 // Gets the number of all tests in this test suite.
10783 int total_test_count() const;
10784
10785 // Returns true if and only if the test suite passed.
10786 bool Passed() const { return !Failed(); }
10787
10788 // Returns true if and only if the test suite failed.
10789 bool Failed() const {
10790 return failed_test_count() > 0 || ad_hoc_test_result().Failed();
10791 }
10792
10793 // Returns the elapsed time, in milliseconds.
10794 TimeInMillis elapsed_time() const { return elapsed_time_; }
10795
10796 // Gets the time of the test suite start, in ms from the start of the
10797 // UNIX epoch.
10798 TimeInMillis start_timestamp() const { return start_timestamp_; }
10799
10800 // Returns the i-th test among all the tests. i can range from 0 to
10801 // total_test_count() - 1. If i is not in that range, returns NULL.
10802 const TestInfo* GetTestInfo(int i) const;
10803
10804 // Returns the TestResult that holds test properties recorded during
10805 // execution of SetUpTestSuite and TearDownTestSuite.
10806 const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
10807
10808 private:
10809 friend class Test;
10810 friend class internal::UnitTestImpl;
10811
10812 // Gets the (mutable) vector of TestInfos in this TestSuite.
10813 std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
10814
10815 // Gets the (immutable) vector of TestInfos in this TestSuite.
10816 const std::vector<TestInfo*>& test_info_list() const {
10817 return test_info_list_;
10818 }
10819
10820 // Returns the i-th test among all the tests. i can range from 0 to
10821 // total_test_count() - 1. If i is not in that range, returns NULL.
10822 TestInfo* GetMutableTestInfo(int i);
10823
10824 // Sets the should_run member.
10825 void set_should_run(bool should) { should_run_ = should; }
10826
10827 // Adds a TestInfo to this test suite. Will delete the TestInfo upon
10828 // destruction of the TestSuite object.
10829 void AddTestInfo(TestInfo * test_info);
10830
10831 // Clears the results of all tests in this test suite.
10832 void ClearResult();
10833
10834 // Clears the results of all tests in the given test suite.
10835 static void ClearTestSuiteResult(TestSuite* test_suite) {
10836 test_suite->ClearResult();
10837 }
10838
10839 // Runs every test in this TestSuite.
10840 void Run();
10841
10842 // Skips the execution of tests under this TestSuite
10843 void Skip();
10844
10845 // Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
10846 // for catching exceptions thrown from SetUpTestSuite().
10847 void RunSetUpTestSuite() {
10848 if (set_up_tc_ != nullptr) {
10849 (*set_up_tc_)();
10850 }
10851 }
10852
10853 // Runs TearDownTestSuite() for this TestSuite. This wrapper is
10854 // needed for catching exceptions thrown from TearDownTestSuite().
10855 void RunTearDownTestSuite() {
10856 if (tear_down_tc_ != nullptr) {
10857 (*tear_down_tc_)();
10858 }
10859 }
10860
10861 // Returns true if and only if test passed.
10862 static bool TestPassed(const TestInfo* test_info) {
10863 return test_info->should_run() && test_info->result()->Passed();
10864 }
10865
10866 // Returns true if and only if test skipped.
10867 static bool TestSkipped(const TestInfo* test_info) {
10868 return test_info->should_run() && test_info->result()->Skipped();
10869 }
10870
10871 // Returns true if and only if test failed.
10872 static bool TestFailed(const TestInfo* test_info) {
10873 return test_info->should_run() && test_info->result()->Failed();
10874 }
10875
10876 // Returns true if and only if the test is disabled and will be reported in
10877 // the XML report.
10878 static bool TestReportableDisabled(const TestInfo* test_info) {
10879 return test_info->is_reportable() && test_info->is_disabled_;
10880 }
10881
10882 // Returns true if and only if test is disabled.
10883 static bool TestDisabled(const TestInfo* test_info) {
10884 return test_info->is_disabled_;
10885 }
10886
10887 // Returns true if and only if this test will appear in the XML report.
10888 static bool TestReportable(const TestInfo* test_info) {
10889 return test_info->is_reportable();
10890 }
10891
10892 // Returns true if the given test should run.
10893 static bool ShouldRunTest(const TestInfo* test_info) {
10894 return test_info->should_run();
10895 }
10896
10897 // Shuffles the tests in this test suite.
10898 void ShuffleTests(internal::Random* random);
10899
10900 // Restores the test order to before the first shuffle.
10901 void UnshuffleTests();
10902
10903 // Name of the test suite.
10904 std::string name_;
10905 // Name of the parameter type, or NULL if this is not a typed or a
10906 // type-parameterized test.
10907 const std::unique_ptr<const ::std::string> type_param_;
10908 // The vector of TestInfos in their original order. It owns the
10909 // elements in the vector.
10910 std::vector<TestInfo*> test_info_list_;
10911 // Provides a level of indirection for the test list to allow easy
10912 // shuffling and restoring the test order. The i-th element in this
10913 // vector is the index of the i-th test in the shuffled test list.
10914 std::vector<int> test_indices_;
10915 // Pointer to the function that sets up the test suite.
10916 internal::SetUpTestSuiteFunc set_up_tc_;
10917 // Pointer to the function that tears down the test suite.
10918 internal::TearDownTestSuiteFunc tear_down_tc_;
10919 // True if and only if any test in this test suite should run.
10920 bool should_run_;
10921 // The start time, in milliseconds since UNIX Epoch.
10922 TimeInMillis start_timestamp_;
10923 // Elapsed time, in milliseconds.
10924 TimeInMillis elapsed_time_;
10925 // Holds test properties recorded during execution of SetUpTestSuite and
10926 // TearDownTestSuite.
10927 TestResult ad_hoc_test_result_;
10928
10929 // We disallow copying TestSuites.
10930 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite);
10931 };
10932
10933 // An Environment object is capable of setting up and tearing down an
10934 // environment. You should subclass this to define your own
10935 // environment(s).
10936 //
10937 // An Environment object does the set-up and tear-down in virtual
10938 // methods SetUp() and TearDown() instead of the constructor and the
10939 // destructor, as:
10940 //
10941 // 1. You cannot safely throw from a destructor. This is a problem
10942 // as in some cases Google Test is used where exceptions are enabled, and
10943 // we may want to implement ASSERT_* using exceptions where they are
10944 // available.
10945 // 2. You cannot use ASSERT_* directly in a constructor or
10946 // destructor.
10947 class Environment {
10948 public:
10949 // The d'tor is virtual as we need to subclass Environment.
10950 virtual ~Environment() {}
10951
10952 // Override this to define how to set up the environment.
10953 virtual void SetUp() {}
10954
10955 // Override this to define how to tear down the environment.
10956 virtual void TearDown() {}
10957 private:
10958 // If you see an error about overriding the following function or
10959 // about it being private, you have mis-spelled SetUp() as Setup().
10960 struct Setup_should_be_spelled_SetUp {};
10961 virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
10962 };
10963
10964 #if GTEST_HAS_EXCEPTIONS
10965
10966 // Exception which can be thrown from TestEventListener::OnTestPartResult.
10967 class GTEST_API_ AssertionException
10968 : public internal::GoogleTestFailureException {
10969 public:
10970 explicit AssertionException(const TestPartResult& result)
10971 : GoogleTestFailureException(result) {}
10972 };
10973
10974 #endif // GTEST_HAS_EXCEPTIONS
10975
10976 // The interface for tracing execution of tests. The methods are organized in
10977 // the order the corresponding events are fired.
10978 class TestEventListener {
10979 public:
10980 virtual ~TestEventListener() {}
10981
10982 // Fired before any test activity starts.
10983 virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
10984
10985 // Fired before each iteration of tests starts. There may be more than
10986 // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
10987 // index, starting from 0.
10988 virtual void OnTestIterationStart(const UnitTest& unit_test,
10989 int iteration) = 0;
10990
10991 // Fired before environment set-up for each iteration of tests starts.
10992 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
10993
10994 // Fired after environment set-up for each iteration of tests ends.
10995 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
10996
10997 // Fired before the test suite starts.
10998 virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}
10999
11000 // Legacy API is deprecated but still available
11001 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11002 virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
11003 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11004
11005 // Fired before the test starts.
11006 virtual void OnTestStart(const TestInfo& test_info) = 0;
11007
11008 // Fired after a failed assertion or a SUCCEED() invocation.
11009 // If you want to throw an exception from this function to skip to the next
11010 // TEST, it must be AssertionException defined above, or inherited from it.
11011 virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
11012
11013 // Fired after the test ends.
11014 virtual void OnTestEnd(const TestInfo& test_info) = 0;
11015
11016 // Fired after the test suite ends.
11017 virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}
11018
11019 // Legacy API is deprecated but still available
11020 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11021 virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
11022 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11023
11024 // Fired before environment tear-down for each iteration of tests starts.
11025 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
11026
11027 // Fired after environment tear-down for each iteration of tests ends.
11028 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
11029
11030 // Fired after each iteration of tests finishes.
11031 virtual void OnTestIterationEnd(const UnitTest& unit_test,
11032 int iteration) = 0;
11033
11034 // Fired after all test activities have ended.
11035 virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
11036 };
11037
11038 // The convenience class for users who need to override just one or two
11039 // methods and are not concerned that a possible change to a signature of
11040 // the methods they override will not be caught during the build. For
11041 // comments about each method please see the definition of TestEventListener
11042 // above.
11043 class EmptyTestEventListener : public TestEventListener {
11044 public:
11045 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
11046 void OnTestIterationStart(const UnitTest& /*unit_test*/,
11047 int /*iteration*/) override {}
11048 void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
11049 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
11050 void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
11051 // Legacy API is deprecated but still available
11052 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11053 void OnTestCaseStart(const TestCase& /*test_case*/) override {}
11054 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11055
11056 void OnTestStart(const TestInfo& /*test_info*/) override {}
11057 void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
11058 void OnTestEnd(const TestInfo& /*test_info*/) override {}
11059 void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
11060 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11061 void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
11062 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11063
11064 void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
11065 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
11066 void OnTestIterationEnd(const UnitTest& /*unit_test*/,
11067 int /*iteration*/) override {}
11068 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
11069 };
11070
11071 // TestEventListeners lets users add listeners to track events in Google Test.
11072 class GTEST_API_ TestEventListeners {
11073 public:
11074 TestEventListeners();
11075 ~TestEventListeners();
11076
11077 // Appends an event listener to the end of the list. Google Test assumes
11078 // the ownership of the listener (i.e. it will delete the listener when
11079 // the test program finishes).
11080 void Append(TestEventListener* listener);
11081
11082 // Removes the given event listener from the list and returns it. It then
11083 // becomes the caller's responsibility to delete the listener. Returns
11084 // NULL if the listener is not found in the list.
11085 TestEventListener* Release(TestEventListener* listener);
11086
11087 // Returns the standard listener responsible for the default console
11088 // output. Can be removed from the listeners list to shut down default
11089 // console output. Note that removing this object from the listener list
11090 // with Release transfers its ownership to the caller and makes this
11091 // function return NULL the next time.
11092 TestEventListener* default_result_printer() const {
11093 return default_result_printer_;
11094 }
11095
11096 // Returns the standard listener responsible for the default XML output
11097 // controlled by the --gtest_output=xml flag. Can be removed from the
11098 // listeners list by users who want to shut down the default XML output
11099 // controlled by this flag and substitute it with custom one. Note that
11100 // removing this object from the listener list with Release transfers its
11101 // ownership to the caller and makes this function return NULL the next
11102 // time.
11103 TestEventListener* default_xml_generator() const {
11104 return default_xml_generator_;
11105 }
11106
11107 private:
11108 friend class TestSuite;
11109 friend class TestInfo;
11110 friend class internal::DefaultGlobalTestPartResultReporter;
11111 friend class internal::NoExecDeathTest;
11112 friend class internal::TestEventListenersAccessor;
11113 friend class internal::UnitTestImpl;
11114
11115 // Returns repeater that broadcasts the TestEventListener events to all
11116 // subscribers.
11117 TestEventListener* repeater();
11118
11119 // Sets the default_result_printer attribute to the provided listener.
11120 // The listener is also added to the listener list and previous
11121 // default_result_printer is removed from it and deleted. The listener can
11122 // also be NULL in which case it will not be added to the list. Does
11123 // nothing if the previous and the current listener objects are the same.
11124 void SetDefaultResultPrinter(TestEventListener* listener);
11125
11126 // Sets the default_xml_generator attribute to the provided listener. The
11127 // listener is also added to the listener list and previous
11128 // default_xml_generator is removed from it and deleted. The listener can
11129 // also be NULL in which case it will not be added to the list. Does
11130 // nothing if the previous and the current listener objects are the same.
11131 void SetDefaultXmlGenerator(TestEventListener* listener);
11132
11133 // Controls whether events will be forwarded by the repeater to the
11134 // listeners in the list.
11135 bool EventForwardingEnabled() const;
11136 void SuppressEventForwarding();
11137
11138 // The actual list of listeners.
11139 internal::TestEventRepeater* repeater_;
11140 // Listener responsible for the standard result output.
11141 TestEventListener* default_result_printer_;
11142 // Listener responsible for the creation of the XML output file.
11143 TestEventListener* default_xml_generator_;
11144
11145 // We disallow copying TestEventListeners.
11146 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
11147 };
11148
11149 // A UnitTest consists of a vector of TestSuites.
11150 //
11151 // This is a singleton class. The only instance of UnitTest is
11152 // created when UnitTest::GetInstance() is first called. This
11153 // instance is never deleted.
11154 //
11155 // UnitTest is not copyable.
11156 //
11157 // This class is thread-safe as long as the methods are called
11158 // according to their specification.
11159 class GTEST_API_ UnitTest {
11160 public:
11161 // Gets the singleton UnitTest object. The first time this method
11162 // is called, a UnitTest object is constructed and returned.
11163 // Consecutive calls will return the same object.
11164 static UnitTest* GetInstance();
11165
11166 // Runs all tests in this UnitTest object and prints the result.
11167 // Returns 0 if successful, or 1 otherwise.
11168 //
11169 // This method can only be called from the main thread.
11170 //
11171 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11172 int Run() GTEST_MUST_USE_RESULT_;
11173
11174 // Returns the working directory when the first TEST() or TEST_F()
11175 // was executed. The UnitTest object owns the string.
11176 const char* original_working_dir() const;
11177
11178 // Returns the TestSuite object for the test that's currently running,
11179 // or NULL if no test is running.
11180 const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);
11181
11182 // Legacy API is still available but deprecated
11183 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11184 const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);
11185 #endif
11186
11187 // Returns the TestInfo object for the test that's currently running,
11188 // or NULL if no test is running.
11189 const TestInfo* current_test_info() const
11190 GTEST_LOCK_EXCLUDED_(mutex_);
11191
11192 // Returns the random seed used at the start of the current test run.
11193 int random_seed() const;
11194
11195 // Returns the ParameterizedTestSuiteRegistry object used to keep track of
11196 // value-parameterized tests and instantiate and register them.
11197 //
11198 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11199 internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()
11200 GTEST_LOCK_EXCLUDED_(mutex_);
11201
11202 // Gets the number of successful test suites.
11203 int successful_test_suite_count() const;
11204
11205 // Gets the number of failed test suites.
11206 int failed_test_suite_count() const;
11207
11208 // Gets the number of all test suites.
11209 int total_test_suite_count() const;
11210
11211 // Gets the number of all test suites that contain at least one test
11212 // that should run.
11213 int test_suite_to_run_count() const;
11214
11215 // Legacy API is deprecated but still available
11216 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11217 int successful_test_case_count() const;
11218 int failed_test_case_count() const;
11219 int total_test_case_count() const;
11220 int test_case_to_run_count() const;
11221 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11222
11223 // Gets the number of successful tests.
11224 int successful_test_count() const;
11225
11226 // Gets the number of skipped tests.
11227 int skipped_test_count() const;
11228
11229 // Gets the number of failed tests.
11230 int failed_test_count() const;
11231
11232 // Gets the number of disabled tests that will be reported in the XML report.
11233 int reportable_disabled_test_count() const;
11234
11235 // Gets the number of disabled tests.
11236 int disabled_test_count() const;
11237
11238 // Gets the number of tests to be printed in the XML report.
11239 int reportable_test_count() const;
11240
11241 // Gets the number of all tests.
11242 int total_test_count() const;
11243
11244 // Gets the number of tests that should run.
11245 int test_to_run_count() const;
11246
11247 // Gets the time of the test program start, in ms from the start of the
11248 // UNIX epoch.
11249 TimeInMillis start_timestamp() const;
11250
11251 // Gets the elapsed time, in milliseconds.
11252 TimeInMillis elapsed_time() const;
11253
11254 // Returns true if and only if the unit test passed (i.e. all test suites
11255 // passed).
11256 bool Passed() const;
11257
11258 // Returns true if and only if the unit test failed (i.e. some test suite
11259 // failed or something outside of all tests failed).
11260 bool Failed() const;
11261
11262 // Gets the i-th test suite among all the test suites. i can range from 0 to
11263 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
11264 const TestSuite* GetTestSuite(int i) const;
11265
11266 // Legacy API is deprecated but still available
11267 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11268 const TestCase* GetTestCase(int i) const;
11269 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11270
11271 // Returns the TestResult containing information on test failures and
11272 // properties logged outside of individual test suites.
11273 const TestResult& ad_hoc_test_result() const;
11274
11275 // Returns the list of event listeners that can be used to track events
11276 // inside Google Test.
11277 TestEventListeners& listeners();
11278
11279 private:
11280 // Registers and returns a global test environment. When a test
11281 // program is run, all global test environments will be set-up in
11282 // the order they were registered. After all tests in the program
11283 // have finished, all global test environments will be torn-down in
11284 // the *reverse* order they were registered.
11285 //
11286 // The UnitTest object takes ownership of the given environment.
11287 //
11288 // This method can only be called from the main thread.
11289 Environment* AddEnvironment(Environment* env);
11290
11291 // Adds a TestPartResult to the current TestResult object. All
11292 // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
11293 // eventually call this to report their results. The user code
11294 // should use the assertion macros instead of calling this directly.
11295 void AddTestPartResult(TestPartResult::Type result_type,
11296 const char* file_name,
11297 int line_number,
11298 const std::string& message,
11299 const std::string& os_stack_trace)
11300 GTEST_LOCK_EXCLUDED_(mutex_);
11301
11302 // Adds a TestProperty to the current TestResult object when invoked from
11303 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
11304 // from SetUpTestSuite or TearDownTestSuite, or to the global property set
11305 // when invoked elsewhere. If the result already contains a property with
11306 // the same key, the value will be updated.
11307 void RecordProperty(const std::string& key, const std::string& value);
11308
11309 // Gets the i-th test suite among all the test suites. i can range from 0 to
11310 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
11311 TestSuite* GetMutableTestSuite(int i);
11312
11313 // Accessors for the implementation object.
11314 internal::UnitTestImpl* impl() { return impl_; }
11315 const internal::UnitTestImpl* impl() const { return impl_; }
11316
11317 // These classes and functions are friends as they need to access private
11318 // members of UnitTest.
11319 friend class ScopedTrace;
11320 friend class Test;
11321 friend class internal::AssertHelper;
11322 friend class internal::StreamingListenerTest;
11323 friend class internal::UnitTestRecordPropertyTestHelper;
11324 friend Environment* AddGlobalTestEnvironment(Environment* env);
11325 friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
11326 friend internal::UnitTestImpl* internal::GetUnitTestImpl();
11327 friend void internal::ReportFailureInUnknownLocation(
11328 TestPartResult::Type result_type,
11329 const std::string& message);
11330
11331 // Creates an empty UnitTest.
11332 UnitTest();
11333
11334 // D'tor
11335 virtual ~UnitTest();
11336
11337 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
11338 // Google Test trace stack.
11339 void PushGTestTrace(const internal::TraceInfo& trace)
11340 GTEST_LOCK_EXCLUDED_(mutex_);
11341
11342 // Pops a trace from the per-thread Google Test trace stack.
11343 void PopGTestTrace()
11344 GTEST_LOCK_EXCLUDED_(mutex_);
11345
11346 // Protects mutable state in *impl_. This is mutable as some const
11347 // methods need to lock it too.
11348 mutable internal::Mutex mutex_;
11349
11350 // Opaque implementation object. This field is never changed once
11351 // the object is constructed. We don't mark it as const here, as
11352 // doing so will cause a warning in the constructor of UnitTest.
11353 // Mutable state in *impl_ is protected by mutex_.
11354 internal::UnitTestImpl* impl_;
11355
11356 // We disallow copying UnitTest.
11357 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
11358 };
11359
11360 // A convenient wrapper for adding an environment for the test
11361 // program.
11362 //
11363 // You should call this before RUN_ALL_TESTS() is called, probably in
11364 // main(). If you use gtest_main, you need to call this before main()
11365 // starts for it to take effect. For example, you can define a global
11366 // variable like this:
11367 //
11368 // testing::Environment* const foo_env =
11369 // testing::AddGlobalTestEnvironment(new FooEnvironment);
11370 //
11371 // However, we strongly recommend you to write your own main() and
11372 // call AddGlobalTestEnvironment() there, as relying on initialization
11373 // of global variables makes the code harder to read and may cause
11374 // problems when you register multiple environments from different
11375 // translation units and the environments have dependencies among them
11376 // (remember that the compiler doesn't guarantee the order in which
11377 // global variables from different translation units are initialized).
11378 inline Environment* AddGlobalTestEnvironment(Environment* env) {
11379 return UnitTest::GetInstance()->AddEnvironment(env);
11380 }
11381
11382 // Initializes Google Test. This must be called before calling
11383 // RUN_ALL_TESTS(). In particular, it parses a command line for the
11384 // flags that Google Test recognizes. Whenever a Google Test flag is
11385 // seen, it is removed from argv, and *argc is decremented.
11386 //
11387 // No value is returned. Instead, the Google Test flag variables are
11388 // updated.
11389 //
11390 // Calling the function for the second time has no user-visible effect.
11391 GTEST_API_ void InitGoogleTest(int* argc, char** argv);
11392
11393 // This overloaded version can be used in Windows programs compiled in
11394 // UNICODE mode.
11395 GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
11396
11397 // This overloaded version can be used on Arduino/embedded platforms where
11398 // there is no argc/argv.
11399 GTEST_API_ void InitGoogleTest();
11400
11401 namespace internal {
11402
11403 // Separate the error generating code from the code path to reduce the stack
11404 // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
11405 // when calling EXPECT_* in a tight loop.
11406 template <typename T1, typename T2>
11407 AssertionResult CmpHelperEQFailure(const char* lhs_expression,
11408 const char* rhs_expression,
11409 const T1& lhs, const T2& rhs) {
11410 return EqFailure(lhs_expression,
11411 rhs_expression,
11412 FormatForComparisonFailureMessage(lhs, rhs),
11413 FormatForComparisonFailureMessage(rhs, lhs),
11414 false);
11415 }
11416
11417 // This block of code defines operator==/!=
11418 // to block lexical scope lookup.
11419 // It prevents using invalid operator==/!= defined at namespace scope.
11420 struct faketype {};
11421 inline bool operator==(faketype, faketype) { return true; }
11422 inline bool operator!=(faketype, faketype) { return false; }
11423
11424 // The helper function for {ASSERT|EXPECT}_EQ.
11425 template <typename T1, typename T2>
11426 AssertionResult CmpHelperEQ(const char* lhs_expression,
11427 const char* rhs_expression,
11428 const T1& lhs,
11429 const T2& rhs) {
11430 if (lhs == rhs) {
11431 return AssertionSuccess();
11432 }
11433
11434 return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
11435 }
11436
11437 class EqHelper {
11438 public:
11439 // This templatized version is for the general case.
11440 template <
11441 typename T1, typename T2,
11442 // Disable this overload for cases where one argument is a pointer
11443 // and the other is the null pointer constant.
11444 typename std::enable_if<!std::is_integral<T1>::value ||
11445 !std::is_pointer<T2>::value>::type* = nullptr>
11446 static AssertionResult Compare(const char* lhs_expression,
11447 const char* rhs_expression, const T1& lhs,
11448 const T2& rhs) {
11449 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
11450 }
11451
11452 // With this overloaded version, we allow anonymous enums to be used
11453 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
11454 // enums can be implicitly cast to BiggestInt.
11455 //
11456 // Even though its body looks the same as the above version, we
11457 // cannot merge the two, as it will make anonymous enums unhappy.
11458 static AssertionResult Compare(const char* lhs_expression,
11459 const char* rhs_expression,
11460 BiggestInt lhs,
11461 BiggestInt rhs) {
11462 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
11463 }
11464
11465 template <typename T>
11466 static AssertionResult Compare(
11467 const char* lhs_expression, const char* rhs_expression,
11468 // Handle cases where '0' is used as a null pointer literal.
11469 std::nullptr_t /* lhs */, T* rhs) {
11470 // We already know that 'lhs' is a null pointer.
11471 return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),
11472 rhs);
11473 }
11474 };
11475
11476 // Separate the error generating code from the code path to reduce the stack
11477 // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
11478 // when calling EXPECT_OP in a tight loop.
11479 template <typename T1, typename T2>
11480 AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
11481 const T1& val1, const T2& val2,
11482 const char* op) {
11483 return AssertionFailure()
11484 << "Expected: (" << expr1 << ") " << op << " (" << expr2
11485 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
11486 << " vs " << FormatForComparisonFailureMessage(val2, val1);
11487 }
11488
11489 // A macro for implementing the helper functions needed to implement
11490 // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
11491 // of similar code.
11492 //
11493 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11494
11495 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
11496 template <typename T1, typename T2>\
11497 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
11498 const T1& val1, const T2& val2) {\
11499 if (val1 op val2) {\
11500 return AssertionSuccess();\
11501 } else {\
11502 return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
11503 }\
11504 }
11505
11506 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11507
11508 // Implements the helper function for {ASSERT|EXPECT}_NE
11509 GTEST_IMPL_CMP_HELPER_(NE, !=)
11510 // Implements the helper function for {ASSERT|EXPECT}_LE
11511 GTEST_IMPL_CMP_HELPER_(LE, <=)
11512 // Implements the helper function for {ASSERT|EXPECT}_LT
11513 GTEST_IMPL_CMP_HELPER_(LT, <)
11514 // Implements the helper function for {ASSERT|EXPECT}_GE
11515 GTEST_IMPL_CMP_HELPER_(GE, >=)
11516 // Implements the helper function for {ASSERT|EXPECT}_GT
11517 GTEST_IMPL_CMP_HELPER_(GT, >)
11518
11519 #undef GTEST_IMPL_CMP_HELPER_
11520
11521 // The helper function for {ASSERT|EXPECT}_STREQ.
11522 //
11523 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11524 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
11525 const char* s2_expression,
11526 const char* s1,
11527 const char* s2);
11528
11529 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
11530 //
11531 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11532 GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
11533 const char* s2_expression,
11534 const char* s1,
11535 const char* s2);
11536
11537 // The helper function for {ASSERT|EXPECT}_STRNE.
11538 //
11539 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11540 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
11541 const char* s2_expression,
11542 const char* s1,
11543 const char* s2);
11544
11545 // The helper function for {ASSERT|EXPECT}_STRCASENE.
11546 //
11547 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11548 GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
11549 const char* s2_expression,
11550 const char* s1,
11551 const char* s2);
11552
11553
11554 // Helper function for *_STREQ on wide strings.
11555 //
11556 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11557 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
11558 const char* s2_expression,
11559 const wchar_t* s1,
11560 const wchar_t* s2);
11561
11562 // Helper function for *_STRNE on wide strings.
11563 //
11564 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11565 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
11566 const char* s2_expression,
11567 const wchar_t* s1,
11568 const wchar_t* s2);
11569
11570 } // namespace internal
11571
11572 // IsSubstring() and IsNotSubstring() are intended to be used as the
11573 // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
11574 // themselves. They check whether needle is a substring of haystack
11575 // (NULL is considered a substring of itself only), and return an
11576 // appropriate error message when they fail.
11577 //
11578 // The {needle,haystack}_expr arguments are the stringified
11579 // expressions that generated the two real arguments.
11580 GTEST_API_ AssertionResult IsSubstring(
11581 const char* needle_expr, const char* haystack_expr,
11582 const char* needle, const char* haystack);
11583 GTEST_API_ AssertionResult IsSubstring(
11584 const char* needle_expr, const char* haystack_expr,
11585 const wchar_t* needle, const wchar_t* haystack);
11586 GTEST_API_ AssertionResult IsNotSubstring(
11587 const char* needle_expr, const char* haystack_expr,
11588 const char* needle, const char* haystack);
11589 GTEST_API_ AssertionResult IsNotSubstring(
11590 const char* needle_expr, const char* haystack_expr,
11591 const wchar_t* needle, const wchar_t* haystack);
11592 GTEST_API_ AssertionResult IsSubstring(
11593 const char* needle_expr, const char* haystack_expr,
11594 const ::std::string& needle, const ::std::string& haystack);
11595 GTEST_API_ AssertionResult IsNotSubstring(
11596 const char* needle_expr, const char* haystack_expr,
11597 const ::std::string& needle, const ::std::string& haystack);
11598
11599 #if GTEST_HAS_STD_WSTRING
11600 GTEST_API_ AssertionResult IsSubstring(
11601 const char* needle_expr, const char* haystack_expr,
11602 const ::std::wstring& needle, const ::std::wstring& haystack);
11603 GTEST_API_ AssertionResult IsNotSubstring(
11604 const char* needle_expr, const char* haystack_expr,
11605 const ::std::wstring& needle, const ::std::wstring& haystack);
11606 #endif // GTEST_HAS_STD_WSTRING
11607
11608 namespace internal {
11609
11610 // Helper template function for comparing floating-points.
11611 //
11612 // Template parameter:
11613 //
11614 // RawType: the raw floating-point type (either float or double)
11615 //
11616 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11617 template <typename RawType>
11618 AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
11619 const char* rhs_expression,
11620 RawType lhs_value,
11621 RawType rhs_value) {
11622 const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
11623
11624 if (lhs.AlmostEquals(rhs)) {
11625 return AssertionSuccess();
11626 }
11627
11628 ::std::stringstream lhs_ss;
11629 lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
11630 << lhs_value;
11631
11632 ::std::stringstream rhs_ss;
11633 rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
11634 << rhs_value;
11635
11636 return EqFailure(lhs_expression,
11637 rhs_expression,
11638 StringStreamToString(&lhs_ss),
11639 StringStreamToString(&rhs_ss),
11640 false);
11641 }
11642
11643 // Helper function for implementing ASSERT_NEAR.
11644 //
11645 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11646 GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
11647 const char* expr2,
11648 const char* abs_error_expr,
11649 double val1,
11650 double val2,
11651 double abs_error);
11652
11653 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
11654 // A class that enables one to stream messages to assertion macros
11655 class GTEST_API_ AssertHelper {
11656 public:
11657 // Constructor.
11658 AssertHelper(TestPartResult::Type type,
11659 const char* file,
11660 int line,
11661 const char* message);
11662 ~AssertHelper();
11663
11664 // Message assignment is a semantic trick to enable assertion
11665 // streaming; see the GTEST_MESSAGE_ macro below.
11666 void operator=(const Message& message) const;
11667
11668 private:
11669 // We put our data in a struct so that the size of the AssertHelper class can
11670 // be as small as possible. This is important because gcc is incapable of
11671 // re-using stack space even for temporary variables, so every EXPECT_EQ
11672 // reserves stack space for another AssertHelper.
11673 struct AssertHelperData {
11674 AssertHelperData(TestPartResult::Type t,
11675 const char* srcfile,
11676 int line_num,
11677 const char* msg)
11678 : type(t), file(srcfile), line(line_num), message(msg) { }
11679
11680 TestPartResult::Type const type;
11681 const char* const file;
11682 int const line;
11683 std::string const message;
11684
11685 private:
11686 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
11687 };
11688
11689 AssertHelperData* const data_;
11690
11691 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
11692 };
11693
11694 } // namespace internal
11695
11696 // The pure interface class that all value-parameterized tests inherit from.
11697 // A value-parameterized class must inherit from both ::testing::Test and
11698 // ::testing::WithParamInterface. In most cases that just means inheriting
11699 // from ::testing::TestWithParam, but more complicated test hierarchies
11700 // may need to inherit from Test and WithParamInterface at different levels.
11701 //
11702 // This interface has support for accessing the test parameter value via
11703 // the GetParam() method.
11704 //
11705 // Use it with one of the parameter generator defining functions, like Range(),
11706 // Values(), ValuesIn(), Bool(), and Combine().
11707 //
11708 // class FooTest : public ::testing::TestWithParam<int> {
11709 // protected:
11710 // FooTest() {
11711 // // Can use GetParam() here.
11712 // }
11713 // ~FooTest() override {
11714 // // Can use GetParam() here.
11715 // }
11716 // void SetUp() override {
11717 // // Can use GetParam() here.
11718 // }
11719 // void TearDown override {
11720 // // Can use GetParam() here.
11721 // }
11722 // };
11723 // TEST_P(FooTest, DoesBar) {
11724 // // Can use GetParam() method here.
11725 // Foo foo;
11726 // ASSERT_TRUE(foo.DoesBar(GetParam()));
11727 // }
11728 // INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
11729
11730 template <typename T>
11731 class WithParamInterface {
11732 public:
11733 typedef T ParamType;
11734 virtual ~WithParamInterface() {}
11735
11736 // The current parameter value. Is also available in the test fixture's
11737 // constructor.
11738 static const ParamType& GetParam() {
11739 GTEST_CHECK_(parameter_ != nullptr)
11740 << "GetParam() can only be called inside a value-parameterized test "
11741 << "-- did you intend to write TEST_P instead of TEST_F?";
11742 return *parameter_;
11743 }
11744
11745 private:
11746 // Sets parameter value. The caller is responsible for making sure the value
11747 // remains alive and unchanged throughout the current test.
11748 static void SetParam(const ParamType* parameter) {
11749 parameter_ = parameter;
11750 }
11751
11752 // Static value used for accessing parameter during a test lifetime.
11753 static const ParamType* parameter_;
11754
11755 // TestClass must be a subclass of WithParamInterface<T> and Test.
11756 template <class TestClass> friend class internal::ParameterizedTestFactory;
11757 };
11758
11759 template <typename T>
11760 const T* WithParamInterface<T>::parameter_ = nullptr;
11761
11762 // Most value-parameterized classes can ignore the existence of
11763 // WithParamInterface, and can just inherit from ::testing::TestWithParam.
11764
11765 template <typename T>
11766 class TestWithParam : public Test, public WithParamInterface<T> {
11767 };
11768
11769 // Macros for indicating success/failure in test code.
11770
11771 // Skips test in runtime.
11772 // Skipping test aborts current function.
11773 // Skipped tests are neither successful nor failed.
11774 #define GTEST_SKIP() GTEST_SKIP_("")
11775
11776 // ADD_FAILURE unconditionally adds a failure to the current test.
11777 // SUCCEED generates a success - it doesn't automatically make the
11778 // current test successful, as a test is only successful when it has
11779 // no failure.
11780 //
11781 // EXPECT_* verifies that a certain condition is satisfied. If not,
11782 // it behaves like ADD_FAILURE. In particular:
11783 //
11784 // EXPECT_TRUE verifies that a Boolean condition is true.
11785 // EXPECT_FALSE verifies that a Boolean condition is false.
11786 //
11787 // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
11788 // that they will also abort the current function on failure. People
11789 // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
11790 // writing data-driven tests often find themselves using ADD_FAILURE
11791 // and EXPECT_* more.
11792
11793 // Generates a nonfatal failure with a generic message.
11794 #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
11795
11796 // Generates a nonfatal failure at the given source file location with
11797 // a generic message.
11798 #define ADD_FAILURE_AT(file, line) \
11799 GTEST_MESSAGE_AT_(file, line, "Failed", \
11800 ::testing::TestPartResult::kNonFatalFailure)
11801
11802 // Generates a fatal failure with a generic message.
11803 #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
11804
11805 // Like GTEST_FAIL(), but at the given source file location.
11806 #define GTEST_FAIL_AT(file, line) \
11807 GTEST_MESSAGE_AT_(file, line, "Failed", \
11808 ::testing::TestPartResult::kFatalFailure)
11809
11810 // Define this macro to 1 to omit the definition of FAIL(), which is a
11811 // generic name and clashes with some other libraries.
11812 #if !GTEST_DONT_DEFINE_FAIL
11813 # define FAIL() GTEST_FAIL()
11814 #endif
11815
11816 // Generates a success with a generic message.
11817 #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
11818
11819 // Define this macro to 1 to omit the definition of SUCCEED(), which
11820 // is a generic name and clashes with some other libraries.
11821 #if !GTEST_DONT_DEFINE_SUCCEED
11822 # define SUCCEED() GTEST_SUCCEED()
11823 #endif
11824
11825 // Macros for testing exceptions.
11826 //
11827 // * {ASSERT|EXPECT}_THROW(statement, expected_exception):
11828 // Tests that the statement throws the expected exception.
11829 // * {ASSERT|EXPECT}_NO_THROW(statement):
11830 // Tests that the statement doesn't throw any exception.
11831 // * {ASSERT|EXPECT}_ANY_THROW(statement):
11832 // Tests that the statement throws an exception.
11833
11834 #define EXPECT_THROW(statement, expected_exception) \
11835 GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
11836 #define EXPECT_NO_THROW(statement) \
11837 GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
11838 #define EXPECT_ANY_THROW(statement) \
11839 GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
11840 #define ASSERT_THROW(statement, expected_exception) \
11841 GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
11842 #define ASSERT_NO_THROW(statement) \
11843 GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
11844 #define ASSERT_ANY_THROW(statement) \
11845 GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
11846
11847 // Boolean assertions. Condition can be either a Boolean expression or an
11848 // AssertionResult. For more information on how to use AssertionResult with
11849 // these macros see comments on that class.
11850 #define GTEST_EXPECT_TRUE(condition) \
11851 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
11852 GTEST_NONFATAL_FAILURE_)
11853 #define GTEST_EXPECT_FALSE(condition) \
11854 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
11855 GTEST_NONFATAL_FAILURE_)
11856 #define GTEST_ASSERT_TRUE(condition) \
11857 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
11858 GTEST_FATAL_FAILURE_)
11859 #define GTEST_ASSERT_FALSE(condition) \
11860 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
11861 GTEST_FATAL_FAILURE_)
11862
11863 // Define these macros to 1 to omit the definition of the corresponding
11864 // EXPECT or ASSERT, which clashes with some users' own code.
11865
11866 #if !GTEST_DONT_DEFINE_EXPECT_TRUE
11867 #define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
11868 #endif
11869
11870 #if !GTEST_DONT_DEFINE_EXPECT_FALSE
11871 #define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
11872 #endif
11873
11874 #if !GTEST_DONT_DEFINE_ASSERT_TRUE
11875 #define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
11876 #endif
11877
11878 #if !GTEST_DONT_DEFINE_ASSERT_FALSE
11879 #define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
11880 #endif
11881
11882 // Macros for testing equalities and inequalities.
11883 //
11884 // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
11885 // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
11886 // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
11887 // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
11888 // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
11889 // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
11890 //
11891 // When they are not, Google Test prints both the tested expressions and
11892 // their actual values. The values must be compatible built-in types,
11893 // or you will get a compiler error. By "compatible" we mean that the
11894 // values can be compared by the respective operator.
11895 //
11896 // Note:
11897 //
11898 // 1. It is possible to make a user-defined type work with
11899 // {ASSERT|EXPECT}_??(), but that requires overloading the
11900 // comparison operators and is thus discouraged by the Google C++
11901 // Usage Guide. Therefore, you are advised to use the
11902 // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
11903 // equal.
11904 //
11905 // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
11906 // pointers (in particular, C strings). Therefore, if you use it
11907 // with two C strings, you are testing how their locations in memory
11908 // are related, not how their content is related. To compare two C
11909 // strings by content, use {ASSERT|EXPECT}_STR*().
11910 //
11911 // 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
11912 // {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
11913 // what the actual value is when it fails, and similarly for the
11914 // other comparisons.
11915 //
11916 // 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
11917 // evaluate their arguments, which is undefined.
11918 //
11919 // 5. These macros evaluate their arguments exactly once.
11920 //
11921 // Examples:
11922 //
11923 // EXPECT_NE(Foo(), 5);
11924 // EXPECT_EQ(a_pointer, NULL);
11925 // ASSERT_LT(i, array_size);
11926 // ASSERT_GT(records.size(), 0) << "There is no record left.";
11927
11928 #define EXPECT_EQ(val1, val2) \
11929 EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
11930 #define EXPECT_NE(val1, val2) \
11931 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
11932 #define EXPECT_LE(val1, val2) \
11933 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
11934 #define EXPECT_LT(val1, val2) \
11935 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
11936 #define EXPECT_GE(val1, val2) \
11937 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
11938 #define EXPECT_GT(val1, val2) \
11939 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
11940
11941 #define GTEST_ASSERT_EQ(val1, val2) \
11942 ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
11943 #define GTEST_ASSERT_NE(val1, val2) \
11944 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
11945 #define GTEST_ASSERT_LE(val1, val2) \
11946 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
11947 #define GTEST_ASSERT_LT(val1, val2) \
11948 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
11949 #define GTEST_ASSERT_GE(val1, val2) \
11950 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
11951 #define GTEST_ASSERT_GT(val1, val2) \
11952 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
11953
11954 // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
11955 // ASSERT_XY(), which clashes with some users' own code.
11956
11957 #if !GTEST_DONT_DEFINE_ASSERT_EQ
11958 # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
11959 #endif
11960
11961 #if !GTEST_DONT_DEFINE_ASSERT_NE
11962 # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
11963 #endif
11964
11965 #if !GTEST_DONT_DEFINE_ASSERT_LE
11966 # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
11967 #endif
11968
11969 #if !GTEST_DONT_DEFINE_ASSERT_LT
11970 # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
11971 #endif
11972
11973 #if !GTEST_DONT_DEFINE_ASSERT_GE
11974 # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
11975 #endif
11976
11977 #if !GTEST_DONT_DEFINE_ASSERT_GT
11978 # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
11979 #endif
11980
11981 // C-string Comparisons. All tests treat NULL and any non-NULL string
11982 // as different. Two NULLs are equal.
11983 //
11984 // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
11985 // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
11986 // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
11987 // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
11988 //
11989 // For wide or narrow string objects, you can use the
11990 // {ASSERT|EXPECT}_??() macros.
11991 //
11992 // Don't depend on the order in which the arguments are evaluated,
11993 // which is undefined.
11994 //
11995 // These macros evaluate their arguments exactly once.
11996
11997 #define EXPECT_STREQ(s1, s2) \
11998 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
11999 #define EXPECT_STRNE(s1, s2) \
12000 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
12001 #define EXPECT_STRCASEEQ(s1, s2) \
12002 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
12003 #define EXPECT_STRCASENE(s1, s2)\
12004 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
12005
12006 #define ASSERT_STREQ(s1, s2) \
12007 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
12008 #define ASSERT_STRNE(s1, s2) \
12009 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
12010 #define ASSERT_STRCASEEQ(s1, s2) \
12011 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
12012 #define ASSERT_STRCASENE(s1, s2)\
12013 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
12014
12015 // Macros for comparing floating-point numbers.
12016 //
12017 // * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
12018 // Tests that two float values are almost equal.
12019 // * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
12020 // Tests that two double values are almost equal.
12021 // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
12022 // Tests that v1 and v2 are within the given distance to each other.
12023 //
12024 // Google Test uses ULP-based comparison to automatically pick a default
12025 // error bound that is appropriate for the operands. See the
12026 // FloatingPoint template class in gtest-internal.h if you are
12027 // interested in the implementation details.
12028
12029 #define EXPECT_FLOAT_EQ(val1, val2)\
12030 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
12031 val1, val2)
12032
12033 #define EXPECT_DOUBLE_EQ(val1, val2)\
12034 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
12035 val1, val2)
12036
12037 #define ASSERT_FLOAT_EQ(val1, val2)\
12038 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
12039 val1, val2)
12040
12041 #define ASSERT_DOUBLE_EQ(val1, val2)\
12042 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
12043 val1, val2)
12044
12045 #define EXPECT_NEAR(val1, val2, abs_error)\
12046 EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
12047 val1, val2, abs_error)
12048
12049 #define ASSERT_NEAR(val1, val2, abs_error)\
12050 ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
12051 val1, val2, abs_error)
12052
12053 // These predicate format functions work on floating-point values, and
12054 // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
12055 //
12056 // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
12057
12058 // Asserts that val1 is less than, or almost equal to, val2. Fails
12059 // otherwise. In particular, it fails if either val1 or val2 is NaN.
12060 GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
12061 float val1, float val2);
12062 GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
12063 double val1, double val2);
12064
12065
12066 #if GTEST_OS_WINDOWS
12067
12068 // Macros that test for HRESULT failure and success, these are only useful
12069 // on Windows, and rely on Windows SDK macros and APIs to compile.
12070 //
12071 // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
12072 //
12073 // When expr unexpectedly fails or succeeds, Google Test prints the
12074 // expected result and the actual result with both a human-readable
12075 // string representation of the error, if available, as well as the
12076 // hex result code.
12077 # define EXPECT_HRESULT_SUCCEEDED(expr) \
12078 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
12079
12080 # define ASSERT_HRESULT_SUCCEEDED(expr) \
12081 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
12082
12083 # define EXPECT_HRESULT_FAILED(expr) \
12084 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
12085
12086 # define ASSERT_HRESULT_FAILED(expr) \
12087 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
12088
12089 #endif // GTEST_OS_WINDOWS
12090
12091 // Macros that execute statement and check that it doesn't generate new fatal
12092 // failures in the current thread.
12093 //
12094 // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
12095 //
12096 // Examples:
12097 //
12098 // EXPECT_NO_FATAL_FAILURE(Process());
12099 // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
12100 //
12101 #define ASSERT_NO_FATAL_FAILURE(statement) \
12102 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
12103 #define EXPECT_NO_FATAL_FAILURE(statement) \
12104 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
12105
12106 // Causes a trace (including the given source file path and line number,
12107 // and the given message) to be included in every test failure message generated
12108 // by code in the scope of the lifetime of an instance of this class. The effect
12109 // is undone with the destruction of the instance.
12110 //
12111 // The message argument can be anything streamable to std::ostream.
12112 //
12113 // Example:
12114 // testing::ScopedTrace trace("file.cc", 123, "message");
12115 //
12116 class GTEST_API_ ScopedTrace {
12117 public:
12118 // The c'tor pushes the given source file location and message onto
12119 // a trace stack maintained by Google Test.
12120
12121 // Template version. Uses Message() to convert the values into strings.
12122 // Slow, but flexible.
12123 template <typename T>
12124 ScopedTrace(const char* file, int line, const T& message) {
12125 PushTrace(file, line, (Message() << message).GetString());
12126 }
12127
12128 // Optimize for some known types.
12129 ScopedTrace(const char* file, int line, const char* message) {
12130 PushTrace(file, line, message ? message : "(null)");
12131 }
12132
12133 ScopedTrace(const char* file, int line, const std::string& message) {
12134 PushTrace(file, line, message);
12135 }
12136
12137 // The d'tor pops the info pushed by the c'tor.
12138 //
12139 // Note that the d'tor is not virtual in order to be efficient.
12140 // Don't inherit from ScopedTrace!
12141 ~ScopedTrace();
12142
12143 private:
12144 void PushTrace(const char* file, int line, std::string message);
12145
12146 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
12147 } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
12148 // c'tor and d'tor. Therefore it doesn't
12149 // need to be used otherwise.
12150
12151 // Causes a trace (including the source file path, the current line
12152 // number, and the given message) to be included in every test failure
12153 // message generated by code in the current scope. The effect is
12154 // undone when the control leaves the current scope.
12155 //
12156 // The message argument can be anything streamable to std::ostream.
12157 //
12158 // In the implementation, we include the current line number as part
12159 // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
12160 // to appear in the same block - as long as they are on different
12161 // lines.
12162 //
12163 // Assuming that each thread maintains its own stack of traces.
12164 // Therefore, a SCOPED_TRACE() would (correctly) only affect the
12165 // assertions in its own thread.
12166 #define SCOPED_TRACE(message) \
12167 ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
12168 __FILE__, __LINE__, (message))
12169
12170 // Compile-time assertion for type equality.
12171 // StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
12172 // are the same type. The value it returns is not interesting.
12173 //
12174 // Instead of making StaticAssertTypeEq a class template, we make it a
12175 // function template that invokes a helper class template. This
12176 // prevents a user from misusing StaticAssertTypeEq<T1, T2> by
12177 // defining objects of that type.
12178 //
12179 // CAVEAT:
12180 //
12181 // When used inside a method of a class template,
12182 // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
12183 // instantiated. For example, given:
12184 //
12185 // template <typename T> class Foo {
12186 // public:
12187 // void Bar() { testing::StaticAssertTypeEq<int, T>(); }
12188 // };
12189 //
12190 // the code:
12191 //
12192 // void Test1() { Foo<bool> foo; }
12193 //
12194 // will NOT generate a compiler error, as Foo<bool>::Bar() is never
12195 // actually instantiated. Instead, you need:
12196 //
12197 // void Test2() { Foo<bool> foo; foo.Bar(); }
12198 //
12199 // to cause a compiler error.
12200 template <typename T1, typename T2>
12201 constexpr bool StaticAssertTypeEq() noexcept {
12202 static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type");
12203 return true;
12204 }
12205
12206 // Defines a test.
12207 //
12208 // The first parameter is the name of the test suite, and the second
12209 // parameter is the name of the test within the test suite.
12210 //
12211 // The convention is to end the test suite name with "Test". For
12212 // example, a test suite for the Foo class can be named FooTest.
12213 //
12214 // Test code should appear between braces after an invocation of
12215 // this macro. Example:
12216 //
12217 // TEST(FooTest, InitializesCorrectly) {
12218 // Foo foo;
12219 // EXPECT_TRUE(foo.StatusIsOK());
12220 // }
12221
12222 // Note that we call GetTestTypeId() instead of GetTypeId<
12223 // ::testing::Test>() here to get the type ID of testing::Test. This
12224 // is to work around a suspected linker bug when using Google Test as
12225 // a framework on Mac OS X. The bug causes GetTypeId<
12226 // ::testing::Test>() to return different values depending on whether
12227 // the call is from the Google Test framework itself or from user test
12228 // code. GetTestTypeId() is guaranteed to always return the same
12229 // value, as it always calls GetTypeId<>() from the Google Test
12230 // framework.
12231 #define GTEST_TEST(test_suite_name, test_name) \
12232 GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \
12233 ::testing::internal::GetTestTypeId())
12234
12235 // Define this macro to 1 to omit the definition of TEST(), which
12236 // is a generic name and clashes with some other libraries.
12237 #if !GTEST_DONT_DEFINE_TEST
12238 #define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
12239 #endif
12240
12241 // Defines a test that uses a test fixture.
12242 //
12243 // The first parameter is the name of the test fixture class, which
12244 // also doubles as the test suite name. The second parameter is the
12245 // name of the test within the test suite.
12246 //
12247 // A test fixture class must be declared earlier. The user should put
12248 // the test code between braces after using this macro. Example:
12249 //
12250 // class FooTest : public testing::Test {
12251 // protected:
12252 // void SetUp() override { b_.AddElement(3); }
12253 //
12254 // Foo a_;
12255 // Foo b_;
12256 // };
12257 //
12258 // TEST_F(FooTest, InitializesCorrectly) {
12259 // EXPECT_TRUE(a_.StatusIsOK());
12260 // }
12261 //
12262 // TEST_F(FooTest, ReturnsElementCountCorrectly) {
12263 // EXPECT_EQ(a_.size(), 0);
12264 // EXPECT_EQ(b_.size(), 1);
12265 // }
12266 //
12267 // GOOGLETEST_CM0011 DO NOT DELETE
12268 #if !GTEST_DONT_DEFINE_TEST
12269 #define TEST_F(test_fixture, test_name)\
12270 GTEST_TEST_(test_fixture, test_name, test_fixture, \
12271 ::testing::internal::GetTypeId<test_fixture>())
12272 #endif // !GTEST_DONT_DEFINE_TEST
12273
12274 // Returns a path to temporary directory.
12275 // Tries to determine an appropriate directory for the platform.
12276 GTEST_API_ std::string TempDir();
12277
12278 #ifdef _MSC_VER
12279 # pragma warning(pop)
12280 #endif
12281
12282 // Dynamically registers a test with the framework.
12283 //
12284 // This is an advanced API only to be used when the `TEST` macros are
12285 // insufficient. The macros should be preferred when possible, as they avoid
12286 // most of the complexity of calling this function.
12287 //
12288 // The `factory` argument is a factory callable (move-constructible) object or
12289 // function pointer that creates a new instance of the Test object. It
12290 // handles ownership to the caller. The signature of the callable is
12291 // `Fixture*()`, where `Fixture` is the test fixture class for the test. All
12292 // tests registered with the same `test_suite_name` must return the same
12293 // fixture type. This is checked at runtime.
12294 //
12295 // The framework will infer the fixture class from the factory and will call
12296 // the `SetUpTestSuite` and `TearDownTestSuite` for it.
12297 //
12298 // Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
12299 // undefined.
12300 //
12301 // Use case example:
12302 //
12303 // class MyFixture : public ::testing::Test {
12304 // public:
12305 // // All of these optional, just like in regular macro usage.
12306 // static void SetUpTestSuite() { ... }
12307 // static void TearDownTestSuite() { ... }
12308 // void SetUp() override { ... }
12309 // void TearDown() override { ... }
12310 // };
12311 //
12312 // class MyTest : public MyFixture {
12313 // public:
12314 // explicit MyTest(int data) : data_(data) {}
12315 // void TestBody() override { ... }
12316 //
12317 // private:
12318 // int data_;
12319 // };
12320 //
12321 // void RegisterMyTests(const std::vector<int>& values) {
12322 // for (int v : values) {
12323 // ::testing::RegisterTest(
12324 // "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
12325 // std::to_string(v).c_str(),
12326 // __FILE__, __LINE__,
12327 // // Important to use the fixture type as the return type here.
12328 // [=]() -> MyFixture* { return new MyTest(v); });
12329 // }
12330 // }
12331 // ...
12332 // int main(int argc, char** argv) {
12333 // std::vector<int> values_to_test = LoadValuesFromConfig();
12334 // RegisterMyTests(values_to_test);
12335 // ...
12336 // return RUN_ALL_TESTS();
12337 // }
12338 //
12339 template <int&... ExplicitParameterBarrier, typename Factory>
12340 TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
12341 const char* type_param, const char* value_param,
12342 const char* file, int line, Factory factory) {
12343 using TestT = typename std::remove_pointer<decltype(factory())>::type;
12344
12345 class FactoryImpl : public internal::TestFactoryBase {
12346 public:
12347 explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}
12348 Test* CreateTest() override { return factory_(); }
12349
12350 private:
12351 Factory factory_;
12352 };
12353
12354 return internal::MakeAndRegisterTestInfo(
12355 test_suite_name, test_name, type_param, value_param,
12356 internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),
12357 internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),
12358 internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),
12359 new FactoryImpl{std::move(factory)});
12360 }
12361
12362 } // namespace testing
12363
12364 // Use this function in main() to run all tests. It returns 0 if all
12365 // tests are successful, or 1 otherwise.
12366 //
12367 // RUN_ALL_TESTS() should be invoked after the command line has been
12368 // parsed by InitGoogleTest().
12369 //
12370 // This function was formerly a macro; thus, it is in the global
12371 // namespace and has an all-caps name.
12372 int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
12373
12374 inline int RUN_ALL_TESTS() {
12375 return ::testing::UnitTest::GetInstance()->Run();
12376 }
12377
12378 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
12379
12380 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_
12381