]> git.proxmox.com Git - ceph.git/blob - ceph/src/fmt/test/gtest/gtest/gtest.h
import quincy beta 17.1.0
[ceph.git] / ceph / src / fmt / test / gtest / gtest / gtest.h
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_KFREEBSD - GNU/kFreeBSD
220 // GTEST_OS_HAIKU - Haiku
221 // GTEST_OS_HPUX - HP-UX
222 // GTEST_OS_LINUX - Linux
223 // GTEST_OS_LINUX_ANDROID - Google Android
224 // GTEST_OS_MAC - Mac OS X
225 // GTEST_OS_IOS - iOS
226 // GTEST_OS_NACL - Google Native Client (NaCl)
227 // GTEST_OS_NETBSD - NetBSD
228 // GTEST_OS_OPENBSD - OpenBSD
229 // GTEST_OS_OS2 - OS/2
230 // GTEST_OS_QNX - QNX
231 // GTEST_OS_SOLARIS - Sun Solaris
232 // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile)
233 // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop
234 // GTEST_OS_WINDOWS_MINGW - MinGW
235 // GTEST_OS_WINDOWS_MOBILE - Windows Mobile
236 // GTEST_OS_WINDOWS_PHONE - Windows Phone
237 // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT
238 // GTEST_OS_ZOS - z/OS
239 //
240 // Among the platforms, Cygwin, Linux, Mac OS X, and Windows have the
241 // most stable support. Since core members of the Google Test project
242 // don't have access to other platforms, support for them may be less
243 // stable. If you notice any problems on your platform, please notify
244 // googletestframework@googlegroups.com (patches for fixing them are
245 // even more welcome!).
246 //
247 // It is possible that none of the GTEST_OS_* macros are defined.
248
249 // Feature-indicating macros
250 // -------------------------
251 //
252 // Macros indicating which Google Test features are available (a macro
253 // is defined to 1 if the corresponding feature is supported;
254 // otherwise UNDEFINED -- it's never defined to 0.). Google Test
255 // defines these macros automatically. Code outside Google Test MUST
256 // NOT define them.
257 //
258 // These macros are public so that portable tests can be written.
259 // Such tests typically surround code using a feature with an #if
260 // which controls that code. For example:
261 //
262 // #if GTEST_HAS_DEATH_TEST
263 // EXPECT_DEATH(DoSomethingDeadly());
264 // #endif
265 //
266 // GTEST_HAS_DEATH_TEST - death tests
267 // GTEST_HAS_TYPED_TEST - typed tests
268 // GTEST_HAS_TYPED_TEST_P - type-parameterized tests
269 // GTEST_IS_THREADSAFE - Google Test is thread-safe.
270 // GOOGLETEST_CM0007 DO NOT DELETE
271 // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with
272 // GTEST_HAS_POSIX_RE (see above) which users can
273 // define themselves.
274 // GTEST_USES_SIMPLE_RE - our own simple regex is used;
275 // the above RE\b(s) are mutually exclusive.
276
277 // Misc public macros
278 // ------------------
279 //
280 // GTEST_FLAG(flag_name) - references the variable corresponding to
281 // the given Google Test flag.
282
283 // Internal utilities
284 // ------------------
285 //
286 // The following macros and utilities are for Google Test's INTERNAL
287 // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY.
288 //
289 // Macros for basic C++ coding:
290 // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
291 // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a
292 // variable don't have to be used.
293 // GTEST_DISALLOW_ASSIGN_ - disables copy operator=.
294 // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
295 // GTEST_DISALLOW_MOVE_ASSIGN_ - disables move operator=.
296 // GTEST_DISALLOW_MOVE_AND_ASSIGN_ - disables move ctor and operator=.
297 // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used.
298 // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
299 // suppressed (constant conditional).
300 // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
301 // is suppressed.
302 // GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
303 // UniversalPrinter<absl::any> specializations.
304 // GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
305 // or
306 // UniversalPrinter<absl::optional>
307 // specializations.
308 // GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
309 // Matcher<absl::string_view>
310 // specializations.
311 // GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
312 // UniversalPrinter<absl::variant>
313 // specializations.
314 //
315 // Synchronization:
316 // Mutex, MutexLock, ThreadLocal, GetThreadCount()
317 // - synchronization primitives.
318 //
319 // Regular expressions:
320 // RE - a simple regular expression class using the POSIX
321 // Extended Regular Expression syntax on UNIX-like platforms
322 // GOOGLETEST_CM0008 DO NOT DELETE
323 // or a reduced regular exception syntax on other
324 // platforms, including Windows.
325 // Logging:
326 // GTEST_LOG_() - logs messages at the specified severity level.
327 // LogToStderr() - directs all log messages to stderr.
328 // FlushInfoLog() - flushes informational log messages.
329 //
330 // Stdout and stderr capturing:
331 // CaptureStdout() - starts capturing stdout.
332 // GetCapturedStdout() - stops capturing stdout and returns the captured
333 // string.
334 // CaptureStderr() - starts capturing stderr.
335 // GetCapturedStderr() - stops capturing stderr and returns the captured
336 // string.
337 //
338 // Integer types:
339 // TypeWithSize - maps an integer to a int type.
340 // TimeInMillis - integers of known sizes.
341 // BiggestInt - the biggest signed integer type.
342 //
343 // Command-line utilities:
344 // GTEST_DECLARE_*() - declares a flag.
345 // GTEST_DEFINE_*() - defines a flag.
346 // GetInjectableArgvs() - returns the command line as a vector of strings.
347 //
348 // Environment variable utilities:
349 // GetEnv() - gets the value of an environment variable.
350 // BoolFromGTestEnv() - parses a bool environment variable.
351 // Int32FromGTestEnv() - parses an int32_t environment variable.
352 // StringFromGTestEnv() - parses a string environment variable.
353 //
354 // Deprecation warnings:
355 // GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as
356 // deprecated; calling a marked function
357 // should generate a compiler warning
358
359 #include <ctype.h> // for isspace, etc
360 #include <stddef.h> // for ptrdiff_t
361 #include <stdio.h>
362 #include <stdlib.h>
363 #include <string.h>
364
365 #include <cerrno>
366 #include <cstdint>
367 #include <limits>
368 #include <type_traits>
369
370 #ifndef _WIN32_WCE
371 # include <sys/types.h>
372 # include <sys/stat.h>
373 #endif // !_WIN32_WCE
374
375 #if defined __APPLE__
376 # include <AvailabilityMacros.h>
377 # include <TargetConditionals.h>
378 #endif
379
380 #include <iostream> // NOLINT
381 #include <locale>
382 #include <memory>
383 #include <string> // NOLINT
384 #include <tuple>
385 #include <vector> // NOLINT
386
387 // Copyright 2015, Google Inc.
388 // All rights reserved.
389 //
390 // Redistribution and use in source and binary forms, with or without
391 // modification, are permitted provided that the following conditions are
392 // met:
393 //
394 // * Redistributions of source code must retain the above copyright
395 // notice, this list of conditions and the following disclaimer.
396 // * Redistributions in binary form must reproduce the above
397 // copyright notice, this list of conditions and the following disclaimer
398 // in the documentation and/or other materials provided with the
399 // distribution.
400 // * Neither the name of Google Inc. nor the names of its
401 // contributors may be used to endorse or promote products derived from
402 // this software without specific prior written permission.
403 //
404 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
405 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
406 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
407 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
408 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
409 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
410 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
411 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
412 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
413 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
414 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
415 //
416 // Injection point for custom user configurations. See README for details
417 //
418 // ** Custom implementation starts here **
419
420 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
421 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
422
423 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
424 // Copyright 2015, Google Inc.
425 // All rights reserved.
426 //
427 // Redistribution and use in source and binary forms, with or without
428 // modification, are permitted provided that the following conditions are
429 // met:
430 //
431 // * Redistributions of source code must retain the above copyright
432 // notice, this list of conditions and the following disclaimer.
433 // * Redistributions in binary form must reproduce the above
434 // copyright notice, this list of conditions and the following disclaimer
435 // in the documentation and/or other materials provided with the
436 // distribution.
437 // * Neither the name of Google Inc. nor the names of its
438 // contributors may be used to endorse or promote products derived from
439 // this software without specific prior written permission.
440 //
441 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
442 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
443 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
444 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
445 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
446 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
447 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
448 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
449 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
450 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
451 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
452 //
453 // The Google C++ Testing and Mocking Framework (Google Test)
454 //
455 // This header file defines the GTEST_OS_* macro.
456 // It is separate from gtest-port.h so that custom/gtest-port.h can include it.
457
458 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
459 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
460
461 // Determines the platform on which Google Test is compiled.
462 #ifdef __CYGWIN__
463 # define GTEST_OS_CYGWIN 1
464 # elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
465 # define GTEST_OS_WINDOWS_MINGW 1
466 # define GTEST_OS_WINDOWS 1
467 #elif defined _WIN32
468 # define GTEST_OS_WINDOWS 1
469 # ifdef _WIN32_WCE
470 # define GTEST_OS_WINDOWS_MOBILE 1
471 # elif defined(WINAPI_FAMILY)
472 # include <winapifamily.h>
473 # if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
474 # define GTEST_OS_WINDOWS_DESKTOP 1
475 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
476 # define GTEST_OS_WINDOWS_PHONE 1
477 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
478 # define GTEST_OS_WINDOWS_RT 1
479 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
480 # define GTEST_OS_WINDOWS_PHONE 1
481 # define GTEST_OS_WINDOWS_TV_TITLE 1
482 # else
483 // WINAPI_FAMILY defined but no known partition matched.
484 // Default to desktop.
485 # define GTEST_OS_WINDOWS_DESKTOP 1
486 # endif
487 # else
488 # define GTEST_OS_WINDOWS_DESKTOP 1
489 # endif // _WIN32_WCE
490 #elif defined __OS2__
491 # define GTEST_OS_OS2 1
492 #elif defined __APPLE__
493 # define GTEST_OS_MAC 1
494 # include <TargetConditionals.h>
495 # if TARGET_OS_IPHONE
496 # define GTEST_OS_IOS 1
497 # endif
498 #elif defined __DragonFly__
499 # define GTEST_OS_DRAGONFLY 1
500 #elif defined __FreeBSD__
501 # define GTEST_OS_FREEBSD 1
502 #elif defined __Fuchsia__
503 # define GTEST_OS_FUCHSIA 1
504 #elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
505 # define GTEST_OS_GNU_KFREEBSD 1
506 #elif defined __linux__
507 # define GTEST_OS_LINUX 1
508 # if defined __ANDROID__
509 # define GTEST_OS_LINUX_ANDROID 1
510 # endif
511 #elif defined __MVS__
512 # define GTEST_OS_ZOS 1
513 #elif defined(__sun) && defined(__SVR4)
514 # define GTEST_OS_SOLARIS 1
515 #elif defined(_AIX)
516 # define GTEST_OS_AIX 1
517 #elif defined(__hpux)
518 # define GTEST_OS_HPUX 1
519 #elif defined __native_client__
520 # define GTEST_OS_NACL 1
521 #elif defined __NetBSD__
522 # define GTEST_OS_NETBSD 1
523 #elif defined __OpenBSD__
524 # define GTEST_OS_OPENBSD 1
525 #elif defined __QNX__
526 # define GTEST_OS_QNX 1
527 #elif defined(__HAIKU__)
528 #define GTEST_OS_HAIKU 1
529 #elif defined ESP8266
530 #define GTEST_OS_ESP8266 1
531 #elif defined ESP32
532 #define GTEST_OS_ESP32 1
533 #elif defined(__XTENSA__)
534 #define GTEST_OS_XTENSA 1
535 #endif // __CYGWIN__
536
537 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
538
539 #if !defined(GTEST_DEV_EMAIL_)
540 # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
541 # define GTEST_FLAG_PREFIX_ "gtest_"
542 # define GTEST_FLAG_PREFIX_DASH_ "gtest-"
543 # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
544 # define GTEST_NAME_ "Google Test"
545 # define GTEST_PROJECT_URL_ "https://github.com/google/googletest/"
546 #endif // !defined(GTEST_DEV_EMAIL_)
547
548 #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
549 # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
550 #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
551
552 // Determines the version of gcc that is used to compile this.
553 #ifdef __GNUC__
554 // 40302 means version 4.3.2.
555 # define GTEST_GCC_VER_ \
556 (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
557 #endif // __GNUC__
558
559 // Macros for disabling Microsoft Visual C++ warnings.
560 //
561 // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
562 // /* code that triggers warnings C4800 and C4385 */
563 // GTEST_DISABLE_MSC_WARNINGS_POP_()
564 #if defined(_MSC_VER)
565 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
566 __pragma(warning(push)) \
567 __pragma(warning(disable: warnings))
568 # define GTEST_DISABLE_MSC_WARNINGS_POP_() \
569 __pragma(warning(pop))
570 #else
571 // Not all compilers are MSVC
572 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
573 # define GTEST_DISABLE_MSC_WARNINGS_POP_()
574 #endif
575
576 // Clang on Windows does not understand MSVC's pragma warning.
577 // We need clang-specific way to disable function deprecation warning.
578 #ifdef __clang__
579 # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
580 _Pragma("clang diagnostic push") \
581 _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \
582 _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"")
583 #define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
584 _Pragma("clang diagnostic pop")
585 #else
586 # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
587 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
588 # define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
589 GTEST_DISABLE_MSC_WARNINGS_POP_()
590 #endif
591
592 // Brings in definitions for functions used in the testing::internal::posix
593 // namespace (read, write, close, chdir, isatty, stat). We do not currently
594 // use them on Windows Mobile.
595 #if GTEST_OS_WINDOWS
596 # if !GTEST_OS_WINDOWS_MOBILE
597 # include <direct.h>
598 # include <io.h>
599 # endif
600 // In order to avoid having to include <windows.h>, use forward declaration
601 #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
602 // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two
603 // separate (equivalent) structs, instead of using typedef
604 typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
605 #else
606 // Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.
607 // This assumption is verified by
608 // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
609 typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
610 #endif
611 #elif GTEST_OS_XTENSA
612 #include <unistd.h>
613 // Xtensa toolchains define strcasecmp in the string.h header instead of
614 // strings.h. string.h is already included.
615 #else
616 // This assumes that non-Windows OSes provide unistd.h. For OSes where this
617 // is not the case, we need to include headers that provide the functions
618 // mentioned above.
619 # include <unistd.h>
620 # include <strings.h>
621 #endif // GTEST_OS_WINDOWS
622
623 #if GTEST_OS_LINUX_ANDROID
624 // Used to define __ANDROID_API__ matching the target NDK API level.
625 # include <android/api-level.h> // NOLINT
626 #endif
627
628 // Defines this to true if and only if Google Test can use POSIX regular
629 // expressions.
630 #ifndef GTEST_HAS_POSIX_RE
631 # if GTEST_OS_LINUX_ANDROID
632 // On Android, <regex.h> is only available starting with Gingerbread.
633 # define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
634 # else
635 #define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA)
636 # endif
637 #endif
638
639 #if GTEST_USES_PCRE
640 // The appropriate headers have already been included.
641
642 #elif GTEST_HAS_POSIX_RE
643
644 // On some platforms, <regex.h> needs someone to define size_t, and
645 // won't compile otherwise. We can #include it here as we already
646 // included <stdlib.h>, which is guaranteed to define size_t through
647 // <stddef.h>.
648 # include <regex.h> // NOLINT
649
650 # define GTEST_USES_POSIX_RE 1
651
652 #elif GTEST_OS_WINDOWS
653
654 // <regex.h> is not available on Windows. Use our own simple regex
655 // implementation instead.
656 # define GTEST_USES_SIMPLE_RE 1
657
658 #else
659
660 // <regex.h> may not be available on this platform. Use our own
661 // simple regex implementation instead.
662 # define GTEST_USES_SIMPLE_RE 1
663
664 #endif // GTEST_USES_PCRE
665
666 #ifndef GTEST_HAS_EXCEPTIONS
667 // The user didn't tell us whether exceptions are enabled, so we need
668 // to figure it out.
669 # if defined(_MSC_VER) && defined(_CPPUNWIND)
670 // MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled.
671 # define GTEST_HAS_EXCEPTIONS 1
672 # elif defined(__BORLANDC__)
673 // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS
674 // macro to enable exceptions, so we'll do the same.
675 // Assumes that exceptions are enabled by default.
676 # ifndef _HAS_EXCEPTIONS
677 # define _HAS_EXCEPTIONS 1
678 # endif // _HAS_EXCEPTIONS
679 # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
680 # elif defined(__clang__)
681 // clang defines __EXCEPTIONS if and only if exceptions are enabled before clang
682 // 220714, but if and only if cleanups are enabled after that. In Obj-C++ files,
683 // there can be cleanups for ObjC exceptions which also need cleanups, even if
684 // C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which
685 // checks for C++ exceptions starting at clang r206352, but which checked for
686 // cleanups prior to that. To reliably check for C++ exception availability with
687 // clang, check for
688 // __EXCEPTIONS && __has_feature(cxx_exceptions).
689 # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
690 # elif defined(__GNUC__) && __EXCEPTIONS
691 // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
692 # define GTEST_HAS_EXCEPTIONS 1
693 # elif defined(__SUNPRO_CC)
694 // Sun Pro CC supports exceptions. However, there is no compile-time way of
695 // detecting whether they are enabled or not. Therefore, we assume that
696 // they are enabled unless the user tells us otherwise.
697 # define GTEST_HAS_EXCEPTIONS 1
698 # elif defined(__IBMCPP__) && __EXCEPTIONS
699 // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
700 # define GTEST_HAS_EXCEPTIONS 1
701 # elif defined(__HP_aCC)
702 // Exception handling is in effect by default in HP aCC compiler. It has to
703 // be turned of by +noeh compiler option if desired.
704 # define GTEST_HAS_EXCEPTIONS 1
705 # else
706 // For other compilers, we assume exceptions are disabled to be
707 // conservative.
708 # define GTEST_HAS_EXCEPTIONS 0
709 # endif // defined(_MSC_VER) || defined(__BORLANDC__)
710 #endif // GTEST_HAS_EXCEPTIONS
711
712 #ifndef GTEST_HAS_STD_WSTRING
713 // The user didn't tell us whether ::std::wstring is available, so we need
714 // to figure it out.
715 // Cygwin 1.7 and below doesn't support ::std::wstring.
716 // Solaris' libc++ doesn't support it either. Android has
717 // no support for it at least as recent as Froyo (2.2).
718 #define GTEST_HAS_STD_WSTRING \
719 (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
720 GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || GTEST_OS_XTENSA))
721
722 #endif // GTEST_HAS_STD_WSTRING
723
724 // Determines whether RTTI is available.
725 #ifndef GTEST_HAS_RTTI
726 // The user didn't tell us whether RTTI is enabled, so we need to
727 // figure it out.
728
729 # ifdef _MSC_VER
730
731 #ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled.
732 # define GTEST_HAS_RTTI 1
733 # else
734 # define GTEST_HAS_RTTI 0
735 # endif
736
737 // Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is
738 // enabled.
739 # elif defined(__GNUC__)
740
741 # ifdef __GXX_RTTI
742 // When building against STLport with the Android NDK and with
743 // -frtti -fno-exceptions, the build fails at link time with undefined
744 // references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
745 // so disable RTTI when detected.
746 # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
747 !defined(__EXCEPTIONS)
748 # define GTEST_HAS_RTTI 0
749 # else
750 # define GTEST_HAS_RTTI 1
751 # endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
752 # else
753 # define GTEST_HAS_RTTI 0
754 # endif // __GXX_RTTI
755
756 // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
757 // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
758 // first version with C++ support.
759 # elif defined(__clang__)
760
761 # define GTEST_HAS_RTTI __has_feature(cxx_rtti)
762
763 // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
764 // both the typeid and dynamic_cast features are present.
765 # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
766
767 # ifdef __RTTI_ALL__
768 # define GTEST_HAS_RTTI 1
769 # else
770 # define GTEST_HAS_RTTI 0
771 # endif
772
773 # else
774
775 // For all other compilers, we assume RTTI is enabled.
776 # define GTEST_HAS_RTTI 1
777
778 # endif // _MSC_VER
779
780 #endif // GTEST_HAS_RTTI
781
782 // It's this header's responsibility to #include <typeinfo> when RTTI
783 // is enabled.
784 #if GTEST_HAS_RTTI
785 # include <typeinfo>
786 #endif
787
788 // Determines whether Google Test can use the pthreads library.
789 #ifndef GTEST_HAS_PTHREAD
790 // The user didn't tell us explicitly, so we make reasonable assumptions about
791 // which platforms have pthreads support.
792 //
793 // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
794 // to your compiler flags.
795 #define GTEST_HAS_PTHREAD \
796 (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \
797 GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
798 GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \
799 GTEST_OS_HAIKU)
800 #endif // GTEST_HAS_PTHREAD
801
802 #if GTEST_HAS_PTHREAD
803 // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
804 // true.
805 # include <pthread.h> // NOLINT
806
807 // For timespec and nanosleep, used below.
808 # include <time.h> // NOLINT
809 #endif
810
811 // Determines whether clone(2) is supported.
812 // Usually it will only be available on Linux, excluding
813 // Linux on the Itanium architecture.
814 // Also see http://linux.die.net/man/2/clone.
815 #ifndef GTEST_HAS_CLONE
816 // The user didn't tell us, so we need to figure it out.
817
818 # if GTEST_OS_LINUX && !defined(__ia64__)
819 # if GTEST_OS_LINUX_ANDROID
820 // On Android, clone() became available at different API levels for each 32-bit
821 // architecture.
822 # if defined(__LP64__) || \
823 (defined(__arm__) && __ANDROID_API__ >= 9) || \
824 (defined(__mips__) && __ANDROID_API__ >= 12) || \
825 (defined(__i386__) && __ANDROID_API__ >= 17)
826 # define GTEST_HAS_CLONE 1
827 # else
828 # define GTEST_HAS_CLONE 0
829 # endif
830 # else
831 # define GTEST_HAS_CLONE 1
832 # endif
833 # else
834 # define GTEST_HAS_CLONE 0
835 # endif // GTEST_OS_LINUX && !defined(__ia64__)
836
837 #endif // GTEST_HAS_CLONE
838
839 // Determines whether to support stream redirection. This is used to test
840 // output correctness and to implement death tests.
841 #ifndef GTEST_HAS_STREAM_REDIRECTION
842 // By default, we assume that stream redirection is supported on all
843 // platforms except known mobile ones.
844 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
845 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
846 # define GTEST_HAS_STREAM_REDIRECTION 0
847 # else
848 # define GTEST_HAS_STREAM_REDIRECTION 1
849 # endif // !GTEST_OS_WINDOWS_MOBILE
850 #endif // GTEST_HAS_STREAM_REDIRECTION
851
852 // Determines whether to support death tests.
853 // pops up a dialog window that cannot be suppressed programmatically.
854 #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
855 (GTEST_OS_MAC && !GTEST_OS_IOS) || \
856 (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \
857 GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \
858 GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
859 GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU)
860 # define GTEST_HAS_DEATH_TEST 1
861 #endif
862
863 // Determines whether to support type-driven tests.
864
865 // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
866 // Sun Pro CC, IBM Visual Age, and HP aCC support.
867 #if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \
868 defined(__IBMCPP__) || defined(__HP_aCC)
869 # define GTEST_HAS_TYPED_TEST 1
870 # define GTEST_HAS_TYPED_TEST_P 1
871 #endif
872
873 // Determines whether the system compiler uses UTF-16 for encoding wide strings.
874 #define GTEST_WIDE_STRING_USES_UTF16_ \
875 (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2)
876
877 // Determines whether test results can be streamed to a socket.
878 #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \
879 GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD
880 # define GTEST_CAN_STREAM_RESULTS_ 1
881 #endif
882
883 // Defines some utility macros.
884
885 // The GNU compiler emits a warning if nested "if" statements are followed by
886 // an "else" statement and braces are not used to explicitly disambiguate the
887 // "else" binding. This leads to problems with code like:
888 //
889 // if (gate)
890 // ASSERT_*(condition) << "Some message";
891 //
892 // The "switch (0) case 0:" idiom is used to suppress this.
893 #ifdef __INTEL_COMPILER
894 # define GTEST_AMBIGUOUS_ELSE_BLOCKER_
895 #else
896 # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT
897 #endif
898
899 // Use this annotation at the end of a struct/class definition to
900 // prevent the compiler from optimizing away instances that are never
901 // used. This is useful when all interesting logic happens inside the
902 // c'tor and / or d'tor. Example:
903 //
904 // struct Foo {
905 // Foo() { ... }
906 // } GTEST_ATTRIBUTE_UNUSED_;
907 //
908 // Also use it after a variable or parameter declaration to tell the
909 // compiler the variable/parameter does not have to be used.
910 #if defined(__GNUC__) && !defined(COMPILER_ICC)
911 # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
912 #elif defined(__clang__)
913 # if __has_attribute(unused)
914 # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
915 # endif
916 #endif
917 #ifndef GTEST_ATTRIBUTE_UNUSED_
918 # define GTEST_ATTRIBUTE_UNUSED_
919 #endif
920
921 // Use this annotation before a function that takes a printf format string.
922 #if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC)
923 # if defined(__MINGW_PRINTF_FORMAT)
924 // MinGW has two different printf implementations. Ensure the format macro
925 // matches the selected implementation. See
926 // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.
927 # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
928 __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \
929 first_to_check)))
930 # else
931 # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
932 __attribute__((__format__(__printf__, string_index, first_to_check)))
933 # endif
934 #else
935 # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
936 #endif
937
938
939 // A macro to disallow copy operator=
940 // This should be used in the private: declarations for a class.
941 #define GTEST_DISALLOW_ASSIGN_(type) \
942 type& operator=(type const &) = delete
943
944 // A macro to disallow copy constructor and operator=
945 // This should be used in the private: declarations for a class.
946 #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \
947 type(type const&) = delete; \
948 type& operator=(type const&) = delete
949
950 // A macro to disallow move operator=
951 // This should be used in the private: declarations for a class.
952 #define GTEST_DISALLOW_MOVE_ASSIGN_(type) \
953 type& operator=(type &&) noexcept = delete
954
955 // A macro to disallow move constructor and operator=
956 // This should be used in the private: declarations for a class.
957 #define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \
958 type(type&&) noexcept = delete; \
959 type& operator=(type&&) noexcept = delete
960
961 // Tell the compiler to warn about unused return values for functions declared
962 // with this macro. The macro should be used on function declarations
963 // following the argument list:
964 //
965 // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
966 #if defined(__GNUC__) && !defined(COMPILER_ICC)
967 # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
968 #else
969 # define GTEST_MUST_USE_RESULT_
970 #endif // __GNUC__ && !COMPILER_ICC
971
972 // MS C++ compiler emits warning when a conditional expression is compile time
973 // constant. In some contexts this warning is false positive and needs to be
974 // suppressed. Use the following two macros in such cases:
975 //
976 // GTEST_INTENTIONAL_CONST_COND_PUSH_()
977 // while (true) {
978 // GTEST_INTENTIONAL_CONST_COND_POP_()
979 // }
980 # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
981 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
982 # define GTEST_INTENTIONAL_CONST_COND_POP_() \
983 GTEST_DISABLE_MSC_WARNINGS_POP_()
984
985 // Determine whether the compiler supports Microsoft's Structured Exception
986 // Handling. This is supported by several Windows compilers but generally
987 // does not exist on any other system.
988 #ifndef GTEST_HAS_SEH
989 // The user didn't tell us, so we need to figure it out.
990
991 # if defined(_MSC_VER) || defined(__BORLANDC__)
992 // These two compilers are known to support SEH.
993 # define GTEST_HAS_SEH 1
994 # else
995 // Assume no SEH.
996 # define GTEST_HAS_SEH 0
997 # endif
998
999 #endif // GTEST_HAS_SEH
1000
1001 #ifndef GTEST_IS_THREADSAFE
1002
1003 #define GTEST_IS_THREADSAFE \
1004 (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \
1005 (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \
1006 GTEST_HAS_PTHREAD)
1007
1008 #endif // GTEST_IS_THREADSAFE
1009
1010 // GTEST_API_ qualifies all symbols that must be exported. The definitions below
1011 // are guarded by #ifndef to give embedders a chance to define GTEST_API_ in
1012 // gtest/internal/custom/gtest-port.h
1013 #ifndef GTEST_API_
1014
1015 #ifdef _MSC_VER
1016 # if GTEST_LINKED_AS_SHARED_LIBRARY
1017 # define GTEST_API_ __declspec(dllimport)
1018 # elif GTEST_CREATE_SHARED_LIBRARY
1019 # define GTEST_API_ __declspec(dllexport)
1020 # endif
1021 #elif __GNUC__ >= 4 || defined(__clang__)
1022 # define GTEST_API_ __attribute__((visibility ("default")))
1023 #endif // _MSC_VER
1024
1025 #endif // GTEST_API_
1026
1027 #ifndef GTEST_API_
1028 # define GTEST_API_
1029 #endif // GTEST_API_
1030
1031 #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE
1032 # define GTEST_DEFAULT_DEATH_TEST_STYLE "fast"
1033 #endif // GTEST_DEFAULT_DEATH_TEST_STYLE
1034
1035 #ifdef __GNUC__
1036 // Ask the compiler to never inline a given function.
1037 # define GTEST_NO_INLINE_ __attribute__((noinline))
1038 #else
1039 # define GTEST_NO_INLINE_
1040 #endif
1041
1042 // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
1043 #if !defined(GTEST_HAS_CXXABI_H_)
1044 # if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
1045 # define GTEST_HAS_CXXABI_H_ 1
1046 # else
1047 # define GTEST_HAS_CXXABI_H_ 0
1048 # endif
1049 #endif
1050
1051 // A function level attribute to disable checking for use of uninitialized
1052 // memory when built with MemorySanitizer.
1053 #if defined(__clang__)
1054 # if __has_feature(memory_sanitizer)
1055 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
1056 __attribute__((no_sanitize_memory))
1057 # else
1058 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
1059 # endif // __has_feature(memory_sanitizer)
1060 #else
1061 # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
1062 #endif // __clang__
1063
1064 // A function level attribute to disable AddressSanitizer instrumentation.
1065 #if defined(__clang__)
1066 # if __has_feature(address_sanitizer)
1067 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
1068 __attribute__((no_sanitize_address))
1069 # else
1070 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1071 # endif // __has_feature(address_sanitizer)
1072 #else
1073 # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
1074 #endif // __clang__
1075
1076 // A function level attribute to disable HWAddressSanitizer instrumentation.
1077 #if defined(__clang__)
1078 # if __has_feature(hwaddress_sanitizer)
1079 # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
1080 __attribute__((no_sanitize("hwaddress")))
1081 # else
1082 # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1083 # endif // __has_feature(hwaddress_sanitizer)
1084 #else
1085 # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
1086 #endif // __clang__
1087
1088 // A function level attribute to disable ThreadSanitizer instrumentation.
1089 #if defined(__clang__)
1090 # if __has_feature(thread_sanitizer)
1091 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
1092 __attribute__((no_sanitize_thread))
1093 # else
1094 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
1095 # endif // __has_feature(thread_sanitizer)
1096 #else
1097 # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
1098 #endif // __clang__
1099
1100 namespace testing {
1101
1102 class Message;
1103
1104 // Legacy imports for backwards compatibility.
1105 // New code should use std:: names directly.
1106 using std::get;
1107 using std::make_tuple;
1108 using std::tuple;
1109 using std::tuple_element;
1110 using std::tuple_size;
1111
1112 namespace internal {
1113
1114 // A secret type that Google Test users don't know about. It has no
1115 // definition on purpose. Therefore it's impossible to create a
1116 // Secret object, which is what we want.
1117 class Secret;
1118
1119 // The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile
1120 // time expression is true (in new code, use static_assert instead). For
1121 // example, you could use it to verify the size of a static array:
1122 //
1123 // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
1124 // names_incorrect_size);
1125 //
1126 // The second argument to the macro must be a valid C++ identifier. If the
1127 // expression is false, compiler will issue an error containing this identifier.
1128 #define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
1129
1130 // A helper for suppressing warnings on constant condition. It just
1131 // returns 'condition'.
1132 GTEST_API_ bool IsTrue(bool condition);
1133
1134 // Defines RE.
1135
1136 #if GTEST_USES_PCRE
1137 // if used, PCRE is injected by custom/gtest-port.h
1138 #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
1139
1140 // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
1141 // Regular Expression syntax.
1142 class GTEST_API_ RE {
1143 public:
1144 // A copy constructor is required by the Standard to initialize object
1145 // references from r-values.
1146 RE(const RE& other) { Init(other.pattern()); }
1147
1148 // Constructs an RE from a string.
1149 RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT
1150
1151 RE(const char* regex) { Init(regex); } // NOLINT
1152 ~RE();
1153
1154 // Returns the string representation of the regex.
1155 const char* pattern() const { return pattern_; }
1156
1157 // FullMatch(str, re) returns true if and only if regular expression re
1158 // matches the entire str.
1159 // PartialMatch(str, re) returns true if and only if regular expression re
1160 // matches a substring of str (including str itself).
1161 static bool FullMatch(const ::std::string& str, const RE& re) {
1162 return FullMatch(str.c_str(), re);
1163 }
1164 static bool PartialMatch(const ::std::string& str, const RE& re) {
1165 return PartialMatch(str.c_str(), re);
1166 }
1167
1168 static bool FullMatch(const char* str, const RE& re);
1169 static bool PartialMatch(const char* str, const RE& re);
1170
1171 private:
1172 void Init(const char* regex);
1173 const char* pattern_;
1174 bool is_valid_;
1175
1176 # if GTEST_USES_POSIX_RE
1177
1178 regex_t full_regex_; // For FullMatch().
1179 regex_t partial_regex_; // For PartialMatch().
1180
1181 # else // GTEST_USES_SIMPLE_RE
1182
1183 const char* full_pattern_; // For FullMatch();
1184
1185 # endif
1186 };
1187
1188 #endif // GTEST_USES_PCRE
1189
1190 // Formats a source file path and a line number as they would appear
1191 // in an error message from the compiler used to compile this code.
1192 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
1193
1194 // Formats a file location for compiler-independent XML output.
1195 // Although this function is not platform dependent, we put it next to
1196 // FormatFileLocation in order to contrast the two functions.
1197 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
1198 int line);
1199
1200 // Defines logging utilities:
1201 // GTEST_LOG_(severity) - logs messages at the specified severity level. The
1202 // message itself is streamed into the macro.
1203 // LogToStderr() - directs all log messages to stderr.
1204 // FlushInfoLog() - flushes informational log messages.
1205
1206 enum GTestLogSeverity {
1207 GTEST_INFO,
1208 GTEST_WARNING,
1209 GTEST_ERROR,
1210 GTEST_FATAL
1211 };
1212
1213 // Formats log entry severity, provides a stream object for streaming the
1214 // log message, and terminates the message with a newline when going out of
1215 // scope.
1216 class GTEST_API_ GTestLog {
1217 public:
1218 GTestLog(GTestLogSeverity severity, const char* file, int line);
1219
1220 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
1221 ~GTestLog();
1222
1223 ::std::ostream& GetStream() { return ::std::cerr; }
1224
1225 private:
1226 const GTestLogSeverity severity_;
1227
1228 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
1229 };
1230
1231 #if !defined(GTEST_LOG_)
1232
1233 # define GTEST_LOG_(severity) \
1234 ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
1235 __FILE__, __LINE__).GetStream()
1236
1237 inline void LogToStderr() {}
1238 inline void FlushInfoLog() { fflush(nullptr); }
1239
1240 #endif // !defined(GTEST_LOG_)
1241
1242 #if !defined(GTEST_CHECK_)
1243 // INTERNAL IMPLEMENTATION - DO NOT USE.
1244 //
1245 // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
1246 // is not satisfied.
1247 // Synopsys:
1248 // GTEST_CHECK_(boolean_condition);
1249 // or
1250 // GTEST_CHECK_(boolean_condition) << "Additional message";
1251 //
1252 // This checks the condition and if the condition is not satisfied
1253 // it prints message about the condition violation, including the
1254 // condition itself, plus additional message streamed into it, if any,
1255 // and then it aborts the program. It aborts the program irrespective of
1256 // whether it is built in the debug mode or not.
1257 # define GTEST_CHECK_(condition) \
1258 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1259 if (::testing::internal::IsTrue(condition)) \
1260 ; \
1261 else \
1262 GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
1263 #endif // !defined(GTEST_CHECK_)
1264
1265 // An all-mode assert to verify that the given POSIX-style function
1266 // call returns 0 (indicating success). Known limitation: this
1267 // doesn't expand to a balanced 'if' statement, so enclose the macro
1268 // in {} if you need to use it as the only statement in an 'if'
1269 // branch.
1270 #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
1271 if (const int gtest_error = (posix_call)) \
1272 GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
1273 << gtest_error
1274
1275 // Transforms "T" into "const T&" according to standard reference collapsing
1276 // rules (this is only needed as a backport for C++98 compilers that do not
1277 // support reference collapsing). Specifically, it transforms:
1278 //
1279 // char ==> const char&
1280 // const char ==> const char&
1281 // char& ==> char&
1282 // const char& ==> const char&
1283 //
1284 // Note that the non-const reference will not have "const" added. This is
1285 // standard, and necessary so that "T" can always bind to "const T&".
1286 template <typename T>
1287 struct ConstRef { typedef const T& type; };
1288 template <typename T>
1289 struct ConstRef<T&> { typedef T& type; };
1290
1291 // The argument T must depend on some template parameters.
1292 #define GTEST_REFERENCE_TO_CONST_(T) \
1293 typename ::testing::internal::ConstRef<T>::type
1294
1295 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1296 //
1297 // Use ImplicitCast_ as a safe version of static_cast for upcasting in
1298 // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
1299 // const Foo*). When you use ImplicitCast_, the compiler checks that
1300 // the cast is safe. Such explicit ImplicitCast_s are necessary in
1301 // surprisingly many situations where C++ demands an exact type match
1302 // instead of an argument type convertable to a target type.
1303 //
1304 // The syntax for using ImplicitCast_ is the same as for static_cast:
1305 //
1306 // ImplicitCast_<ToType>(expr)
1307 //
1308 // ImplicitCast_ would have been part of the C++ standard library,
1309 // but the proposal was submitted too late. It will probably make
1310 // its way into the language in the future.
1311 //
1312 // This relatively ugly name is intentional. It prevents clashes with
1313 // similar functions users may have (e.g., implicit_cast). The internal
1314 // namespace alone is not enough because the function can be found by ADL.
1315 template<typename To>
1316 inline To ImplicitCast_(To x) { return x; }
1317
1318 // When you upcast (that is, cast a pointer from type Foo to type
1319 // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
1320 // always succeed. When you downcast (that is, cast a pointer from
1321 // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
1322 // how do you know the pointer is really of type SubclassOfFoo? It
1323 // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
1324 // when you downcast, you should use this macro. In debug mode, we
1325 // use dynamic_cast<> to double-check the downcast is legal (we die
1326 // if it's not). In normal mode, we do the efficient static_cast<>
1327 // instead. Thus, it's important to test in debug mode to make sure
1328 // the cast is legal!
1329 // This is the only place in the code we should use dynamic_cast<>.
1330 // In particular, you SHOULDN'T be using dynamic_cast<> in order to
1331 // do RTTI (eg code like this:
1332 // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
1333 // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
1334 // You should design the code some other way not to need this.
1335 //
1336 // This relatively ugly name is intentional. It prevents clashes with
1337 // similar functions users may have (e.g., down_cast). The internal
1338 // namespace alone is not enough because the function can be found by ADL.
1339 template<typename To, typename From> // use like this: DownCast_<T*>(foo);
1340 inline To DownCast_(From* f) { // so we only accept pointers
1341 // Ensures that To is a sub-type of From *. This test is here only
1342 // for compile-time type checking, and has no overhead in an
1343 // optimized build at run-time, as it will be optimized away
1344 // completely.
1345 GTEST_INTENTIONAL_CONST_COND_PUSH_()
1346 if (false) {
1347 GTEST_INTENTIONAL_CONST_COND_POP_()
1348 const To to = nullptr;
1349 ::testing::internal::ImplicitCast_<From*>(to);
1350 }
1351
1352 #if GTEST_HAS_RTTI
1353 // RTTI: debug mode only!
1354 GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);
1355 #endif
1356 return static_cast<To>(f);
1357 }
1358
1359 // Downcasts the pointer of type Base to Derived.
1360 // Derived must be a subclass of Base. The parameter MUST
1361 // point to a class of type Derived, not any subclass of it.
1362 // When RTTI is available, the function performs a runtime
1363 // check to enforce this.
1364 template <class Derived, class Base>
1365 Derived* CheckedDowncastToActualType(Base* base) {
1366 #if GTEST_HAS_RTTI
1367 GTEST_CHECK_(typeid(*base) == typeid(Derived));
1368 #endif
1369
1370 #if GTEST_HAS_DOWNCAST_
1371 return ::down_cast<Derived*>(base);
1372 #elif GTEST_HAS_RTTI
1373 return dynamic_cast<Derived*>(base); // NOLINT
1374 #else
1375 return static_cast<Derived*>(base); // Poor man's downcast.
1376 #endif
1377 }
1378
1379 #if GTEST_HAS_STREAM_REDIRECTION
1380
1381 // Defines the stderr capturer:
1382 // CaptureStdout - starts capturing stdout.
1383 // GetCapturedStdout - stops capturing stdout and returns the captured string.
1384 // CaptureStderr - starts capturing stderr.
1385 // GetCapturedStderr - stops capturing stderr and returns the captured string.
1386 //
1387 GTEST_API_ void CaptureStdout();
1388 GTEST_API_ std::string GetCapturedStdout();
1389 GTEST_API_ void CaptureStderr();
1390 GTEST_API_ std::string GetCapturedStderr();
1391
1392 #endif // GTEST_HAS_STREAM_REDIRECTION
1393 // Returns the size (in bytes) of a file.
1394 GTEST_API_ size_t GetFileSize(FILE* file);
1395
1396 // Reads the entire content of a file as a string.
1397 GTEST_API_ std::string ReadEntireFile(FILE* file);
1398
1399 // All command line arguments.
1400 GTEST_API_ std::vector<std::string> GetArgvs();
1401
1402 #if GTEST_HAS_DEATH_TEST
1403
1404 std::vector<std::string> GetInjectableArgvs();
1405 // Deprecated: pass the args vector by value instead.
1406 void SetInjectableArgvs(const std::vector<std::string>* new_argvs);
1407 void SetInjectableArgvs(const std::vector<std::string>& new_argvs);
1408 void ClearInjectableArgvs();
1409
1410 #endif // GTEST_HAS_DEATH_TEST
1411
1412 // Defines synchronization primitives.
1413 #if GTEST_IS_THREADSAFE
1414 # if GTEST_HAS_PTHREAD
1415 // Sleeps for (roughly) n milliseconds. This function is only for testing
1416 // Google Test's own constructs. Don't use it in user tests, either
1417 // directly or indirectly.
1418 inline void SleepMilliseconds(int n) {
1419 const timespec time = {
1420 0, // 0 seconds.
1421 n * 1000L * 1000L, // And n ms.
1422 };
1423 nanosleep(&time, nullptr);
1424 }
1425 # endif // GTEST_HAS_PTHREAD
1426
1427 # if GTEST_HAS_NOTIFICATION_
1428 // Notification has already been imported into the namespace.
1429 // Nothing to do here.
1430
1431 # elif GTEST_HAS_PTHREAD
1432 // Allows a controller thread to pause execution of newly created
1433 // threads until notified. Instances of this class must be created
1434 // and destroyed in the controller thread.
1435 //
1436 // This class is only for testing Google Test's own constructs. Do not
1437 // use it in user tests, either directly or indirectly.
1438 class Notification {
1439 public:
1440 Notification() : notified_(false) {
1441 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
1442 }
1443 ~Notification() {
1444 pthread_mutex_destroy(&mutex_);
1445 }
1446
1447 // Notifies all threads created with this notification to start. Must
1448 // be called from the controller thread.
1449 void Notify() {
1450 pthread_mutex_lock(&mutex_);
1451 notified_ = true;
1452 pthread_mutex_unlock(&mutex_);
1453 }
1454
1455 // Blocks until the controller thread notifies. Must be called from a test
1456 // thread.
1457 void WaitForNotification() {
1458 for (;;) {
1459 pthread_mutex_lock(&mutex_);
1460 const bool notified = notified_;
1461 pthread_mutex_unlock(&mutex_);
1462 if (notified)
1463 break;
1464 SleepMilliseconds(10);
1465 }
1466 }
1467
1468 private:
1469 pthread_mutex_t mutex_;
1470 bool notified_;
1471
1472 GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1473 };
1474
1475 # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1476
1477 GTEST_API_ void SleepMilliseconds(int n);
1478
1479 // Provides leak-safe Windows kernel handle ownership.
1480 // Used in death tests and in threading support.
1481 class GTEST_API_ AutoHandle {
1482 public:
1483 // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
1484 // avoid including <windows.h> in this header file. Including <windows.h> is
1485 // undesirable because it defines a lot of symbols and macros that tend to
1486 // conflict with client code. This assumption is verified by
1487 // WindowsTypesTest.HANDLEIsVoidStar.
1488 typedef void* Handle;
1489 AutoHandle();
1490 explicit AutoHandle(Handle handle);
1491
1492 ~AutoHandle();
1493
1494 Handle Get() const;
1495 void Reset();
1496 void Reset(Handle handle);
1497
1498 private:
1499 // Returns true if and only if the handle is a valid handle object that can be
1500 // closed.
1501 bool IsCloseable() const;
1502
1503 Handle handle_;
1504
1505 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1506 };
1507
1508 // Allows a controller thread to pause execution of newly created
1509 // threads until notified. Instances of this class must be created
1510 // and destroyed in the controller thread.
1511 //
1512 // This class is only for testing Google Test's own constructs. Do not
1513 // use it in user tests, either directly or indirectly.
1514 class GTEST_API_ Notification {
1515 public:
1516 Notification();
1517 void Notify();
1518 void WaitForNotification();
1519
1520 private:
1521 AutoHandle event_;
1522
1523 GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
1524 };
1525 # endif // GTEST_HAS_NOTIFICATION_
1526
1527 // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
1528 // defined, but we don't want to use MinGW's pthreads implementation, which
1529 // has conformance problems with some versions of the POSIX standard.
1530 # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
1531
1532 // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
1533 // Consequently, it cannot select a correct instantiation of ThreadWithParam
1534 // in order to call its Run(). Introducing ThreadWithParamBase as a
1535 // non-templated base class for ThreadWithParam allows us to bypass this
1536 // problem.
1537 class ThreadWithParamBase {
1538 public:
1539 virtual ~ThreadWithParamBase() {}
1540 virtual void Run() = 0;
1541 };
1542
1543 // pthread_create() accepts a pointer to a function type with the C linkage.
1544 // According to the Standard (7.5/1), function types with different linkages
1545 // are different even if they are otherwise identical. Some compilers (for
1546 // example, SunStudio) treat them as different types. Since class methods
1547 // cannot be defined with C-linkage we need to define a free C-function to
1548 // pass into pthread_create().
1549 extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
1550 static_cast<ThreadWithParamBase*>(thread)->Run();
1551 return nullptr;
1552 }
1553
1554 // Helper class for testing Google Test's multi-threading constructs.
1555 // To use it, write:
1556 //
1557 // void ThreadFunc(int param) { /* Do things with param */ }
1558 // Notification thread_can_start;
1559 // ...
1560 // // The thread_can_start parameter is optional; you can supply NULL.
1561 // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
1562 // thread_can_start.Notify();
1563 //
1564 // These classes are only for testing Google Test's own constructs. Do
1565 // not use them in user tests, either directly or indirectly.
1566 template <typename T>
1567 class ThreadWithParam : public ThreadWithParamBase {
1568 public:
1569 typedef void UserThreadFunc(T);
1570
1571 ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1572 : func_(func),
1573 param_(param),
1574 thread_can_start_(thread_can_start),
1575 finished_(false) {
1576 ThreadWithParamBase* const base = this;
1577 // The thread can be created only after all fields except thread_
1578 // have been initialized.
1579 GTEST_CHECK_POSIX_SUCCESS_(
1580 pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base));
1581 }
1582 ~ThreadWithParam() override { Join(); }
1583
1584 void Join() {
1585 if (!finished_) {
1586 GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr));
1587 finished_ = true;
1588 }
1589 }
1590
1591 void Run() override {
1592 if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification();
1593 func_(param_);
1594 }
1595
1596 private:
1597 UserThreadFunc* const func_; // User-supplied thread function.
1598 const T param_; // User-supplied parameter to the thread function.
1599 // When non-NULL, used to block execution until the controller thread
1600 // notifies.
1601 Notification* const thread_can_start_;
1602 bool finished_; // true if and only if we know that the thread function has
1603 // finished.
1604 pthread_t thread_; // The native thread object.
1605
1606 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1607 };
1608 # endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
1609 // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1610
1611 # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
1612 // Mutex and ThreadLocal have already been imported into the namespace.
1613 // Nothing to do here.
1614
1615 # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
1616
1617 // Mutex implements mutex on Windows platforms. It is used in conjunction
1618 // with class MutexLock:
1619 //
1620 // Mutex mutex;
1621 // ...
1622 // MutexLock lock(&mutex); // Acquires the mutex and releases it at the
1623 // // end of the current scope.
1624 //
1625 // A static Mutex *must* be defined or declared using one of the following
1626 // macros:
1627 // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
1628 // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
1629 //
1630 // (A non-static Mutex is defined/declared in the usual way).
1631 class GTEST_API_ Mutex {
1632 public:
1633 enum MutexType { kStatic = 0, kDynamic = 1 };
1634 // We rely on kStaticMutex being 0 as it is to what the linker initializes
1635 // type_ in static mutexes. critical_section_ will be initialized lazily
1636 // in ThreadSafeLazyInit().
1637 enum StaticConstructorSelector { kStaticMutex = 0 };
1638
1639 // This constructor intentionally does nothing. It relies on type_ being
1640 // statically initialized to 0 (effectively setting it to kStatic) and on
1641 // ThreadSafeLazyInit() to lazily initialize the rest of the members.
1642 explicit Mutex(StaticConstructorSelector /*dummy*/) {}
1643
1644 Mutex();
1645 ~Mutex();
1646
1647 void Lock();
1648
1649 void Unlock();
1650
1651 // Does nothing if the current thread holds the mutex. Otherwise, crashes
1652 // with high probability.
1653 void AssertHeld();
1654
1655 private:
1656 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
1657 void ThreadSafeLazyInit();
1658
1659 // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503,
1660 // we assume that 0 is an invalid value for thread IDs.
1661 unsigned int owner_thread_id_;
1662
1663 // For static mutexes, we rely on these members being initialized to zeros
1664 // by the linker.
1665 MutexType type_;
1666 long critical_section_init_phase_; // NOLINT
1667 GTEST_CRITICAL_SECTION* critical_section_;
1668
1669 GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1670 };
1671
1672 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1673 extern ::testing::internal::Mutex mutex
1674
1675 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1676 ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
1677
1678 // We cannot name this class MutexLock because the ctor declaration would
1679 // conflict with a macro named MutexLock, which is defined on some
1680 // platforms. That macro is used as a defensive measure to prevent against
1681 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1682 // "MutexLock l(&mu)". Hence the typedef trick below.
1683 class GTestMutexLock {
1684 public:
1685 explicit GTestMutexLock(Mutex* mutex)
1686 : mutex_(mutex) { mutex_->Lock(); }
1687
1688 ~GTestMutexLock() { mutex_->Unlock(); }
1689
1690 private:
1691 Mutex* const mutex_;
1692
1693 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1694 };
1695
1696 typedef GTestMutexLock MutexLock;
1697
1698 // Base class for ValueHolder<T>. Allows a caller to hold and delete a value
1699 // without knowing its type.
1700 class ThreadLocalValueHolderBase {
1701 public:
1702 virtual ~ThreadLocalValueHolderBase() {}
1703 };
1704
1705 // Provides a way for a thread to send notifications to a ThreadLocal
1706 // regardless of its parameter type.
1707 class ThreadLocalBase {
1708 public:
1709 // Creates a new ValueHolder<T> object holding a default value passed to
1710 // this ThreadLocal<T>'s constructor and returns it. It is the caller's
1711 // responsibility not to call this when the ThreadLocal<T> instance already
1712 // has a value on the current thread.
1713 virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
1714
1715 protected:
1716 ThreadLocalBase() {}
1717 virtual ~ThreadLocalBase() {}
1718
1719 private:
1720 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
1721 };
1722
1723 // Maps a thread to a set of ThreadLocals that have values instantiated on that
1724 // thread and notifies them when the thread exits. A ThreadLocal instance is
1725 // expected to persist until all threads it has values on have terminated.
1726 class GTEST_API_ ThreadLocalRegistry {
1727 public:
1728 // Registers thread_local_instance as having value on the current thread.
1729 // Returns a value that can be used to identify the thread from other threads.
1730 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
1731 const ThreadLocalBase* thread_local_instance);
1732
1733 // Invoked when a ThreadLocal instance is destroyed.
1734 static void OnThreadLocalDestroyed(
1735 const ThreadLocalBase* thread_local_instance);
1736 };
1737
1738 class GTEST_API_ ThreadWithParamBase {
1739 public:
1740 void Join();
1741
1742 protected:
1743 class Runnable {
1744 public:
1745 virtual ~Runnable() {}
1746 virtual void Run() = 0;
1747 };
1748
1749 ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
1750 virtual ~ThreadWithParamBase();
1751
1752 private:
1753 AutoHandle thread_;
1754 };
1755
1756 // Helper class for testing Google Test's multi-threading constructs.
1757 template <typename T>
1758 class ThreadWithParam : public ThreadWithParamBase {
1759 public:
1760 typedef void UserThreadFunc(T);
1761
1762 ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
1763 : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
1764 }
1765 virtual ~ThreadWithParam() {}
1766
1767 private:
1768 class RunnableImpl : public Runnable {
1769 public:
1770 RunnableImpl(UserThreadFunc* func, T param)
1771 : func_(func),
1772 param_(param) {
1773 }
1774 virtual ~RunnableImpl() {}
1775 virtual void Run() {
1776 func_(param_);
1777 }
1778
1779 private:
1780 UserThreadFunc* const func_;
1781 const T param_;
1782
1783 GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
1784 };
1785
1786 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
1787 };
1788
1789 // Implements thread-local storage on Windows systems.
1790 //
1791 // // Thread 1
1792 // ThreadLocal<int> tl(100); // 100 is the default value for each thread.
1793 //
1794 // // Thread 2
1795 // tl.set(150); // Changes the value for thread 2 only.
1796 // EXPECT_EQ(150, tl.get());
1797 //
1798 // // Thread 1
1799 // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value.
1800 // tl.set(200);
1801 // EXPECT_EQ(200, tl.get());
1802 //
1803 // The template type argument T must have a public copy constructor.
1804 // In addition, the default ThreadLocal constructor requires T to have
1805 // a public default constructor.
1806 //
1807 // The users of a TheadLocal instance have to make sure that all but one
1808 // threads (including the main one) using that instance have exited before
1809 // destroying it. Otherwise, the per-thread objects managed for them by the
1810 // ThreadLocal instance are not guaranteed to be destroyed on all platforms.
1811 //
1812 // Google Test only uses global ThreadLocal objects. That means they
1813 // will die after main() has returned. Therefore, no per-thread
1814 // object managed by Google Test will be leaked as long as all threads
1815 // using Google Test have exited when main() returns.
1816 template <typename T>
1817 class ThreadLocal : public ThreadLocalBase {
1818 public:
1819 ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
1820 explicit ThreadLocal(const T& value)
1821 : default_factory_(new InstanceValueHolderFactory(value)) {}
1822
1823 ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
1824
1825 T* pointer() { return GetOrCreateValue(); }
1826 const T* pointer() const { return GetOrCreateValue(); }
1827 const T& get() const { return *pointer(); }
1828 void set(const T& value) { *pointer() = value; }
1829
1830 private:
1831 // Holds a value of T. Can be deleted via its base class without the caller
1832 // knowing the type of T.
1833 class ValueHolder : public ThreadLocalValueHolderBase {
1834 public:
1835 ValueHolder() : value_() {}
1836 explicit ValueHolder(const T& value) : value_(value) {}
1837
1838 T* pointer() { return &value_; }
1839
1840 private:
1841 T value_;
1842 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
1843 };
1844
1845
1846 T* GetOrCreateValue() const {
1847 return static_cast<ValueHolder*>(
1848 ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
1849 }
1850
1851 virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
1852 return default_factory_->MakeNewHolder();
1853 }
1854
1855 class ValueHolderFactory {
1856 public:
1857 ValueHolderFactory() {}
1858 virtual ~ValueHolderFactory() {}
1859 virtual ValueHolder* MakeNewHolder() const = 0;
1860
1861 private:
1862 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
1863 };
1864
1865 class DefaultValueHolderFactory : public ValueHolderFactory {
1866 public:
1867 DefaultValueHolderFactory() {}
1868 ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
1869
1870 private:
1871 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
1872 };
1873
1874 class InstanceValueHolderFactory : public ValueHolderFactory {
1875 public:
1876 explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
1877 ValueHolder* MakeNewHolder() const override {
1878 return new ValueHolder(value_);
1879 }
1880
1881 private:
1882 const T value_; // The value for each thread.
1883
1884 GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
1885 };
1886
1887 std::unique_ptr<ValueHolderFactory> default_factory_;
1888
1889 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
1890 };
1891
1892 # elif GTEST_HAS_PTHREAD
1893
1894 // MutexBase and Mutex implement mutex on pthreads-based platforms.
1895 class MutexBase {
1896 public:
1897 // Acquires this mutex.
1898 void Lock() {
1899 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
1900 owner_ = pthread_self();
1901 has_owner_ = true;
1902 }
1903
1904 // Releases this mutex.
1905 void Unlock() {
1906 // Since the lock is being released the owner_ field should no longer be
1907 // considered valid. We don't protect writing to has_owner_ here, as it's
1908 // the caller's responsibility to ensure that the current thread holds the
1909 // mutex when this is called.
1910 has_owner_ = false;
1911 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
1912 }
1913
1914 // Does nothing if the current thread holds the mutex. Otherwise, crashes
1915 // with high probability.
1916 void AssertHeld() const {
1917 GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
1918 << "The current thread is not holding the mutex @" << this;
1919 }
1920
1921 // A static mutex may be used before main() is entered. It may even
1922 // be used before the dynamic initialization stage. Therefore we
1923 // must be able to initialize a static mutex object at link time.
1924 // This means MutexBase has to be a POD and its member variables
1925 // have to be public.
1926 public:
1927 pthread_mutex_t mutex_; // The underlying pthread mutex.
1928 // has_owner_ indicates whether the owner_ field below contains a valid thread
1929 // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
1930 // accesses to the owner_ field should be protected by a check of this field.
1931 // An alternative might be to memset() owner_ to all zeros, but there's no
1932 // guarantee that a zero'd pthread_t is necessarily invalid or even different
1933 // from pthread_self().
1934 bool has_owner_;
1935 pthread_t owner_; // The thread holding the mutex.
1936 };
1937
1938 // Forward-declares a static mutex.
1939 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
1940 extern ::testing::internal::MutexBase mutex
1941
1942 // Defines and statically (i.e. at link time) initializes a static mutex.
1943 // The initialization list here does not explicitly initialize each field,
1944 // instead relying on default initialization for the unspecified fields. In
1945 // particular, the owner_ field (a pthread_t) is not explicitly initialized.
1946 // This allows initialization to work whether pthread_t is a scalar or struct.
1947 // The flag -Wmissing-field-initializers must not be specified for this to work.
1948 #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
1949 ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0}
1950
1951 // The Mutex class can only be used for mutexes created at runtime. It
1952 // shares its API with MutexBase otherwise.
1953 class Mutex : public MutexBase {
1954 public:
1955 Mutex() {
1956 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
1957 has_owner_ = false;
1958 }
1959 ~Mutex() {
1960 GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
1961 }
1962
1963 private:
1964 GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
1965 };
1966
1967 // We cannot name this class MutexLock because the ctor declaration would
1968 // conflict with a macro named MutexLock, which is defined on some
1969 // platforms. That macro is used as a defensive measure to prevent against
1970 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
1971 // "MutexLock l(&mu)". Hence the typedef trick below.
1972 class GTestMutexLock {
1973 public:
1974 explicit GTestMutexLock(MutexBase* mutex)
1975 : mutex_(mutex) { mutex_->Lock(); }
1976
1977 ~GTestMutexLock() { mutex_->Unlock(); }
1978
1979 private:
1980 MutexBase* const mutex_;
1981
1982 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
1983 };
1984
1985 typedef GTestMutexLock MutexLock;
1986
1987 // Helpers for ThreadLocal.
1988
1989 // pthread_key_create() requires DeleteThreadLocalValue() to have
1990 // C-linkage. Therefore it cannot be templatized to access
1991 // ThreadLocal<T>. Hence the need for class
1992 // ThreadLocalValueHolderBase.
1993 class ThreadLocalValueHolderBase {
1994 public:
1995 virtual ~ThreadLocalValueHolderBase() {}
1996 };
1997
1998 // Called by pthread to delete thread-local data stored by
1999 // pthread_setspecific().
2000 extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
2001 delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
2002 }
2003
2004 // Implements thread-local storage on pthreads-based systems.
2005 template <typename T>
2006 class GTEST_API_ ThreadLocal {
2007 public:
2008 ThreadLocal()
2009 : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
2010 explicit ThreadLocal(const T& value)
2011 : key_(CreateKey()),
2012 default_factory_(new InstanceValueHolderFactory(value)) {}
2013
2014 ~ThreadLocal() {
2015 // Destroys the managed object for the current thread, if any.
2016 DeleteThreadLocalValue(pthread_getspecific(key_));
2017
2018 // Releases resources associated with the key. This will *not*
2019 // delete managed objects for other threads.
2020 GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
2021 }
2022
2023 T* pointer() { return GetOrCreateValue(); }
2024 const T* pointer() const { return GetOrCreateValue(); }
2025 const T& get() const { return *pointer(); }
2026 void set(const T& value) { *pointer() = value; }
2027
2028 private:
2029 // Holds a value of type T.
2030 class ValueHolder : public ThreadLocalValueHolderBase {
2031 public:
2032 ValueHolder() : value_() {}
2033 explicit ValueHolder(const T& value) : value_(value) {}
2034
2035 T* pointer() { return &value_; }
2036
2037 private:
2038 T value_;
2039 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
2040 };
2041
2042 static pthread_key_t CreateKey() {
2043 pthread_key_t key;
2044 // When a thread exits, DeleteThreadLocalValue() will be called on
2045 // the object managed for that thread.
2046 GTEST_CHECK_POSIX_SUCCESS_(
2047 pthread_key_create(&key, &DeleteThreadLocalValue));
2048 return key;
2049 }
2050
2051 T* GetOrCreateValue() const {
2052 ThreadLocalValueHolderBase* const holder =
2053 static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
2054 if (holder != nullptr) {
2055 return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
2056 }
2057
2058 ValueHolder* const new_holder = default_factory_->MakeNewHolder();
2059 ThreadLocalValueHolderBase* const holder_base = new_holder;
2060 GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
2061 return new_holder->pointer();
2062 }
2063
2064 class ValueHolderFactory {
2065 public:
2066 ValueHolderFactory() {}
2067 virtual ~ValueHolderFactory() {}
2068 virtual ValueHolder* MakeNewHolder() const = 0;
2069
2070 private:
2071 GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
2072 };
2073
2074 class DefaultValueHolderFactory : public ValueHolderFactory {
2075 public:
2076 DefaultValueHolderFactory() {}
2077 ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
2078
2079 private:
2080 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
2081 };
2082
2083 class InstanceValueHolderFactory : public ValueHolderFactory {
2084 public:
2085 explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
2086 ValueHolder* MakeNewHolder() const override {
2087 return new ValueHolder(value_);
2088 }
2089
2090 private:
2091 const T value_; // The value for each thread.
2092
2093 GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
2094 };
2095
2096 // A key pthreads uses for looking up per-thread values.
2097 const pthread_key_t key_;
2098 std::unique_ptr<ValueHolderFactory> default_factory_;
2099
2100 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
2101 };
2102
2103 # endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
2104
2105 #else // GTEST_IS_THREADSAFE
2106
2107 // A dummy implementation of synchronization primitives (mutex, lock,
2108 // and thread-local variable). Necessary for compiling Google Test where
2109 // mutex is not supported - using Google Test in multiple threads is not
2110 // supported on such platforms.
2111
2112 class Mutex {
2113 public:
2114 Mutex() {}
2115 void Lock() {}
2116 void Unlock() {}
2117 void AssertHeld() const {}
2118 };
2119
2120 # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
2121 extern ::testing::internal::Mutex mutex
2122
2123 # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
2124
2125 // We cannot name this class MutexLock because the ctor declaration would
2126 // conflict with a macro named MutexLock, which is defined on some
2127 // platforms. That macro is used as a defensive measure to prevent against
2128 // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
2129 // "MutexLock l(&mu)". Hence the typedef trick below.
2130 class GTestMutexLock {
2131 public:
2132 explicit GTestMutexLock(Mutex*) {} // NOLINT
2133 };
2134
2135 typedef GTestMutexLock MutexLock;
2136
2137 template <typename T>
2138 class GTEST_API_ ThreadLocal {
2139 public:
2140 ThreadLocal() : value_() {}
2141 explicit ThreadLocal(const T& value) : value_(value) {}
2142 T* pointer() { return &value_; }
2143 const T* pointer() const { return &value_; }
2144 const T& get() const { return value_; }
2145 void set(const T& value) { value_ = value; }
2146 private:
2147 T value_;
2148 };
2149
2150 #endif // GTEST_IS_THREADSAFE
2151
2152 // Returns the number of threads running in the process, or 0 to indicate that
2153 // we cannot detect it.
2154 GTEST_API_ size_t GetThreadCount();
2155
2156 #if GTEST_OS_WINDOWS
2157 # define GTEST_PATH_SEP_ "\\"
2158 # define GTEST_HAS_ALT_PATH_SEP_ 1
2159 #else
2160 # define GTEST_PATH_SEP_ "/"
2161 # define GTEST_HAS_ALT_PATH_SEP_ 0
2162 #endif // GTEST_OS_WINDOWS
2163
2164 // Utilities for char.
2165
2166 // isspace(int ch) and friends accept an unsigned char or EOF. char
2167 // may be signed, depending on the compiler (or compiler flags).
2168 // Therefore we need to cast a char to unsigned char before calling
2169 // isspace(), etc.
2170
2171 inline bool IsAlpha(char ch) {
2172 return isalpha(static_cast<unsigned char>(ch)) != 0;
2173 }
2174 inline bool IsAlNum(char ch) {
2175 return isalnum(static_cast<unsigned char>(ch)) != 0;
2176 }
2177 inline bool IsDigit(char ch) {
2178 return isdigit(static_cast<unsigned char>(ch)) != 0;
2179 }
2180 inline bool IsLower(char ch) {
2181 return islower(static_cast<unsigned char>(ch)) != 0;
2182 }
2183 inline bool IsSpace(char ch) {
2184 return isspace(static_cast<unsigned char>(ch)) != 0;
2185 }
2186 inline bool IsUpper(char ch) {
2187 return isupper(static_cast<unsigned char>(ch)) != 0;
2188 }
2189 inline bool IsXDigit(char ch) {
2190 return isxdigit(static_cast<unsigned char>(ch)) != 0;
2191 }
2192 #ifdef __cpp_char8_t
2193 inline bool IsXDigit(char8_t ch) {
2194 return isxdigit(static_cast<unsigned char>(ch)) != 0;
2195 }
2196 #endif
2197 inline bool IsXDigit(char16_t ch) {
2198 const unsigned char low_byte = static_cast<unsigned char>(ch);
2199 return ch == low_byte && isxdigit(low_byte) != 0;
2200 }
2201 inline bool IsXDigit(char32_t ch) {
2202 const unsigned char low_byte = static_cast<unsigned char>(ch);
2203 return ch == low_byte && isxdigit(low_byte) != 0;
2204 }
2205 inline bool IsXDigit(wchar_t ch) {
2206 const unsigned char low_byte = static_cast<unsigned char>(ch);
2207 return ch == low_byte && isxdigit(low_byte) != 0;
2208 }
2209
2210 inline char ToLower(char ch) {
2211 return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
2212 }
2213 inline char ToUpper(char ch) {
2214 return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
2215 }
2216
2217 inline std::string StripTrailingSpaces(std::string str) {
2218 std::string::iterator it = str.end();
2219 while (it != str.begin() && IsSpace(*--it))
2220 it = str.erase(it);
2221 return str;
2222 }
2223
2224 // The testing::internal::posix namespace holds wrappers for common
2225 // POSIX functions. These wrappers hide the differences between
2226 // Windows/MSVC and POSIX systems. Since some compilers define these
2227 // standard functions as macros, the wrapper cannot have the same name
2228 // as the wrapped function.
2229
2230 namespace posix {
2231
2232 // Functions with a different name on Windows.
2233
2234 #if GTEST_OS_WINDOWS
2235
2236 typedef struct _stat StatStruct;
2237
2238 # ifdef __BORLANDC__
2239 inline int DoIsATTY(int fd) { return isatty(fd); }
2240 inline int StrCaseCmp(const char* s1, const char* s2) {
2241 return stricmp(s1, s2);
2242 }
2243 inline char* StrDup(const char* src) { return strdup(src); }
2244 # else // !__BORLANDC__
2245 # if GTEST_OS_WINDOWS_MOBILE
2246 inline int DoIsATTY(int /* fd */) { return 0; }
2247 # else
2248 inline int DoIsATTY(int fd) { return _isatty(fd); }
2249 # endif // GTEST_OS_WINDOWS_MOBILE
2250 inline int StrCaseCmp(const char* s1, const char* s2) {
2251 return _stricmp(s1, s2);
2252 }
2253 inline char* StrDup(const char* src) { return _strdup(src); }
2254 # endif // __BORLANDC__
2255
2256 # if GTEST_OS_WINDOWS_MOBILE
2257 inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
2258 // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
2259 // time and thus not defined there.
2260 # else
2261 inline int FileNo(FILE* file) { return _fileno(file); }
2262 inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
2263 inline int RmDir(const char* dir) { return _rmdir(dir); }
2264 inline bool IsDir(const StatStruct& st) {
2265 return (_S_IFDIR & st.st_mode) != 0;
2266 }
2267 # endif // GTEST_OS_WINDOWS_MOBILE
2268
2269 #elif GTEST_OS_ESP8266
2270 typedef struct stat StatStruct;
2271
2272 inline int FileNo(FILE* file) { return fileno(file); }
2273 inline int DoIsATTY(int fd) { return isatty(fd); }
2274 inline int Stat(const char* path, StatStruct* buf) {
2275 // stat function not implemented on ESP8266
2276 return 0;
2277 }
2278 inline int StrCaseCmp(const char* s1, const char* s2) {
2279 return strcasecmp(s1, s2);
2280 }
2281 inline char* StrDup(const char* src) { return strdup(src); }
2282 inline int RmDir(const char* dir) { return rmdir(dir); }
2283 inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2284
2285 #else
2286
2287 typedef struct stat StatStruct;
2288
2289 inline int FileNo(FILE* file) { return fileno(file); }
2290 inline int DoIsATTY(int fd) { return isatty(fd); }
2291 inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
2292 inline int StrCaseCmp(const char* s1, const char* s2) {
2293 return strcasecmp(s1, s2);
2294 }
2295 inline char* StrDup(const char* src) { return strdup(src); }
2296 inline int RmDir(const char* dir) { return rmdir(dir); }
2297 inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
2298
2299 #endif // GTEST_OS_WINDOWS
2300
2301 inline int IsATTY(int fd) {
2302 // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout
2303 // to a file on Linux), which is unexpected, so save the previous value, and
2304 // restore it after the call.
2305 int savedErrno = errno;
2306 int isAttyValue = DoIsATTY(fd);
2307 errno = savedErrno;
2308
2309 return isAttyValue;
2310 }
2311
2312 // Functions deprecated by MSVC 8.0.
2313
2314 GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
2315
2316 // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
2317 // StrError() aren't needed on Windows CE at this time and thus not
2318 // defined there.
2319
2320 #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
2321 !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !GTEST_OS_XTENSA
2322 inline int ChDir(const char* dir) { return chdir(dir); }
2323 #endif
2324 inline FILE* FOpen(const char* path, const char* mode) {
2325 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2326 struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
2327 std::wstring_convert<wchar_codecvt> converter;
2328 std::wstring wide_path = converter.from_bytes(path);
2329 std::wstring wide_mode = converter.from_bytes(mode);
2330 return _wfopen(wide_path.c_str(), wide_mode.c_str());
2331 #else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2332 return fopen(path, mode);
2333 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2334 }
2335 #if !GTEST_OS_WINDOWS_MOBILE
2336 inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
2337 return freopen(path, mode, stream);
2338 }
2339 inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
2340 #endif
2341 inline int FClose(FILE* fp) { return fclose(fp); }
2342 #if !GTEST_OS_WINDOWS_MOBILE
2343 inline int Read(int fd, void* buf, unsigned int count) {
2344 return static_cast<int>(read(fd, buf, count));
2345 }
2346 inline int Write(int fd, const void* buf, unsigned int count) {
2347 return static_cast<int>(write(fd, buf, count));
2348 }
2349 inline int Close(int fd) { return close(fd); }
2350 inline const char* StrError(int errnum) { return strerror(errnum); }
2351 #endif
2352 inline const char* GetEnv(const char* name) {
2353 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
2354 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
2355 // We are on an embedded platform, which has no environment variables.
2356 static_cast<void>(name); // To prevent 'unused argument' warning.
2357 return nullptr;
2358 #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
2359 // Environment variables which we programmatically clear will be set to the
2360 // empty string rather than unset (NULL). Handle that case.
2361 const char* const env = getenv(name);
2362 return (env != nullptr && env[0] != '\0') ? env : nullptr;
2363 #else
2364 return getenv(name);
2365 #endif
2366 }
2367
2368 GTEST_DISABLE_MSC_DEPRECATED_POP_()
2369
2370 #if GTEST_OS_WINDOWS_MOBILE
2371 // Windows CE has no C library. The abort() function is used in
2372 // several places in Google Test. This implementation provides a reasonable
2373 // imitation of standard behaviour.
2374 [[noreturn]] void Abort();
2375 #else
2376 [[noreturn]] inline void Abort() { abort(); }
2377 #endif // GTEST_OS_WINDOWS_MOBILE
2378
2379 } // namespace posix
2380
2381 // MSVC "deprecates" snprintf and issues warnings wherever it is used. In
2382 // order to avoid these warnings, we need to use _snprintf or _snprintf_s on
2383 // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate
2384 // function in order to achieve that. We use macro definition here because
2385 // snprintf is a variadic function.
2386 #if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE
2387 // MSVC 2005 and above support variadic macros.
2388 # define GTEST_SNPRINTF_(buffer, size, format, ...) \
2389 _snprintf_s(buffer, size, size, format, __VA_ARGS__)
2390 #elif defined(_MSC_VER)
2391 // Windows CE does not define _snprintf_s
2392 # define GTEST_SNPRINTF_ _snprintf
2393 #else
2394 # define GTEST_SNPRINTF_ snprintf
2395 #endif
2396
2397 // The biggest signed integer type the compiler supports.
2398 //
2399 // long long is guaranteed to be at least 64-bits in C++11.
2400 using BiggestInt = long long; // NOLINT
2401
2402 // The maximum number a BiggestInt can represent.
2403 constexpr BiggestInt kMaxBiggestInt = (std::numeric_limits<BiggestInt>::max)();
2404
2405 // This template class serves as a compile-time function from size to
2406 // type. It maps a size in bytes to a primitive type with that
2407 // size. e.g.
2408 //
2409 // TypeWithSize<4>::UInt
2410 //
2411 // is typedef-ed to be unsigned int (unsigned integer made up of 4
2412 // bytes).
2413 //
2414 // Such functionality should belong to STL, but I cannot find it
2415 // there.
2416 //
2417 // Google Test uses this class in the implementation of floating-point
2418 // comparison.
2419 //
2420 // For now it only handles UInt (unsigned int) as that's all Google Test
2421 // needs. Other types can be easily added in the future if need
2422 // arises.
2423 template <size_t size>
2424 class TypeWithSize {
2425 public:
2426 // This prevents the user from using TypeWithSize<N> with incorrect
2427 // values of N.
2428 using UInt = void;
2429 };
2430
2431 // The specialization for size 4.
2432 template <>
2433 class TypeWithSize<4> {
2434 public:
2435 using Int = std::int32_t;
2436 using UInt = std::uint32_t;
2437 };
2438
2439 // The specialization for size 8.
2440 template <>
2441 class TypeWithSize<8> {
2442 public:
2443 using Int = std::int64_t;
2444 using UInt = std::uint64_t;
2445 };
2446
2447 // Integer types of known sizes.
2448 using TimeInMillis = int64_t; // Represents time in milliseconds.
2449
2450 // Utilities for command line flags and environment variables.
2451
2452 // Macro for referencing flags.
2453 #if !defined(GTEST_FLAG)
2454 # define GTEST_FLAG(name) FLAGS_gtest_##name
2455 #endif // !defined(GTEST_FLAG)
2456
2457 #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2458 # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
2459 #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
2460
2461 #if !defined(GTEST_DECLARE_bool_)
2462 # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
2463
2464 // Macros for declaring flags.
2465 # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
2466 # define GTEST_DECLARE_int32_(name) \
2467 GTEST_API_ extern std::int32_t GTEST_FLAG(name)
2468 # define GTEST_DECLARE_string_(name) \
2469 GTEST_API_ extern ::std::string GTEST_FLAG(name)
2470
2471 // Macros for defining flags.
2472 # define GTEST_DEFINE_bool_(name, default_val, doc) \
2473 GTEST_API_ bool GTEST_FLAG(name) = (default_val)
2474 # define GTEST_DEFINE_int32_(name, default_val, doc) \
2475 GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val)
2476 # define GTEST_DEFINE_string_(name, default_val, doc) \
2477 GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
2478
2479 #endif // !defined(GTEST_DECLARE_bool_)
2480
2481 // Thread annotations
2482 #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2483 # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
2484 # define GTEST_LOCK_EXCLUDED_(locks)
2485 #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
2486
2487 // Parses 'str' for a 32-bit signed integer. If successful, writes the result
2488 // to *value and returns true; otherwise leaves *value unchanged and returns
2489 // false.
2490 GTEST_API_ bool ParseInt32(const Message& src_text, const char* str,
2491 int32_t* value);
2492
2493 // Parses a bool/int32_t/string from the environment variable
2494 // corresponding to the given Google Test flag.
2495 bool BoolFromGTestEnv(const char* flag, bool default_val);
2496 GTEST_API_ int32_t Int32FromGTestEnv(const char* flag, int32_t default_val);
2497 std::string OutputFlagAlsoCheckEnvVar();
2498 const char* StringFromGTestEnv(const char* flag, const char* default_val);
2499
2500 } // namespace internal
2501 } // namespace testing
2502
2503 #if !defined(GTEST_INTERNAL_DEPRECATED)
2504
2505 // Internal Macro to mark an API deprecated, for googletest usage only
2506 // Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or
2507 // GTEST_INTERNAL_DEPRECATED(message) <return_type> myFunction(); Every usage of
2508 // a deprecated entity will trigger a warning when compiled with
2509 // `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler).
2510 // For msvc /W3 option will need to be used
2511 // Note that for 'other' compilers this macro evaluates to nothing to prevent
2512 // compilations errors.
2513 #if defined(_MSC_VER)
2514 #define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message))
2515 #elif defined(__GNUC__)
2516 #define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message)))
2517 #else
2518 #define GTEST_INTERNAL_DEPRECATED(message)
2519 #endif
2520
2521 #endif // !defined(GTEST_INTERNAL_DEPRECATED)
2522
2523 #if GTEST_HAS_ABSL
2524 // Always use absl::any for UniversalPrinter<> specializations if googletest
2525 // is built with absl support.
2526 #define GTEST_INTERNAL_HAS_ANY 1
2527 #include "absl/types/any.h"
2528 namespace testing {
2529 namespace internal {
2530 using Any = ::absl::any;
2531 } // namespace internal
2532 } // namespace testing
2533 #else
2534 #ifdef __has_include
2535 #if __has_include(<any>) && __cplusplus >= 201703L
2536 // Otherwise for C++17 and higher use std::any for UniversalPrinter<>
2537 // specializations.
2538 #define GTEST_INTERNAL_HAS_ANY 1
2539 #include <any>
2540 namespace testing {
2541 namespace internal {
2542 using Any = ::std::any;
2543 } // namespace internal
2544 } // namespace testing
2545 // The case where absl is configured NOT to alias std::any is not
2546 // supported.
2547 #endif // __has_include(<any>) && __cplusplus >= 201703L
2548 #endif // __has_include
2549 #endif // GTEST_HAS_ABSL
2550
2551 #if GTEST_HAS_ABSL
2552 // Always use absl::optional for UniversalPrinter<> specializations if
2553 // googletest is built with absl support.
2554 #define GTEST_INTERNAL_HAS_OPTIONAL 1
2555 #include "absl/types/optional.h"
2556 namespace testing {
2557 namespace internal {
2558 template <typename T>
2559 using Optional = ::absl::optional<T>;
2560 } // namespace internal
2561 } // namespace testing
2562 #else
2563 #ifdef __has_include
2564 #if __has_include(<optional>) && __cplusplus >= 201703L
2565 // Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
2566 // specializations.
2567 #define GTEST_INTERNAL_HAS_OPTIONAL 1
2568 #include <optional>
2569 namespace testing {
2570 namespace internal {
2571 template <typename T>
2572 using Optional = ::std::optional<T>;
2573 } // namespace internal
2574 } // namespace testing
2575 // The case where absl is configured NOT to alias std::optional is not
2576 // supported.
2577 #endif // __has_include(<optional>) && __cplusplus >= 201703L
2578 #endif // __has_include
2579 #endif // GTEST_HAS_ABSL
2580
2581 #if GTEST_HAS_ABSL
2582 // Always use absl::string_view for Matcher<> specializations if googletest
2583 // is built with absl support.
2584 # define GTEST_INTERNAL_HAS_STRING_VIEW 1
2585 #include "absl/strings/string_view.h"
2586 namespace testing {
2587 namespace internal {
2588 using StringView = ::absl::string_view;
2589 } // namespace internal
2590 } // namespace testing
2591 #else
2592 # ifdef __has_include
2593 # if __has_include(<string_view>) && __cplusplus >= 201703L
2594 // Otherwise for C++17 and higher use std::string_view for Matcher<>
2595 // specializations.
2596 # define GTEST_INTERNAL_HAS_STRING_VIEW 1
2597 #include <string_view>
2598 namespace testing {
2599 namespace internal {
2600 using StringView = ::std::string_view;
2601 } // namespace internal
2602 } // namespace testing
2603 // The case where absl is configured NOT to alias std::string_view is not
2604 // supported.
2605 # endif // __has_include(<string_view>) && __cplusplus >= 201703L
2606 # endif // __has_include
2607 #endif // GTEST_HAS_ABSL
2608
2609 #if GTEST_HAS_ABSL
2610 // Always use absl::variant for UniversalPrinter<> specializations if googletest
2611 // is built with absl support.
2612 #define GTEST_INTERNAL_HAS_VARIANT 1
2613 #include "absl/types/variant.h"
2614 namespace testing {
2615 namespace internal {
2616 template <typename... T>
2617 using Variant = ::absl::variant<T...>;
2618 } // namespace internal
2619 } // namespace testing
2620 #else
2621 #ifdef __has_include
2622 #if __has_include(<variant>) && __cplusplus >= 201703L
2623 // Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
2624 // specializations.
2625 #define GTEST_INTERNAL_HAS_VARIANT 1
2626 #include <variant>
2627 namespace testing {
2628 namespace internal {
2629 template <typename... T>
2630 using Variant = ::std::variant<T...>;
2631 } // namespace internal
2632 } // namespace testing
2633 // The case where absl is configured NOT to alias std::variant is not supported.
2634 #endif // __has_include(<variant>) && __cplusplus >= 201703L
2635 #endif // __has_include
2636 #endif // GTEST_HAS_ABSL
2637
2638 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
2639
2640 #if GTEST_OS_LINUX
2641 # include <stdlib.h>
2642 # include <sys/types.h>
2643 # include <sys/wait.h>
2644 # include <unistd.h>
2645 #endif // GTEST_OS_LINUX
2646
2647 #if GTEST_HAS_EXCEPTIONS
2648 # include <stdexcept>
2649 #endif
2650
2651 #include <ctype.h>
2652 #include <float.h>
2653 #include <string.h>
2654 #include <cstdint>
2655 #include <iomanip>
2656 #include <limits>
2657 #include <map>
2658 #include <set>
2659 #include <string>
2660 #include <type_traits>
2661 #include <vector>
2662
2663 // Copyright 2005, Google Inc.
2664 // All rights reserved.
2665 //
2666 // Redistribution and use in source and binary forms, with or without
2667 // modification, are permitted provided that the following conditions are
2668 // met:
2669 //
2670 // * Redistributions of source code must retain the above copyright
2671 // notice, this list of conditions and the following disclaimer.
2672 // * Redistributions in binary form must reproduce the above
2673 // copyright notice, this list of conditions and the following disclaimer
2674 // in the documentation and/or other materials provided with the
2675 // distribution.
2676 // * Neither the name of Google Inc. nor the names of its
2677 // contributors may be used to endorse or promote products derived from
2678 // this software without specific prior written permission.
2679 //
2680 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2681 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2682 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2683 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2684 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2685 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2686 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2687 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2688 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2689 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2690 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2691
2692 //
2693 // The Google C++ Testing and Mocking Framework (Google Test)
2694 //
2695 // This header file defines the Message class.
2696 //
2697 // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
2698 // leave some internal implementation details in this header file.
2699 // They are clearly marked by comments like this:
2700 //
2701 // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2702 //
2703 // Such code is NOT meant to be used by a user directly, and is subject
2704 // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
2705 // program!
2706
2707 // GOOGLETEST_CM0001 DO NOT DELETE
2708
2709 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
2710 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
2711
2712 #include <limits>
2713 #include <memory>
2714 #include <sstream>
2715
2716
2717 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
2718 /* class A needs to have dll-interface to be used by clients of class B */)
2719
2720 // Ensures that there is at least one operator<< in the global namespace.
2721 // See Message& operator<<(...) below for why.
2722 void operator<<(const testing::internal::Secret&, int);
2723
2724 namespace testing {
2725
2726 // The Message class works like an ostream repeater.
2727 //
2728 // Typical usage:
2729 //
2730 // 1. You stream a bunch of values to a Message object.
2731 // It will remember the text in a stringstream.
2732 // 2. Then you stream the Message object to an ostream.
2733 // This causes the text in the Message to be streamed
2734 // to the ostream.
2735 //
2736 // For example;
2737 //
2738 // testing::Message foo;
2739 // foo << 1 << " != " << 2;
2740 // std::cout << foo;
2741 //
2742 // will print "1 != 2".
2743 //
2744 // Message is not intended to be inherited from. In particular, its
2745 // destructor is not virtual.
2746 //
2747 // Note that stringstream behaves differently in gcc and in MSVC. You
2748 // can stream a NULL char pointer to it in the former, but not in the
2749 // latter (it causes an access violation if you do). The Message
2750 // class hides this difference by treating a NULL char pointer as
2751 // "(null)".
2752 class GTEST_API_ Message {
2753 private:
2754 // The type of basic IO manipulators (endl, ends, and flush) for
2755 // narrow streams.
2756 typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
2757
2758 public:
2759 // Constructs an empty Message.
2760 Message();
2761
2762 // Copy constructor.
2763 Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT
2764 *ss_ << msg.GetString();
2765 }
2766
2767 // Constructs a Message from a C-string.
2768 explicit Message(const char* str) : ss_(new ::std::stringstream) {
2769 *ss_ << str;
2770 }
2771
2772 // Streams a non-pointer value to this object.
2773 template <typename T>
2774 inline Message& operator <<(const T& val) {
2775 // Some libraries overload << for STL containers. These
2776 // overloads are defined in the global namespace instead of ::std.
2777 //
2778 // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
2779 // overloads are visible in either the std namespace or the global
2780 // namespace, but not other namespaces, including the testing
2781 // namespace which Google Test's Message class is in.
2782 //
2783 // To allow STL containers (and other types that has a << operator
2784 // defined in the global namespace) to be used in Google Test
2785 // assertions, testing::Message must access the custom << operator
2786 // from the global namespace. With this using declaration,
2787 // overloads of << defined in the global namespace and those
2788 // visible via Koenig lookup are both exposed in this function.
2789 using ::operator <<;
2790 *ss_ << val;
2791 return *this;
2792 }
2793
2794 // Streams a pointer value to this object.
2795 //
2796 // This function is an overload of the previous one. When you
2797 // stream a pointer to a Message, this definition will be used as it
2798 // is more specialized. (The C++ Standard, section
2799 // [temp.func.order].) If you stream a non-pointer, then the
2800 // previous definition will be used.
2801 //
2802 // The reason for this overload is that streaming a NULL pointer to
2803 // ostream is undefined behavior. Depending on the compiler, you
2804 // may get "0", "(nil)", "(null)", or an access violation. To
2805 // ensure consistent result across compilers, we always treat NULL
2806 // as "(null)".
2807 template <typename T>
2808 inline Message& operator <<(T* const& pointer) { // NOLINT
2809 if (pointer == nullptr) {
2810 *ss_ << "(null)";
2811 } else {
2812 *ss_ << pointer;
2813 }
2814 return *this;
2815 }
2816
2817 // Since the basic IO manipulators are overloaded for both narrow
2818 // and wide streams, we have to provide this specialized definition
2819 // of operator <<, even though its body is the same as the
2820 // templatized version above. Without this definition, streaming
2821 // endl or other basic IO manipulators to Message will confuse the
2822 // compiler.
2823 Message& operator <<(BasicNarrowIoManip val) {
2824 *ss_ << val;
2825 return *this;
2826 }
2827
2828 // Instead of 1/0, we want to see true/false for bool values.
2829 Message& operator <<(bool b) {
2830 return *this << (b ? "true" : "false");
2831 }
2832
2833 // These two overloads allow streaming a wide C string to a Message
2834 // using the UTF-8 encoding.
2835 Message& operator <<(const wchar_t* wide_c_str);
2836 Message& operator <<(wchar_t* wide_c_str);
2837
2838 #if GTEST_HAS_STD_WSTRING
2839 // Converts the given wide string to a narrow string using the UTF-8
2840 // encoding, and streams the result to this Message object.
2841 Message& operator <<(const ::std::wstring& wstr);
2842 #endif // GTEST_HAS_STD_WSTRING
2843
2844 // Gets the text streamed to this object so far as an std::string.
2845 // Each '\0' character in the buffer is replaced with "\\0".
2846 //
2847 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2848 std::string GetString() const;
2849
2850 private:
2851 // We'll hold the text streamed to this object here.
2852 const std::unique_ptr< ::std::stringstream> ss_;
2853
2854 // We declare (but don't implement) this to prevent the compiler
2855 // from implementing the assignment operator.
2856 void operator=(const Message&);
2857 };
2858
2859 // Streams a Message to an ostream.
2860 inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
2861 return os << sb.GetString();
2862 }
2863
2864 namespace internal {
2865
2866 // Converts a streamable value to an std::string. A NULL pointer is
2867 // converted to "(null)". When the input value is a ::string,
2868 // ::std::string, ::wstring, or ::std::wstring object, each NUL
2869 // character in it is replaced with "\\0".
2870 template <typename T>
2871 std::string StreamableToString(const T& streamable) {
2872 return (Message() << streamable).GetString();
2873 }
2874
2875 } // namespace internal
2876 } // namespace testing
2877
2878 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
2879
2880 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
2881 // Copyright 2008, Google Inc.
2882 // All rights reserved.
2883 //
2884 // Redistribution and use in source and binary forms, with or without
2885 // modification, are permitted provided that the following conditions are
2886 // met:
2887 //
2888 // * Redistributions of source code must retain the above copyright
2889 // notice, this list of conditions and the following disclaimer.
2890 // * Redistributions in binary form must reproduce the above
2891 // copyright notice, this list of conditions and the following disclaimer
2892 // in the documentation and/or other materials provided with the
2893 // distribution.
2894 // * Neither the name of Google Inc. nor the names of its
2895 // contributors may be used to endorse or promote products derived from
2896 // this software without specific prior written permission.
2897 //
2898 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2899 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2900 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2901 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2902 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2903 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2904 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2905 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2906 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2907 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2908 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2909 //
2910 // Google Test filepath utilities
2911 //
2912 // This header file declares classes and functions used internally by
2913 // Google Test. They are subject to change without notice.
2914 //
2915 // This file is #included in gtest/internal/gtest-internal.h.
2916 // Do not include this header file separately!
2917
2918 // GOOGLETEST_CM0001 DO NOT DELETE
2919
2920 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
2921 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
2922
2923 // Copyright 2005, Google Inc.
2924 // All rights reserved.
2925 //
2926 // Redistribution and use in source and binary forms, with or without
2927 // modification, are permitted provided that the following conditions are
2928 // met:
2929 //
2930 // * Redistributions of source code must retain the above copyright
2931 // notice, this list of conditions and the following disclaimer.
2932 // * Redistributions in binary form must reproduce the above
2933 // copyright notice, this list of conditions and the following disclaimer
2934 // in the documentation and/or other materials provided with the
2935 // distribution.
2936 // * Neither the name of Google Inc. nor the names of its
2937 // contributors may be used to endorse or promote products derived from
2938 // this software without specific prior written permission.
2939 //
2940 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2941 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2942 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2943 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2944 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2945 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2946 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2947 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2948 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2949 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2950 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2951 //
2952 // The Google C++ Testing and Mocking Framework (Google Test)
2953 //
2954 // This header file declares the String class and functions used internally by
2955 // Google Test. They are subject to change without notice. They should not used
2956 // by code external to Google Test.
2957 //
2958 // This header file is #included by gtest-internal.h.
2959 // It should not be #included by other files.
2960
2961 // GOOGLETEST_CM0001 DO NOT DELETE
2962
2963 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
2964 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
2965
2966 #ifdef __BORLANDC__
2967 // string.h is not guaranteed to provide strcpy on C++ Builder.
2968 # include <mem.h>
2969 #endif
2970
2971 #include <string.h>
2972 #include <cstdint>
2973 #include <string>
2974
2975
2976 namespace testing {
2977 namespace internal {
2978
2979 // String - an abstract class holding static string utilities.
2980 class GTEST_API_ String {
2981 public:
2982 // Static utility methods
2983
2984 // Clones a 0-terminated C string, allocating memory using new. The
2985 // caller is responsible for deleting the return value using
2986 // delete[]. Returns the cloned string, or NULL if the input is
2987 // NULL.
2988 //
2989 // This is different from strdup() in string.h, which allocates
2990 // memory using malloc().
2991 static const char* CloneCString(const char* c_str);
2992
2993 #if GTEST_OS_WINDOWS_MOBILE
2994 // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
2995 // able to pass strings to Win32 APIs on CE we need to convert them
2996 // to 'Unicode', UTF-16.
2997
2998 // Creates a UTF-16 wide string from the given ANSI string, allocating
2999 // memory using new. The caller is responsible for deleting the return
3000 // value using delete[]. Returns the wide string, or NULL if the
3001 // input is NULL.
3002 //
3003 // The wide string is created using the ANSI codepage (CP_ACP) to
3004 // match the behaviour of the ANSI versions of Win32 calls and the
3005 // C runtime.
3006 static LPCWSTR AnsiToUtf16(const char* c_str);
3007
3008 // Creates an ANSI string from the given wide string, allocating
3009 // memory using new. The caller is responsible for deleting the return
3010 // value using delete[]. Returns the ANSI string, or NULL if the
3011 // input is NULL.
3012 //
3013 // The returned string is created using the ANSI codepage (CP_ACP) to
3014 // match the behaviour of the ANSI versions of Win32 calls and the
3015 // C runtime.
3016 static const char* Utf16ToAnsi(LPCWSTR utf16_str);
3017 #endif
3018
3019 // Compares two C strings. Returns true if and only if they have the same
3020 // content.
3021 //
3022 // Unlike strcmp(), this function can handle NULL argument(s). A
3023 // NULL C string is considered different to any non-NULL C string,
3024 // including the empty string.
3025 static bool CStringEquals(const char* lhs, const char* rhs);
3026
3027 // Converts a wide C string to a String using the UTF-8 encoding.
3028 // NULL will be converted to "(null)". If an error occurred during
3029 // the conversion, "(failed to convert from wide string)" is
3030 // returned.
3031 static std::string ShowWideCString(const wchar_t* wide_c_str);
3032
3033 // Compares two wide C strings. Returns true if and only if they have the
3034 // same content.
3035 //
3036 // Unlike wcscmp(), this function can handle NULL argument(s). A
3037 // NULL C string is considered different to any non-NULL C string,
3038 // including the empty string.
3039 static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
3040
3041 // Compares two C strings, ignoring case. Returns true if and only if
3042 // they have the same content.
3043 //
3044 // Unlike strcasecmp(), this function can handle NULL argument(s).
3045 // A NULL C string is considered different to any non-NULL C string,
3046 // including the empty string.
3047 static bool CaseInsensitiveCStringEquals(const char* lhs,
3048 const char* rhs);
3049
3050 // Compares two wide C strings, ignoring case. Returns true if and only if
3051 // they have the same content.
3052 //
3053 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3054 // A NULL C string is considered different to any non-NULL wide C string,
3055 // including the empty string.
3056 // NB: The implementations on different platforms slightly differ.
3057 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3058 // environment variable. On GNU platform this method uses wcscasecmp
3059 // which compares according to LC_CTYPE category of the current locale.
3060 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3061 // current locale.
3062 static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3063 const wchar_t* rhs);
3064
3065 // Returns true if and only if the given string ends with the given suffix,
3066 // ignoring case. Any string is considered to end with an empty suffix.
3067 static bool EndsWithCaseInsensitive(
3068 const std::string& str, const std::string& suffix);
3069
3070 // Formats an int value as "%02d".
3071 static std::string FormatIntWidth2(int value); // "%02d" for width == 2
3072
3073 // Formats an int value to given width with leading zeros.
3074 static std::string FormatIntWidthN(int value, int width);
3075
3076 // Formats an int value as "%X".
3077 static std::string FormatHexInt(int value);
3078
3079 // Formats an int value as "%X".
3080 static std::string FormatHexUInt32(uint32_t value);
3081
3082 // Formats a byte as "%02X".
3083 static std::string FormatByte(unsigned char value);
3084
3085 private:
3086 String(); // Not meant to be instantiated.
3087 }; // class String
3088
3089 // Gets the content of the stringstream's buffer as an std::string. Each '\0'
3090 // character in the buffer is replaced with "\\0".
3091 GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
3092
3093 } // namespace internal
3094 } // namespace testing
3095
3096 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
3097
3098 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
3099 /* class A needs to have dll-interface to be used by clients of class B */)
3100
3101 namespace testing {
3102 namespace internal {
3103
3104 // FilePath - a class for file and directory pathname manipulation which
3105 // handles platform-specific conventions (like the pathname separator).
3106 // Used for helper functions for naming files in a directory for xml output.
3107 // Except for Set methods, all methods are const or static, which provides an
3108 // "immutable value object" -- useful for peace of mind.
3109 // A FilePath with a value ending in a path separator ("like/this/") represents
3110 // a directory, otherwise it is assumed to represent a file. In either case,
3111 // it may or may not represent an actual file or directory in the file system.
3112 // Names are NOT checked for syntax correctness -- no checking for illegal
3113 // characters, malformed paths, etc.
3114
3115 class GTEST_API_ FilePath {
3116 public:
3117 FilePath() : pathname_("") { }
3118 FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
3119
3120 explicit FilePath(const std::string& pathname) : pathname_(pathname) {
3121 Normalize();
3122 }
3123
3124 FilePath& operator=(const FilePath& rhs) {
3125 Set(rhs);
3126 return *this;
3127 }
3128
3129 void Set(const FilePath& rhs) {
3130 pathname_ = rhs.pathname_;
3131 }
3132
3133 const std::string& string() const { return pathname_; }
3134 const char* c_str() const { return pathname_.c_str(); }
3135
3136 // Returns the current working directory, or "" if unsuccessful.
3137 static FilePath GetCurrentDir();
3138
3139 // Given directory = "dir", base_name = "test", number = 0,
3140 // extension = "xml", returns "dir/test.xml". If number is greater
3141 // than zero (e.g., 12), returns "dir/test_12.xml".
3142 // On Windows platform, uses \ as the separator rather than /.
3143 static FilePath MakeFileName(const FilePath& directory,
3144 const FilePath& base_name,
3145 int number,
3146 const char* extension);
3147
3148 // Given directory = "dir", relative_path = "test.xml",
3149 // returns "dir/test.xml".
3150 // On Windows, uses \ as the separator rather than /.
3151 static FilePath ConcatPaths(const FilePath& directory,
3152 const FilePath& relative_path);
3153
3154 // Returns a pathname for a file that does not currently exist. The pathname
3155 // will be directory/base_name.extension or
3156 // directory/base_name_<number>.extension if directory/base_name.extension
3157 // already exists. The number will be incremented until a pathname is found
3158 // that does not already exist.
3159 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
3160 // There could be a race condition if two or more processes are calling this
3161 // function at the same time -- they could both pick the same filename.
3162 static FilePath GenerateUniqueFileName(const FilePath& directory,
3163 const FilePath& base_name,
3164 const char* extension);
3165
3166 // Returns true if and only if the path is "".
3167 bool IsEmpty() const { return pathname_.empty(); }
3168
3169 // If input name has a trailing separator character, removes it and returns
3170 // the name, otherwise return the name string unmodified.
3171 // On Windows platform, uses \ as the separator, other platforms use /.
3172 FilePath RemoveTrailingPathSeparator() const;
3173
3174 // Returns a copy of the FilePath with the directory part removed.
3175 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
3176 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
3177 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
3178 // returns an empty FilePath ("").
3179 // On Windows platform, '\' is the path separator, otherwise it is '/'.
3180 FilePath RemoveDirectoryName() const;
3181
3182 // RemoveFileName returns the directory path with the filename removed.
3183 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
3184 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
3185 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
3186 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
3187 // On Windows platform, '\' is the path separator, otherwise it is '/'.
3188 FilePath RemoveFileName() const;
3189
3190 // Returns a copy of the FilePath with the case-insensitive extension removed.
3191 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
3192 // FilePath("dir/file"). If a case-insensitive extension is not
3193 // found, returns a copy of the original FilePath.
3194 FilePath RemoveExtension(const char* extension) const;
3195
3196 // Creates directories so that path exists. Returns true if successful or if
3197 // the directories already exist; returns false if unable to create
3198 // directories for any reason. Will also return false if the FilePath does
3199 // not represent a directory (that is, it doesn't end with a path separator).
3200 bool CreateDirectoriesRecursively() const;
3201
3202 // Create the directory so that path exists. Returns true if successful or
3203 // if the directory already exists; returns false if unable to create the
3204 // directory for any reason, including if the parent directory does not
3205 // exist. Not named "CreateDirectory" because that's a macro on Windows.
3206 bool CreateFolder() const;
3207
3208 // Returns true if FilePath describes something in the file-system,
3209 // either a file, directory, or whatever, and that something exists.
3210 bool FileOrDirectoryExists() const;
3211
3212 // Returns true if pathname describes a directory in the file-system
3213 // that exists.
3214 bool DirectoryExists() const;
3215
3216 // Returns true if FilePath ends with a path separator, which indicates that
3217 // it is intended to represent a directory. Returns false otherwise.
3218 // This does NOT check that a directory (or file) actually exists.
3219 bool IsDirectory() const;
3220
3221 // Returns true if pathname describes a root directory. (Windows has one
3222 // root directory per disk drive.)
3223 bool IsRootDirectory() const;
3224
3225 // Returns true if pathname describes an absolute path.
3226 bool IsAbsolutePath() const;
3227
3228 private:
3229 // Replaces multiple consecutive separators with a single separator.
3230 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
3231 // redundancies that might be in a pathname involving "." or "..".
3232 //
3233 // A pathname with multiple consecutive separators may occur either through
3234 // user error or as a result of some scripts or APIs that generate a pathname
3235 // with a trailing separator. On other platforms the same API or script
3236 // may NOT generate a pathname with a trailing "/". Then elsewhere that
3237 // pathname may have another "/" and pathname components added to it,
3238 // without checking for the separator already being there.
3239 // The script language and operating system may allow paths like "foo//bar"
3240 // but some of the functions in FilePath will not handle that correctly. In
3241 // particular, RemoveTrailingPathSeparator() only removes one separator, and
3242 // it is called in CreateDirectoriesRecursively() assuming that it will change
3243 // a pathname from directory syntax (trailing separator) to filename syntax.
3244 //
3245 // On Windows this method also replaces the alternate path separator '/' with
3246 // the primary path separator '\\', so that for example "bar\\/\\foo" becomes
3247 // "bar\\foo".
3248
3249 void Normalize();
3250
3251 // Returns a pointer to the last occurrence of a valid path separator in
3252 // the FilePath. On Windows, for example, both '/' and '\' are valid path
3253 // separators. Returns NULL if no path separator was found.
3254 const char* FindLastPathSeparator() const;
3255
3256 std::string pathname_;
3257 }; // class FilePath
3258
3259 } // namespace internal
3260 } // namespace testing
3261
3262 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
3263
3264 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
3265 // Copyright 2008 Google Inc.
3266 // All Rights Reserved.
3267 //
3268 // Redistribution and use in source and binary forms, with or without
3269 // modification, are permitted provided that the following conditions are
3270 // met:
3271 //
3272 // * Redistributions of source code must retain the above copyright
3273 // notice, this list of conditions and the following disclaimer.
3274 // * Redistributions in binary form must reproduce the above
3275 // copyright notice, this list of conditions and the following disclaimer
3276 // in the documentation and/or other materials provided with the
3277 // distribution.
3278 // * Neither the name of Google Inc. nor the names of its
3279 // contributors may be used to endorse or promote products derived from
3280 // this software without specific prior written permission.
3281 //
3282 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
3283 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
3284 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
3285 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3286 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3287 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3288 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3289 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3290 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3291 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3292 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3293
3294 // Type utilities needed for implementing typed and type-parameterized
3295 // tests.
3296
3297 // GOOGLETEST_CM0001 DO NOT DELETE
3298
3299 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
3300 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
3301
3302
3303 // #ifdef __GNUC__ is too general here. It is possible to use gcc without using
3304 // libstdc++ (which is where cxxabi.h comes from).
3305 # if GTEST_HAS_CXXABI_H_
3306 # include <cxxabi.h>
3307 # elif defined(__HP_aCC)
3308 # include <acxx_demangle.h>
3309 # endif // GTEST_HASH_CXXABI_H_
3310
3311 namespace testing {
3312 namespace internal {
3313
3314 // Canonicalizes a given name with respect to the Standard C++ Library.
3315 // This handles removing the inline namespace within `std` that is
3316 // used by various standard libraries (e.g., `std::__1`). Names outside
3317 // of namespace std are returned unmodified.
3318 inline std::string CanonicalizeForStdLibVersioning(std::string s) {
3319 static const char prefix[] = "std::__";
3320 if (s.compare(0, strlen(prefix), prefix) == 0) {
3321 std::string::size_type end = s.find("::", strlen(prefix));
3322 if (end != s.npos) {
3323 // Erase everything between the initial `std` and the second `::`.
3324 s.erase(strlen("std"), end - strlen("std"));
3325 }
3326 }
3327 return s;
3328 }
3329
3330 #if GTEST_HAS_RTTI
3331 // GetTypeName(const std::type_info&) returns a human-readable name of type T.
3332 inline std::string GetTypeName(const std::type_info& type) {
3333 const char* const name = type.name();
3334 #if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
3335 int status = 0;
3336 // gcc's implementation of typeid(T).name() mangles the type name,
3337 // so we have to demangle it.
3338 #if GTEST_HAS_CXXABI_H_
3339 using abi::__cxa_demangle;
3340 #endif // GTEST_HAS_CXXABI_H_
3341 char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
3342 const std::string name_str(status == 0 ? readable_name : name);
3343 free(readable_name);
3344 return CanonicalizeForStdLibVersioning(name_str);
3345 #else
3346 return name;
3347 #endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
3348 }
3349 #endif // GTEST_HAS_RTTI
3350
3351 // GetTypeName<T>() returns a human-readable name of type T if and only if
3352 // RTTI is enabled, otherwise it returns a dummy type name.
3353 // NB: This function is also used in Google Mock, so don't move it inside of
3354 // the typed-test-only section below.
3355 template <typename T>
3356 std::string GetTypeName() {
3357 #if GTEST_HAS_RTTI
3358 return GetTypeName(typeid(T));
3359 #else
3360 return "<type>";
3361 #endif // GTEST_HAS_RTTI
3362 }
3363
3364 // A unique type indicating an empty node
3365 struct None {};
3366
3367 # define GTEST_TEMPLATE_ template <typename T> class
3368
3369 // The template "selector" struct TemplateSel<Tmpl> is used to
3370 // represent Tmpl, which must be a class template with one type
3371 // parameter, as a type. TemplateSel<Tmpl>::Bind<T>::type is defined
3372 // as the type Tmpl<T>. This allows us to actually instantiate the
3373 // template "selected" by TemplateSel<Tmpl>.
3374 //
3375 // This trick is necessary for simulating typedef for class templates,
3376 // which C++ doesn't support directly.
3377 template <GTEST_TEMPLATE_ Tmpl>
3378 struct TemplateSel {
3379 template <typename T>
3380 struct Bind {
3381 typedef Tmpl<T> type;
3382 };
3383 };
3384
3385 # define GTEST_BIND_(TmplSel, T) \
3386 TmplSel::template Bind<T>::type
3387
3388 template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>
3389 struct Templates {
3390 using Head = TemplateSel<Head_>;
3391 using Tail = Templates<Tail_...>;
3392 };
3393
3394 template <GTEST_TEMPLATE_ Head_>
3395 struct Templates<Head_> {
3396 using Head = TemplateSel<Head_>;
3397 using Tail = None;
3398 };
3399
3400 // Tuple-like type lists
3401 template <typename Head_, typename... Tail_>
3402 struct Types {
3403 using Head = Head_;
3404 using Tail = Types<Tail_...>;
3405 };
3406
3407 template <typename Head_>
3408 struct Types<Head_> {
3409 using Head = Head_;
3410 using Tail = None;
3411 };
3412
3413 // Helper metafunctions to tell apart a single type from types
3414 // generated by ::testing::Types
3415 template <typename... Ts>
3416 struct ProxyTypeList {
3417 using type = Types<Ts...>;
3418 };
3419
3420 template <typename>
3421 struct is_proxy_type_list : std::false_type {};
3422
3423 template <typename... Ts>
3424 struct is_proxy_type_list<ProxyTypeList<Ts...>> : std::true_type {};
3425
3426 // Generator which conditionally creates type lists.
3427 // It recognizes if a requested type list should be created
3428 // and prevents creating a new type list nested within another one.
3429 template <typename T>
3430 struct GenerateTypeList {
3431 private:
3432 using proxy = typename std::conditional<is_proxy_type_list<T>::value, T,
3433 ProxyTypeList<T>>::type;
3434
3435 public:
3436 using type = typename proxy::type;
3437 };
3438
3439 } // namespace internal
3440
3441 template <typename... Ts>
3442 using Types = internal::ProxyTypeList<Ts...>;
3443
3444 } // namespace testing
3445
3446 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
3447
3448 // Due to C++ preprocessor weirdness, we need double indirection to
3449 // concatenate two tokens when one of them is __LINE__. Writing
3450 //
3451 // foo ## __LINE__
3452 //
3453 // will result in the token foo__LINE__, instead of foo followed by
3454 // the current line number. For more details, see
3455 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
3456 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
3457 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
3458
3459 // Stringifies its argument.
3460 // Work around a bug in visual studio which doesn't accept code like this:
3461 //
3462 // #define GTEST_STRINGIFY_(name) #name
3463 // #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
3464 // MACRO(, x, y)
3465 //
3466 // Complaining about the argument to GTEST_STRINGIFY_ being empty.
3467 // This is allowed by the spec.
3468 #define GTEST_STRINGIFY_HELPER_(name, ...) #name
3469 #define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
3470
3471 namespace proto2 {
3472 class MessageLite;
3473 }
3474
3475 namespace testing {
3476
3477 // Forward declarations.
3478
3479 class AssertionResult; // Result of an assertion.
3480 class Message; // Represents a failure message.
3481 class Test; // Represents a test.
3482 class TestInfo; // Information about a test.
3483 class TestPartResult; // Result of a test part.
3484 class UnitTest; // A collection of test suites.
3485
3486 template <typename T>
3487 ::std::string PrintToString(const T& value);
3488
3489 namespace internal {
3490
3491 struct TraceInfo; // Information about a trace point.
3492 class TestInfoImpl; // Opaque implementation of TestInfo
3493 class UnitTestImpl; // Opaque implementation of UnitTest
3494
3495 // The text used in failure messages to indicate the start of the
3496 // stack trace.
3497 GTEST_API_ extern const char kStackTraceMarker[];
3498
3499 // An IgnoredValue object can be implicitly constructed from ANY value.
3500 class IgnoredValue {
3501 struct Sink {};
3502 public:
3503 // This constructor template allows any value to be implicitly
3504 // converted to IgnoredValue. The object has no data member and
3505 // doesn't try to remember anything about the argument. We
3506 // deliberately omit the 'explicit' keyword in order to allow the
3507 // conversion to be implicit.
3508 // Disable the conversion if T already has a magical conversion operator.
3509 // Otherwise we get ambiguity.
3510 template <typename T,
3511 typename std::enable_if<!std::is_convertible<T, Sink>::value,
3512 int>::type = 0>
3513 IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
3514 };
3515
3516 // Appends the user-supplied message to the Google-Test-generated message.
3517 GTEST_API_ std::string AppendUserMessage(
3518 const std::string& gtest_msg, const Message& user_msg);
3519
3520 #if GTEST_HAS_EXCEPTIONS
3521
3522 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
3523 /* an exported class was derived from a class that was not exported */)
3524
3525 // This exception is thrown by (and only by) a failed Google Test
3526 // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
3527 // are enabled). We derive it from std::runtime_error, which is for
3528 // errors presumably detectable only at run time. Since
3529 // std::runtime_error inherits from std::exception, many testing
3530 // frameworks know how to extract and print the message inside it.
3531 class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
3532 public:
3533 explicit GoogleTestFailureException(const TestPartResult& failure);
3534 };
3535
3536 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
3537
3538 #endif // GTEST_HAS_EXCEPTIONS
3539
3540 namespace edit_distance {
3541 // Returns the optimal edits to go from 'left' to 'right'.
3542 // All edits cost the same, with replace having lower priority than
3543 // add/remove.
3544 // Simple implementation of the Wagner-Fischer algorithm.
3545 // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
3546 enum EditType { kMatch, kAdd, kRemove, kReplace };
3547 GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
3548 const std::vector<size_t>& left, const std::vector<size_t>& right);
3549
3550 // Same as above, but the input is represented as strings.
3551 GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
3552 const std::vector<std::string>& left,
3553 const std::vector<std::string>& right);
3554
3555 // Create a diff of the input strings in Unified diff format.
3556 GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
3557 const std::vector<std::string>& right,
3558 size_t context = 2);
3559
3560 } // namespace edit_distance
3561
3562 // Calculate the diff between 'left' and 'right' and return it in unified diff
3563 // format.
3564 // If not null, stores in 'total_line_count' the total number of lines found
3565 // in left + right.
3566 GTEST_API_ std::string DiffStrings(const std::string& left,
3567 const std::string& right,
3568 size_t* total_line_count);
3569
3570 // Constructs and returns the message for an equality assertion
3571 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
3572 //
3573 // The first four parameters are the expressions used in the assertion
3574 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
3575 // where foo is 5 and bar is 6, we have:
3576 //
3577 // expected_expression: "foo"
3578 // actual_expression: "bar"
3579 // expected_value: "5"
3580 // actual_value: "6"
3581 //
3582 // The ignoring_case parameter is true if and only if the assertion is a
3583 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
3584 // be inserted into the message.
3585 GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
3586 const char* actual_expression,
3587 const std::string& expected_value,
3588 const std::string& actual_value,
3589 bool ignoring_case);
3590
3591 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
3592 GTEST_API_ std::string GetBoolAssertionFailureMessage(
3593 const AssertionResult& assertion_result,
3594 const char* expression_text,
3595 const char* actual_predicate_value,
3596 const char* expected_predicate_value);
3597
3598 // This template class represents an IEEE floating-point number
3599 // (either single-precision or double-precision, depending on the
3600 // template parameters).
3601 //
3602 // The purpose of this class is to do more sophisticated number
3603 // comparison. (Due to round-off error, etc, it's very unlikely that
3604 // two floating-points will be equal exactly. Hence a naive
3605 // comparison by the == operation often doesn't work.)
3606 //
3607 // Format of IEEE floating-point:
3608 //
3609 // The most-significant bit being the leftmost, an IEEE
3610 // floating-point looks like
3611 //
3612 // sign_bit exponent_bits fraction_bits
3613 //
3614 // Here, sign_bit is a single bit that designates the sign of the
3615 // number.
3616 //
3617 // For float, there are 8 exponent bits and 23 fraction bits.
3618 //
3619 // For double, there are 11 exponent bits and 52 fraction bits.
3620 //
3621 // More details can be found at
3622 // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
3623 //
3624 // Template parameter:
3625 //
3626 // RawType: the raw floating-point type (either float or double)
3627 template <typename RawType>
3628 class FloatingPoint {
3629 public:
3630 // Defines the unsigned integer type that has the same size as the
3631 // floating point number.
3632 typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
3633
3634 // Constants.
3635
3636 // # of bits in a number.
3637 static const size_t kBitCount = 8*sizeof(RawType);
3638
3639 // # of fraction bits in a number.
3640 static const size_t kFractionBitCount =
3641 std::numeric_limits<RawType>::digits - 1;
3642
3643 // # of exponent bits in a number.
3644 static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
3645
3646 // The mask for the sign bit.
3647 static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
3648
3649 // The mask for the fraction bits.
3650 static const Bits kFractionBitMask =
3651 ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
3652
3653 // The mask for the exponent bits.
3654 static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
3655
3656 // How many ULP's (Units in the Last Place) we want to tolerate when
3657 // comparing two numbers. The larger the value, the more error we
3658 // allow. A 0 value means that two numbers must be exactly the same
3659 // to be considered equal.
3660 //
3661 // The maximum error of a single floating-point operation is 0.5
3662 // units in the last place. On Intel CPU's, all floating-point
3663 // calculations are done with 80-bit precision, while double has 64
3664 // bits. Therefore, 4 should be enough for ordinary use.
3665 //
3666 // See the following article for more details on ULP:
3667 // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
3668 static const uint32_t kMaxUlps = 4;
3669
3670 // Constructs a FloatingPoint from a raw floating-point number.
3671 //
3672 // On an Intel CPU, passing a non-normalized NAN (Not a Number)
3673 // around may change its bits, although the new value is guaranteed
3674 // to be also a NAN. Therefore, don't expect this constructor to
3675 // preserve the bits in x when x is a NAN.
3676 explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
3677
3678 // Static methods
3679
3680 // Reinterprets a bit pattern as a floating-point number.
3681 //
3682 // This function is needed to test the AlmostEquals() method.
3683 static RawType ReinterpretBits(const Bits bits) {
3684 FloatingPoint fp(0);
3685 fp.u_.bits_ = bits;
3686 return fp.u_.value_;
3687 }
3688
3689 // Returns the floating-point number that represent positive infinity.
3690 static RawType Infinity() {
3691 return ReinterpretBits(kExponentBitMask);
3692 }
3693
3694 // Returns the maximum representable finite floating-point number.
3695 static RawType Max();
3696
3697 // Non-static methods
3698
3699 // Returns the bits that represents this number.
3700 const Bits &bits() const { return u_.bits_; }
3701
3702 // Returns the exponent bits of this number.
3703 Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
3704
3705 // Returns the fraction bits of this number.
3706 Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
3707
3708 // Returns the sign bit of this number.
3709 Bits sign_bit() const { return kSignBitMask & u_.bits_; }
3710
3711 // Returns true if and only if this is NAN (not a number).
3712 bool is_nan() const {
3713 // It's a NAN if the exponent bits are all ones and the fraction
3714 // bits are not entirely zeros.
3715 return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
3716 }
3717
3718 // Returns true if and only if this number is at most kMaxUlps ULP's away
3719 // from rhs. In particular, this function:
3720 //
3721 // - returns false if either number is (or both are) NAN.
3722 // - treats really large numbers as almost equal to infinity.
3723 // - thinks +0.0 and -0.0 are 0 DLP's apart.
3724 bool AlmostEquals(const FloatingPoint& rhs) const {
3725 // The IEEE standard says that any comparison operation involving
3726 // a NAN must return false.
3727 if (is_nan() || rhs.is_nan()) return false;
3728
3729 return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
3730 <= kMaxUlps;
3731 }
3732
3733 private:
3734 // The data type used to store the actual floating-point number.
3735 union FloatingPointUnion {
3736 RawType value_; // The raw floating-point number.
3737 Bits bits_; // The bits that represent the number.
3738 };
3739
3740 // Converts an integer from the sign-and-magnitude representation to
3741 // the biased representation. More precisely, let N be 2 to the
3742 // power of (kBitCount - 1), an integer x is represented by the
3743 // unsigned number x + N.
3744 //
3745 // For instance,
3746 //
3747 // -N + 1 (the most negative number representable using
3748 // sign-and-magnitude) is represented by 1;
3749 // 0 is represented by N; and
3750 // N - 1 (the biggest number representable using
3751 // sign-and-magnitude) is represented by 2N - 1.
3752 //
3753 // Read http://en.wikipedia.org/wiki/Signed_number_representations
3754 // for more details on signed number representations.
3755 static Bits SignAndMagnitudeToBiased(const Bits &sam) {
3756 if (kSignBitMask & sam) {
3757 // sam represents a negative number.
3758 return ~sam + 1;
3759 } else {
3760 // sam represents a positive number.
3761 return kSignBitMask | sam;
3762 }
3763 }
3764
3765 // Given two numbers in the sign-and-magnitude representation,
3766 // returns the distance between them as an unsigned number.
3767 static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
3768 const Bits &sam2) {
3769 const Bits biased1 = SignAndMagnitudeToBiased(sam1);
3770 const Bits biased2 = SignAndMagnitudeToBiased(sam2);
3771 return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
3772 }
3773
3774 FloatingPointUnion u_;
3775 };
3776
3777 // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
3778 // macro defined by <windows.h>.
3779 template <>
3780 inline float FloatingPoint<float>::Max() { return FLT_MAX; }
3781 template <>
3782 inline double FloatingPoint<double>::Max() { return DBL_MAX; }
3783
3784 // Typedefs the instances of the FloatingPoint template class that we
3785 // care to use.
3786 typedef FloatingPoint<float> Float;
3787 typedef FloatingPoint<double> Double;
3788
3789 // In order to catch the mistake of putting tests that use different
3790 // test fixture classes in the same test suite, we need to assign
3791 // unique IDs to fixture classes and compare them. The TypeId type is
3792 // used to hold such IDs. The user should treat TypeId as an opaque
3793 // type: the only operation allowed on TypeId values is to compare
3794 // them for equality using the == operator.
3795 typedef const void* TypeId;
3796
3797 template <typename T>
3798 class TypeIdHelper {
3799 public:
3800 // dummy_ must not have a const type. Otherwise an overly eager
3801 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
3802 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
3803 static bool dummy_;
3804 };
3805
3806 template <typename T>
3807 bool TypeIdHelper<T>::dummy_ = false;
3808
3809 // GetTypeId<T>() returns the ID of type T. Different values will be
3810 // returned for different types. Calling the function twice with the
3811 // same type argument is guaranteed to return the same ID.
3812 template <typename T>
3813 TypeId GetTypeId() {
3814 // The compiler is required to allocate a different
3815 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
3816 // the template. Therefore, the address of dummy_ is guaranteed to
3817 // be unique.
3818 return &(TypeIdHelper<T>::dummy_);
3819 }
3820
3821 // Returns the type ID of ::testing::Test. Always call this instead
3822 // of GetTypeId< ::testing::Test>() to get the type ID of
3823 // ::testing::Test, as the latter may give the wrong result due to a
3824 // suspected linker bug when compiling Google Test as a Mac OS X
3825 // framework.
3826 GTEST_API_ TypeId GetTestTypeId();
3827
3828 // Defines the abstract factory interface that creates instances
3829 // of a Test object.
3830 class TestFactoryBase {
3831 public:
3832 virtual ~TestFactoryBase() {}
3833
3834 // Creates a test instance to run. The instance is both created and destroyed
3835 // within TestInfoImpl::Run()
3836 virtual Test* CreateTest() = 0;
3837
3838 protected:
3839 TestFactoryBase() {}
3840
3841 private:
3842 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
3843 };
3844
3845 // This class provides implementation of TeastFactoryBase interface.
3846 // It is used in TEST and TEST_F macros.
3847 template <class TestClass>
3848 class TestFactoryImpl : public TestFactoryBase {
3849 public:
3850 Test* CreateTest() override { return new TestClass; }
3851 };
3852
3853 #if GTEST_OS_WINDOWS
3854
3855 // Predicate-formatters for implementing the HRESULT checking macros
3856 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
3857 // We pass a long instead of HRESULT to avoid causing an
3858 // include dependency for the HRESULT type.
3859 GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
3860 long hr); // NOLINT
3861 GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
3862 long hr); // NOLINT
3863
3864 #endif // GTEST_OS_WINDOWS
3865
3866 // Types of SetUpTestSuite() and TearDownTestSuite() functions.
3867 using SetUpTestSuiteFunc = void (*)();
3868 using TearDownTestSuiteFunc = void (*)();
3869
3870 struct CodeLocation {
3871 CodeLocation(const std::string& a_file, int a_line)
3872 : file(a_file), line(a_line) {}
3873
3874 std::string file;
3875 int line;
3876 };
3877
3878 // Helper to identify which setup function for TestCase / TestSuite to call.
3879 // Only one function is allowed, either TestCase or TestSute but not both.
3880
3881 // Utility functions to help SuiteApiResolver
3882 using SetUpTearDownSuiteFuncType = void (*)();
3883
3884 inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
3885 SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {
3886 return a == def ? nullptr : a;
3887 }
3888
3889 template <typename T>
3890 // Note that SuiteApiResolver inherits from T because
3891 // SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
3892 // SuiteApiResolver can access them.
3893 struct SuiteApiResolver : T {
3894 // testing::Test is only forward declared at this point. So we make it a
3895 // dependend class for the compiler to be OK with it.
3896 using Test =
3897 typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
3898
3899 static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
3900 int line_num) {
3901 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3902 SetUpTearDownSuiteFuncType test_case_fp =
3903 GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
3904 SetUpTearDownSuiteFuncType test_suite_fp =
3905 GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);
3906
3907 GTEST_CHECK_(!test_case_fp || !test_suite_fp)
3908 << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
3909 "make sure there is only one present at "
3910 << filename << ":" << line_num;
3911
3912 return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
3913 #else
3914 (void)(filename);
3915 (void)(line_num);
3916 return &T::SetUpTestSuite;
3917 #endif
3918 }
3919
3920 static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
3921 int line_num) {
3922 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3923 SetUpTearDownSuiteFuncType test_case_fp =
3924 GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
3925 SetUpTearDownSuiteFuncType test_suite_fp =
3926 GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);
3927
3928 GTEST_CHECK_(!test_case_fp || !test_suite_fp)
3929 << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
3930 " please make sure there is only one present at"
3931 << filename << ":" << line_num;
3932
3933 return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
3934 #else
3935 (void)(filename);
3936 (void)(line_num);
3937 return &T::TearDownTestSuite;
3938 #endif
3939 }
3940 };
3941
3942 // Creates a new TestInfo object and registers it with Google Test;
3943 // returns the created object.
3944 //
3945 // Arguments:
3946 //
3947 // test_suite_name: name of the test suite
3948 // name: name of the test
3949 // type_param: the name of the test's type parameter, or NULL if
3950 // this is not a typed or a type-parameterized test.
3951 // value_param: text representation of the test's value parameter,
3952 // or NULL if this is not a type-parameterized test.
3953 // code_location: code location where the test is defined
3954 // fixture_class_id: ID of the test fixture class
3955 // set_up_tc: pointer to the function that sets up the test suite
3956 // tear_down_tc: pointer to the function that tears down the test suite
3957 // factory: pointer to the factory that creates a test object.
3958 // The newly created TestInfo instance will assume
3959 // ownership of the factory object.
3960 GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
3961 const char* test_suite_name, const char* name, const char* type_param,
3962 const char* value_param, CodeLocation code_location,
3963 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
3964 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
3965
3966 // If *pstr starts with the given prefix, modifies *pstr to be right
3967 // past the prefix and returns true; otherwise leaves *pstr unchanged
3968 // and returns false. None of pstr, *pstr, and prefix can be NULL.
3969 GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
3970
3971 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
3972 /* class A needs to have dll-interface to be used by clients of class B */)
3973
3974 // State of the definition of a type-parameterized test suite.
3975 class GTEST_API_ TypedTestSuitePState {
3976 public:
3977 TypedTestSuitePState() : registered_(false) {}
3978
3979 // Adds the given test name to defined_test_names_ and return true
3980 // if the test suite hasn't been registered; otherwise aborts the
3981 // program.
3982 bool AddTestName(const char* file, int line, const char* case_name,
3983 const char* test_name) {
3984 if (registered_) {
3985 fprintf(stderr,
3986 "%s Test %s must be defined before "
3987 "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
3988 FormatFileLocation(file, line).c_str(), test_name, case_name);
3989 fflush(stderr);
3990 posix::Abort();
3991 }
3992 registered_tests_.insert(
3993 ::std::make_pair(test_name, CodeLocation(file, line)));
3994 return true;
3995 }
3996
3997 bool TestExists(const std::string& test_name) const {
3998 return registered_tests_.count(test_name) > 0;
3999 }
4000
4001 const CodeLocation& GetCodeLocation(const std::string& test_name) const {
4002 RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
4003 GTEST_CHECK_(it != registered_tests_.end());
4004 return it->second;
4005 }
4006
4007 // Verifies that registered_tests match the test names in
4008 // defined_test_names_; returns registered_tests if successful, or
4009 // aborts the program otherwise.
4010 const char* VerifyRegisteredTestNames(const char* test_suite_name,
4011 const char* file, int line,
4012 const char* registered_tests);
4013
4014 private:
4015 typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
4016
4017 bool registered_;
4018 RegisteredTestsMap registered_tests_;
4019 };
4020
4021 // Legacy API is deprecated but still available
4022 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4023 using TypedTestCasePState = TypedTestSuitePState;
4024 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4025
4026 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
4027
4028 // Skips to the first non-space char after the first comma in 'str';
4029 // returns NULL if no comma is found in 'str'.
4030 inline const char* SkipComma(const char* str) {
4031 const char* comma = strchr(str, ',');
4032 if (comma == nullptr) {
4033 return nullptr;
4034 }
4035 while (IsSpace(*(++comma))) {}
4036 return comma;
4037 }
4038
4039 // Returns the prefix of 'str' before the first comma in it; returns
4040 // the entire string if it contains no comma.
4041 inline std::string GetPrefixUntilComma(const char* str) {
4042 const char* comma = strchr(str, ',');
4043 return comma == nullptr ? str : std::string(str, comma);
4044 }
4045
4046 // Splits a given string on a given delimiter, populating a given
4047 // vector with the fields.
4048 void SplitString(const ::std::string& str, char delimiter,
4049 ::std::vector< ::std::string>* dest);
4050
4051 // The default argument to the template below for the case when the user does
4052 // not provide a name generator.
4053 struct DefaultNameGenerator {
4054 template <typename T>
4055 static std::string GetName(int i) {
4056 return StreamableToString(i);
4057 }
4058 };
4059
4060 template <typename Provided = DefaultNameGenerator>
4061 struct NameGeneratorSelector {
4062 typedef Provided type;
4063 };
4064
4065 template <typename NameGenerator>
4066 void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}
4067
4068 template <typename NameGenerator, typename Types>
4069 void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
4070 result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
4071 GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
4072 i + 1);
4073 }
4074
4075 template <typename NameGenerator, typename Types>
4076 std::vector<std::string> GenerateNames() {
4077 std::vector<std::string> result;
4078 GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
4079 return result;
4080 }
4081
4082 // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
4083 // registers a list of type-parameterized tests with Google Test. The
4084 // return value is insignificant - we just need to return something
4085 // such that we can call this function in a namespace scope.
4086 //
4087 // Implementation note: The GTEST_TEMPLATE_ macro declares a template
4088 // template parameter. It's defined in gtest-type-util.h.
4089 template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
4090 class TypeParameterizedTest {
4091 public:
4092 // 'index' is the index of the test in the type list 'Types'
4093 // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
4094 // Types). Valid values for 'index' are [0, N - 1] where N is the
4095 // length of Types.
4096 static bool Register(const char* prefix, const CodeLocation& code_location,
4097 const char* case_name, const char* test_names, int index,
4098 const std::vector<std::string>& type_names =
4099 GenerateNames<DefaultNameGenerator, Types>()) {
4100 typedef typename Types::Head Type;
4101 typedef Fixture<Type> FixtureClass;
4102 typedef typename GTEST_BIND_(TestSel, Type) TestClass;
4103
4104 // First, registers the first type-parameterized test in the type
4105 // list.
4106 MakeAndRegisterTestInfo(
4107 (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
4108 "/" + type_names[static_cast<size_t>(index)])
4109 .c_str(),
4110 StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
4111 GetTypeName<Type>().c_str(),
4112 nullptr, // No value parameter.
4113 code_location, GetTypeId<FixtureClass>(),
4114 SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(
4115 code_location.file.c_str(), code_location.line),
4116 SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(
4117 code_location.file.c_str(), code_location.line),
4118 new TestFactoryImpl<TestClass>);
4119
4120 // Next, recurses (at compile time) with the tail of the type list.
4121 return TypeParameterizedTest<Fixture, TestSel,
4122 typename Types::Tail>::Register(prefix,
4123 code_location,
4124 case_name,
4125 test_names,
4126 index + 1,
4127 type_names);
4128 }
4129 };
4130
4131 // The base case for the compile time recursion.
4132 template <GTEST_TEMPLATE_ Fixture, class TestSel>
4133 class TypeParameterizedTest<Fixture, TestSel, internal::None> {
4134 public:
4135 static bool Register(const char* /*prefix*/, const CodeLocation&,
4136 const char* /*case_name*/, const char* /*test_names*/,
4137 int /*index*/,
4138 const std::vector<std::string>& =
4139 std::vector<std::string>() /*type_names*/) {
4140 return true;
4141 }
4142 };
4143
4144 GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
4145 CodeLocation code_location);
4146 GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
4147 const char* case_name);
4148
4149 // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
4150 // registers *all combinations* of 'Tests' and 'Types' with Google
4151 // Test. The return value is insignificant - we just need to return
4152 // something such that we can call this function in a namespace scope.
4153 template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
4154 class TypeParameterizedTestSuite {
4155 public:
4156 static bool Register(const char* prefix, CodeLocation code_location,
4157 const TypedTestSuitePState* state, const char* case_name,
4158 const char* test_names,
4159 const std::vector<std::string>& type_names =
4160 GenerateNames<DefaultNameGenerator, Types>()) {
4161 RegisterTypeParameterizedTestSuiteInstantiation(case_name);
4162 std::string test_name = StripTrailingSpaces(
4163 GetPrefixUntilComma(test_names));
4164 if (!state->TestExists(test_name)) {
4165 fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
4166 case_name, test_name.c_str(),
4167 FormatFileLocation(code_location.file.c_str(),
4168 code_location.line).c_str());
4169 fflush(stderr);
4170 posix::Abort();
4171 }
4172 const CodeLocation& test_location = state->GetCodeLocation(test_name);
4173
4174 typedef typename Tests::Head Head;
4175
4176 // First, register the first test in 'Test' for each type in 'Types'.
4177 TypeParameterizedTest<Fixture, Head, Types>::Register(
4178 prefix, test_location, case_name, test_names, 0, type_names);
4179
4180 // Next, recurses (at compile time) with the tail of the test list.
4181 return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
4182 Types>::Register(prefix, code_location,
4183 state, case_name,
4184 SkipComma(test_names),
4185 type_names);
4186 }
4187 };
4188
4189 // The base case for the compile time recursion.
4190 template <GTEST_TEMPLATE_ Fixture, typename Types>
4191 class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
4192 public:
4193 static bool Register(const char* /*prefix*/, const CodeLocation&,
4194 const TypedTestSuitePState* /*state*/,
4195 const char* /*case_name*/, const char* /*test_names*/,
4196 const std::vector<std::string>& =
4197 std::vector<std::string>() /*type_names*/) {
4198 return true;
4199 }
4200 };
4201
4202 // Returns the current OS stack trace as an std::string.
4203 //
4204 // The maximum number of stack frames to be included is specified by
4205 // the gtest_stack_trace_depth flag. The skip_count parameter
4206 // specifies the number of top frames to be skipped, which doesn't
4207 // count against the number of frames to be included.
4208 //
4209 // For example, if Foo() calls Bar(), which in turn calls
4210 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4211 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4212 GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
4213 UnitTest* unit_test, int skip_count);
4214
4215 // Helpers for suppressing warnings on unreachable code or constant
4216 // condition.
4217
4218 // Always returns true.
4219 GTEST_API_ bool AlwaysTrue();
4220
4221 // Always returns false.
4222 inline bool AlwaysFalse() { return !AlwaysTrue(); }
4223
4224 // Helper for suppressing false warning from Clang on a const char*
4225 // variable declared in a conditional expression always being NULL in
4226 // the else branch.
4227 struct GTEST_API_ ConstCharPtr {
4228 ConstCharPtr(const char* str) : value(str) {}
4229 operator bool() const { return true; }
4230 const char* value;
4231 };
4232
4233 // Helper for declaring std::string within 'if' statement
4234 // in pre C++17 build environment.
4235 struct TrueWithString {
4236 TrueWithString() = default;
4237 explicit TrueWithString(const char* str) : value(str) {}
4238 explicit TrueWithString(const std::string& str) : value(str) {}
4239 explicit operator bool() const { return true; }
4240 std::string value;
4241 };
4242
4243 // A simple Linear Congruential Generator for generating random
4244 // numbers with a uniform distribution. Unlike rand() and srand(), it
4245 // doesn't use global state (and therefore can't interfere with user
4246 // code). Unlike rand_r(), it's portable. An LCG isn't very random,
4247 // but it's good enough for our purposes.
4248 class GTEST_API_ Random {
4249 public:
4250 static const uint32_t kMaxRange = 1u << 31;
4251
4252 explicit Random(uint32_t seed) : state_(seed) {}
4253
4254 void Reseed(uint32_t seed) { state_ = seed; }
4255
4256 // Generates a random number from [0, range). Crashes if 'range' is
4257 // 0 or greater than kMaxRange.
4258 uint32_t Generate(uint32_t range);
4259
4260 private:
4261 uint32_t state_;
4262 GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
4263 };
4264
4265 // Turns const U&, U&, const U, and U all into U.
4266 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
4267 typename std::remove_const<typename std::remove_reference<T>::type>::type
4268
4269 // HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
4270 // that's true if and only if T has methods DebugString() and ShortDebugString()
4271 // that return std::string.
4272 template <typename T>
4273 class HasDebugStringAndShortDebugString {
4274 private:
4275 template <typename C>
4276 static auto CheckDebugString(C*) -> typename std::is_same<
4277 std::string, decltype(std::declval<const C>().DebugString())>::type;
4278 template <typename>
4279 static std::false_type CheckDebugString(...);
4280
4281 template <typename C>
4282 static auto CheckShortDebugString(C*) -> typename std::is_same<
4283 std::string, decltype(std::declval<const C>().ShortDebugString())>::type;
4284 template <typename>
4285 static std::false_type CheckShortDebugString(...);
4286
4287 using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));
4288 using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));
4289
4290 public:
4291 static constexpr bool value =
4292 HasDebugStringType::value && HasShortDebugStringType::value;
4293 };
4294
4295 template <typename T>
4296 constexpr bool HasDebugStringAndShortDebugString<T>::value;
4297
4298 // When the compiler sees expression IsContainerTest<C>(0), if C is an
4299 // STL-style container class, the first overload of IsContainerTest
4300 // will be viable (since both C::iterator* and C::const_iterator* are
4301 // valid types and NULL can be implicitly converted to them). It will
4302 // be picked over the second overload as 'int' is a perfect match for
4303 // the type of argument 0. If C::iterator or C::const_iterator is not
4304 // a valid type, the first overload is not viable, and the second
4305 // overload will be picked. Therefore, we can determine whether C is
4306 // a container class by checking the type of IsContainerTest<C>(0).
4307 // The value of the expression is insignificant.
4308 //
4309 // In C++11 mode we check the existence of a const_iterator and that an
4310 // iterator is properly implemented for the container.
4311 //
4312 // For pre-C++11 that we look for both C::iterator and C::const_iterator.
4313 // The reason is that C++ injects the name of a class as a member of the
4314 // class itself (e.g. you can refer to class iterator as either
4315 // 'iterator' or 'iterator::iterator'). If we look for C::iterator
4316 // only, for example, we would mistakenly think that a class named
4317 // iterator is an STL container.
4318 //
4319 // Also note that the simpler approach of overloading
4320 // IsContainerTest(typename C::const_iterator*) and
4321 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
4322 typedef int IsContainer;
4323 template <class C,
4324 class Iterator = decltype(::std::declval<const C&>().begin()),
4325 class = decltype(::std::declval<const C&>().end()),
4326 class = decltype(++::std::declval<Iterator&>()),
4327 class = decltype(*::std::declval<Iterator>()),
4328 class = typename C::const_iterator>
4329 IsContainer IsContainerTest(int /* dummy */) {
4330 return 0;
4331 }
4332
4333 typedef char IsNotContainer;
4334 template <class C>
4335 IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
4336
4337 // Trait to detect whether a type T is a hash table.
4338 // The heuristic used is that the type contains an inner type `hasher` and does
4339 // not contain an inner type `reverse_iterator`.
4340 // If the container is iterable in reverse, then order might actually matter.
4341 template <typename T>
4342 struct IsHashTable {
4343 private:
4344 template <typename U>
4345 static char test(typename U::hasher*, typename U::reverse_iterator*);
4346 template <typename U>
4347 static int test(typename U::hasher*, ...);
4348 template <typename U>
4349 static char test(...);
4350
4351 public:
4352 static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);
4353 };
4354
4355 template <typename T>
4356 const bool IsHashTable<T>::value;
4357
4358 template <typename C,
4359 bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>
4360 struct IsRecursiveContainerImpl;
4361
4362 template <typename C>
4363 struct IsRecursiveContainerImpl<C, false> : public std::false_type {};
4364
4365 // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
4366 // obey the same inconsistencies as the IsContainerTest, namely check if
4367 // something is a container is relying on only const_iterator in C++11 and
4368 // is relying on both const_iterator and iterator otherwise
4369 template <typename C>
4370 struct IsRecursiveContainerImpl<C, true> {
4371 using value_type = decltype(*std::declval<typename C::const_iterator>());
4372 using type =
4373 std::is_same<typename std::remove_const<
4374 typename std::remove_reference<value_type>::type>::type,
4375 C>;
4376 };
4377
4378 // IsRecursiveContainer<Type> is a unary compile-time predicate that
4379 // evaluates whether C is a recursive container type. A recursive container
4380 // type is a container type whose value_type is equal to the container type
4381 // itself. An example for a recursive container type is
4382 // boost::filesystem::path, whose iterator has a value_type that is equal to
4383 // boost::filesystem::path.
4384 template <typename C>
4385 struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};
4386
4387 // Utilities for native arrays.
4388
4389 // ArrayEq() compares two k-dimensional native arrays using the
4390 // elements' operator==, where k can be any integer >= 0. When k is
4391 // 0, ArrayEq() degenerates into comparing a single pair of values.
4392
4393 template <typename T, typename U>
4394 bool ArrayEq(const T* lhs, size_t size, const U* rhs);
4395
4396 // This generic version is used when k is 0.
4397 template <typename T, typename U>
4398 inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
4399
4400 // This overload is used when k >= 1.
4401 template <typename T, typename U, size_t N>
4402 inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
4403 return internal::ArrayEq(lhs, N, rhs);
4404 }
4405
4406 // This helper reduces code bloat. If we instead put its logic inside
4407 // the previous ArrayEq() function, arrays with different sizes would
4408 // lead to different copies of the template code.
4409 template <typename T, typename U>
4410 bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
4411 for (size_t i = 0; i != size; i++) {
4412 if (!internal::ArrayEq(lhs[i], rhs[i]))
4413 return false;
4414 }
4415 return true;
4416 }
4417
4418 // Finds the first element in the iterator range [begin, end) that
4419 // equals elem. Element may be a native array type itself.
4420 template <typename Iter, typename Element>
4421 Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
4422 for (Iter it = begin; it != end; ++it) {
4423 if (internal::ArrayEq(*it, elem))
4424 return it;
4425 }
4426 return end;
4427 }
4428
4429 // CopyArray() copies a k-dimensional native array using the elements'
4430 // operator=, where k can be any integer >= 0. When k is 0,
4431 // CopyArray() degenerates into copying a single value.
4432
4433 template <typename T, typename U>
4434 void CopyArray(const T* from, size_t size, U* to);
4435
4436 // This generic version is used when k is 0.
4437 template <typename T, typename U>
4438 inline void CopyArray(const T& from, U* to) { *to = from; }
4439
4440 // This overload is used when k >= 1.
4441 template <typename T, typename U, size_t N>
4442 inline void CopyArray(const T(&from)[N], U(*to)[N]) {
4443 internal::CopyArray(from, N, *to);
4444 }
4445
4446 // This helper reduces code bloat. If we instead put its logic inside
4447 // the previous CopyArray() function, arrays with different sizes
4448 // would lead to different copies of the template code.
4449 template <typename T, typename U>
4450 void CopyArray(const T* from, size_t size, U* to) {
4451 for (size_t i = 0; i != size; i++) {
4452 internal::CopyArray(from[i], to + i);
4453 }
4454 }
4455
4456 // The relation between an NativeArray object (see below) and the
4457 // native array it represents.
4458 // We use 2 different structs to allow non-copyable types to be used, as long
4459 // as RelationToSourceReference() is passed.
4460 struct RelationToSourceReference {};
4461 struct RelationToSourceCopy {};
4462
4463 // Adapts a native array to a read-only STL-style container. Instead
4464 // of the complete STL container concept, this adaptor only implements
4465 // members useful for Google Mock's container matchers. New members
4466 // should be added as needed. To simplify the implementation, we only
4467 // support Element being a raw type (i.e. having no top-level const or
4468 // reference modifier). It's the client's responsibility to satisfy
4469 // this requirement. Element can be an array type itself (hence
4470 // multi-dimensional arrays are supported).
4471 template <typename Element>
4472 class NativeArray {
4473 public:
4474 // STL-style container typedefs.
4475 typedef Element value_type;
4476 typedef Element* iterator;
4477 typedef const Element* const_iterator;
4478
4479 // Constructs from a native array. References the source.
4480 NativeArray(const Element* array, size_t count, RelationToSourceReference) {
4481 InitRef(array, count);
4482 }
4483
4484 // Constructs from a native array. Copies the source.
4485 NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
4486 InitCopy(array, count);
4487 }
4488
4489 // Copy constructor.
4490 NativeArray(const NativeArray& rhs) {
4491 (this->*rhs.clone_)(rhs.array_, rhs.size_);
4492 }
4493
4494 ~NativeArray() {
4495 if (clone_ != &NativeArray::InitRef)
4496 delete[] array_;
4497 }
4498
4499 // STL-style container methods.
4500 size_t size() const { return size_; }
4501 const_iterator begin() const { return array_; }
4502 const_iterator end() const { return array_ + size_; }
4503 bool operator==(const NativeArray& rhs) const {
4504 return size() == rhs.size() &&
4505 ArrayEq(begin(), size(), rhs.begin());
4506 }
4507
4508 private:
4509 static_assert(!std::is_const<Element>::value, "Type must not be const");
4510 static_assert(!std::is_reference<Element>::value,
4511 "Type must not be a reference");
4512
4513 // Initializes this object with a copy of the input.
4514 void InitCopy(const Element* array, size_t a_size) {
4515 Element* const copy = new Element[a_size];
4516 CopyArray(array, a_size, copy);
4517 array_ = copy;
4518 size_ = a_size;
4519 clone_ = &NativeArray::InitCopy;
4520 }
4521
4522 // Initializes this object with a reference of the input.
4523 void InitRef(const Element* array, size_t a_size) {
4524 array_ = array;
4525 size_ = a_size;
4526 clone_ = &NativeArray::InitRef;
4527 }
4528
4529 const Element* array_;
4530 size_t size_;
4531 void (NativeArray::*clone_)(const Element*, size_t);
4532 };
4533
4534 // Backport of std::index_sequence.
4535 template <size_t... Is>
4536 struct IndexSequence {
4537 using type = IndexSequence;
4538 };
4539
4540 // Double the IndexSequence, and one if plus_one is true.
4541 template <bool plus_one, typename T, size_t sizeofT>
4542 struct DoubleSequence;
4543 template <size_t... I, size_t sizeofT>
4544 struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
4545 using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
4546 };
4547 template <size_t... I, size_t sizeofT>
4548 struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
4549 using type = IndexSequence<I..., (sizeofT + I)...>;
4550 };
4551
4552 // Backport of std::make_index_sequence.
4553 // It uses O(ln(N)) instantiation depth.
4554 template <size_t N>
4555 struct MakeIndexSequenceImpl
4556 : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,
4557 N / 2>::type {};
4558
4559 template <>
4560 struct MakeIndexSequenceImpl<0> : IndexSequence<> {};
4561
4562 template <size_t N>
4563 using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;
4564
4565 template <typename... T>
4566 using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;
4567
4568 template <size_t>
4569 struct Ignore {
4570 Ignore(...); // NOLINT
4571 };
4572
4573 template <typename>
4574 struct ElemFromListImpl;
4575 template <size_t... I>
4576 struct ElemFromListImpl<IndexSequence<I...>> {
4577 // We make Ignore a template to solve a problem with MSVC.
4578 // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but
4579 // MSVC doesn't understand how to deal with that pack expansion.
4580 // Use `0 * I` to have a single instantiation of Ignore.
4581 template <typename R>
4582 static R Apply(Ignore<0 * I>..., R (*)(), ...);
4583 };
4584
4585 template <size_t N, typename... T>
4586 struct ElemFromList {
4587 using type =
4588 decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply(
4589 static_cast<T (*)()>(nullptr)...));
4590 };
4591
4592 struct FlatTupleConstructTag {};
4593
4594 template <typename... T>
4595 class FlatTuple;
4596
4597 template <typename Derived, size_t I>
4598 struct FlatTupleElemBase;
4599
4600 template <typename... T, size_t I>
4601 struct FlatTupleElemBase<FlatTuple<T...>, I> {
4602 using value_type = typename ElemFromList<I, T...>::type;
4603 FlatTupleElemBase() = default;
4604 template <typename Arg>
4605 explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)
4606 : value(std::forward<Arg>(t)) {}
4607 value_type value;
4608 };
4609
4610 template <typename Derived, typename Idx>
4611 struct FlatTupleBase;
4612
4613 template <size_t... Idx, typename... T>
4614 struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
4615 : FlatTupleElemBase<FlatTuple<T...>, Idx>... {
4616 using Indices = IndexSequence<Idx...>;
4617 FlatTupleBase() = default;
4618 template <typename... Args>
4619 explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)
4620 : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},
4621 std::forward<Args>(args))... {}
4622
4623 template <size_t I>
4624 const typename ElemFromList<I, T...>::type& Get() const {
4625 return FlatTupleElemBase<FlatTuple<T...>, I>::value;
4626 }
4627
4628 template <size_t I>
4629 typename ElemFromList<I, T...>::type& Get() {
4630 return FlatTupleElemBase<FlatTuple<T...>, I>::value;
4631 }
4632
4633 template <typename F>
4634 auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
4635 return std::forward<F>(f)(Get<Idx>()...);
4636 }
4637
4638 template <typename F>
4639 auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
4640 return std::forward<F>(f)(Get<Idx>()...);
4641 }
4642 };
4643
4644 // Analog to std::tuple but with different tradeoffs.
4645 // This class minimizes the template instantiation depth, thus allowing more
4646 // elements than std::tuple would. std::tuple has been seen to require an
4647 // instantiation depth of more than 10x the number of elements in some
4648 // implementations.
4649 // FlatTuple and ElemFromList are not recursive and have a fixed depth
4650 // regardless of T...
4651 // MakeIndexSequence, on the other hand, it is recursive but with an
4652 // instantiation depth of O(ln(N)).
4653 template <typename... T>
4654 class FlatTuple
4655 : private FlatTupleBase<FlatTuple<T...>,
4656 typename MakeIndexSequence<sizeof...(T)>::type> {
4657 using Indices = typename FlatTupleBase<
4658 FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices;
4659
4660 public:
4661 FlatTuple() = default;
4662 template <typename... Args>
4663 explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)
4664 : FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}
4665
4666 using FlatTuple::FlatTupleBase::Apply;
4667 using FlatTuple::FlatTupleBase::Get;
4668 };
4669
4670 // Utility functions to be called with static_assert to induce deprecation
4671 // warnings.
4672 GTEST_INTERNAL_DEPRECATED(
4673 "INSTANTIATE_TEST_CASE_P is deprecated, please use "
4674 "INSTANTIATE_TEST_SUITE_P")
4675 constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
4676
4677 GTEST_INTERNAL_DEPRECATED(
4678 "TYPED_TEST_CASE_P is deprecated, please use "
4679 "TYPED_TEST_SUITE_P")
4680 constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
4681
4682 GTEST_INTERNAL_DEPRECATED(
4683 "TYPED_TEST_CASE is deprecated, please use "
4684 "TYPED_TEST_SUITE")
4685 constexpr bool TypedTestCaseIsDeprecated() { return true; }
4686
4687 GTEST_INTERNAL_DEPRECATED(
4688 "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
4689 "REGISTER_TYPED_TEST_SUITE_P")
4690 constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
4691
4692 GTEST_INTERNAL_DEPRECATED(
4693 "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
4694 "INSTANTIATE_TYPED_TEST_SUITE_P")
4695 constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
4696
4697 } // namespace internal
4698 } // namespace testing
4699
4700 namespace std {
4701 // Some standard library implementations use `struct tuple_size` and some use
4702 // `class tuple_size`. Clang warns about the mismatch.
4703 // https://reviews.llvm.org/D55466
4704 #ifdef __clang__
4705 #pragma clang diagnostic push
4706 #pragma clang diagnostic ignored "-Wmismatched-tags"
4707 #endif
4708 template <typename... Ts>
4709 struct tuple_size<testing::internal::FlatTuple<Ts...>>
4710 : std::integral_constant<size_t, sizeof...(Ts)> {};
4711 #ifdef __clang__
4712 #pragma clang diagnostic pop
4713 #endif
4714 } // namespace std
4715
4716 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
4717 ::testing::internal::AssertHelper(result_type, file, line, message) \
4718 = ::testing::Message()
4719
4720 #define GTEST_MESSAGE_(message, result_type) \
4721 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
4722
4723 #define GTEST_FATAL_FAILURE_(message) \
4724 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
4725
4726 #define GTEST_NONFATAL_FAILURE_(message) \
4727 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
4728
4729 #define GTEST_SUCCESS_(message) \
4730 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
4731
4732 #define GTEST_SKIP_(message) \
4733 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
4734
4735 // Suppress MSVC warning 4072 (unreachable code) for the code following
4736 // statement if it returns or throws (or doesn't return or throw in some
4737 // situations).
4738 // NOTE: The "else" is important to keep this expansion to prevent a top-level
4739 // "else" from attaching to our "if".
4740 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
4741 if (::testing::internal::AlwaysTrue()) { \
4742 statement; \
4743 } else /* NOLINT */ \
4744 static_assert(true, "") // User must have a semicolon after expansion.
4745
4746 #if GTEST_HAS_EXCEPTIONS
4747
4748 namespace testing {
4749 namespace internal {
4750
4751 class NeverThrown {
4752 public:
4753 const char* what() const noexcept {
4754 return "this exception should never be thrown";
4755 }
4756 };
4757
4758 } // namespace internal
4759 } // namespace testing
4760
4761 #if GTEST_HAS_RTTI
4762
4763 #define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
4764
4765 #else // GTEST_HAS_RTTI
4766
4767 #define GTEST_EXCEPTION_TYPE_(e) \
4768 std::string { "an std::exception-derived error" }
4769
4770 #endif // GTEST_HAS_RTTI
4771
4772 #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
4773 catch (typename std::conditional< \
4774 std::is_same<typename std::remove_cv<typename std::remove_reference< \
4775 expected_exception>::type>::type, \
4776 std::exception>::value, \
4777 const ::testing::internal::NeverThrown&, const std::exception&>::type \
4778 e) { \
4779 gtest_msg.value = "Expected: " #statement \
4780 " throws an exception of type " #expected_exception \
4781 ".\n Actual: it throws "; \
4782 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
4783 gtest_msg.value += " with description \""; \
4784 gtest_msg.value += e.what(); \
4785 gtest_msg.value += "\"."; \
4786 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4787 }
4788
4789 #else // GTEST_HAS_EXCEPTIONS
4790
4791 #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
4792
4793 #endif // GTEST_HAS_EXCEPTIONS
4794
4795 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
4796 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4797 if (::testing::internal::TrueWithString gtest_msg{}) { \
4798 bool gtest_caught_expected = false; \
4799 try { \
4800 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4801 } catch (expected_exception const&) { \
4802 gtest_caught_expected = true; \
4803 } \
4804 GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
4805 catch (...) { \
4806 gtest_msg.value = "Expected: " #statement \
4807 " throws an exception of type " #expected_exception \
4808 ".\n Actual: it throws a different type."; \
4809 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4810 } \
4811 if (!gtest_caught_expected) { \
4812 gtest_msg.value = "Expected: " #statement \
4813 " throws an exception of type " #expected_exception \
4814 ".\n Actual: it throws nothing."; \
4815 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
4816 } \
4817 } else /*NOLINT*/ \
4818 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
4819 : fail(gtest_msg.value.c_str())
4820
4821 #if GTEST_HAS_EXCEPTIONS
4822
4823 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
4824 catch (std::exception const& e) { \
4825 gtest_msg.value = "it throws "; \
4826 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
4827 gtest_msg.value += " with description \""; \
4828 gtest_msg.value += e.what(); \
4829 gtest_msg.value += "\"."; \
4830 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
4831 }
4832
4833 #else // GTEST_HAS_EXCEPTIONS
4834
4835 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()
4836
4837 #endif // GTEST_HAS_EXCEPTIONS
4838
4839 #define GTEST_TEST_NO_THROW_(statement, fail) \
4840 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4841 if (::testing::internal::TrueWithString gtest_msg{}) { \
4842 try { \
4843 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4844 } \
4845 GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
4846 catch (...) { \
4847 gtest_msg.value = "it throws."; \
4848 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
4849 } \
4850 } else \
4851 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
4852 fail(("Expected: " #statement " doesn't throw an exception.\n" \
4853 " Actual: " + gtest_msg.value).c_str())
4854
4855 #define GTEST_TEST_ANY_THROW_(statement, fail) \
4856 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4857 if (::testing::internal::AlwaysTrue()) { \
4858 bool gtest_caught_any = false; \
4859 try { \
4860 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4861 } \
4862 catch (...) { \
4863 gtest_caught_any = true; \
4864 } \
4865 if (!gtest_caught_any) { \
4866 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
4867 } \
4868 } else \
4869 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
4870 fail("Expected: " #statement " throws an exception.\n" \
4871 " Actual: it doesn't.")
4872
4873
4874 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
4875 // either a boolean expression or an AssertionResult. text is a textual
4876 // representation of expression as it was passed into the EXPECT_TRUE.
4877 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
4878 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4879 if (const ::testing::AssertionResult gtest_ar_ = \
4880 ::testing::AssertionResult(expression)) \
4881 ; \
4882 else \
4883 fail(::testing::internal::GetBoolAssertionFailureMessage(\
4884 gtest_ar_, text, #actual, #expected).c_str())
4885
4886 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
4887 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
4888 if (::testing::internal::AlwaysTrue()) { \
4889 ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
4890 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
4891 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
4892 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
4893 } \
4894 } else \
4895 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
4896 fail("Expected: " #statement " doesn't generate new fatal " \
4897 "failures in the current thread.\n" \
4898 " Actual: it does.")
4899
4900 // Expands to the name of the class that implements the given test.
4901 #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
4902 test_suite_name##_##test_name##_Test
4903
4904 // Helper macro for defining tests.
4905 #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
4906 static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \
4907 "test_suite_name must not be empty"); \
4908 static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \
4909 "test_name must not be empty"); \
4910 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
4911 : public parent_class { \
4912 public: \
4913 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
4914 ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
4915 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
4916 test_name)); \
4917 GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
4918 test_name)); \
4919 \
4920 private: \
4921 void TestBody() override; \
4922 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
4923 }; \
4924 \
4925 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
4926 test_name)::test_info_ = \
4927 ::testing::internal::MakeAndRegisterTestInfo( \
4928 #test_suite_name, #test_name, nullptr, nullptr, \
4929 ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
4930 ::testing::internal::SuiteApiResolver< \
4931 parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
4932 ::testing::internal::SuiteApiResolver< \
4933 parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
4934 new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
4935 test_suite_name, test_name)>); \
4936 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
4937
4938 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
4939 // Copyright 2005, Google Inc.
4940 // All rights reserved.
4941 //
4942 // Redistribution and use in source and binary forms, with or without
4943 // modification, are permitted provided that the following conditions are
4944 // met:
4945 //
4946 // * Redistributions of source code must retain the above copyright
4947 // notice, this list of conditions and the following disclaimer.
4948 // * Redistributions in binary form must reproduce the above
4949 // copyright notice, this list of conditions and the following disclaimer
4950 // in the documentation and/or other materials provided with the
4951 // distribution.
4952 // * Neither the name of Google Inc. nor the names of its
4953 // contributors may be used to endorse or promote products derived from
4954 // this software without specific prior written permission.
4955 //
4956 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4957 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
4958 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
4959 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
4960 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
4961 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
4962 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
4963 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
4964 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
4965 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
4966 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4967
4968 //
4969 // The Google C++ Testing and Mocking Framework (Google Test)
4970 //
4971 // This header file defines the public API for death tests. It is
4972 // #included by gtest.h so a user doesn't need to include this
4973 // directly.
4974 // GOOGLETEST_CM0001 DO NOT DELETE
4975
4976 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
4977 #define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
4978
4979 // Copyright 2005, Google Inc.
4980 // All rights reserved.
4981 //
4982 // Redistribution and use in source and binary forms, with or without
4983 // modification, are permitted provided that the following conditions are
4984 // met:
4985 //
4986 // * Redistributions of source code must retain the above copyright
4987 // notice, this list of conditions and the following disclaimer.
4988 // * Redistributions in binary form must reproduce the above
4989 // copyright notice, this list of conditions and the following disclaimer
4990 // in the documentation and/or other materials provided with the
4991 // distribution.
4992 // * Neither the name of Google Inc. nor the names of its
4993 // contributors may be used to endorse or promote products derived from
4994 // this software without specific prior written permission.
4995 //
4996 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4997 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
4998 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
4999 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5000 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5001 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5002 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5003 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5004 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5005 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5006 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5007 //
5008 // The Google C++ Testing and Mocking Framework (Google Test)
5009 //
5010 // This header file defines internal utilities needed for implementing
5011 // death tests. They are subject to change without notice.
5012 // GOOGLETEST_CM0001 DO NOT DELETE
5013
5014 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
5015 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
5016
5017 // Copyright 2007, Google Inc.
5018 // All rights reserved.
5019 //
5020 // Redistribution and use in source and binary forms, with or without
5021 // modification, are permitted provided that the following conditions are
5022 // met:
5023 //
5024 // * Redistributions of source code must retain the above copyright
5025 // notice, this list of conditions and the following disclaimer.
5026 // * Redistributions in binary form must reproduce the above
5027 // copyright notice, this list of conditions and the following disclaimer
5028 // in the documentation and/or other materials provided with the
5029 // distribution.
5030 // * Neither the name of Google Inc. nor the names of its
5031 // contributors may be used to endorse or promote products derived from
5032 // this software without specific prior written permission.
5033 //
5034 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5035 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5036 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5037 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5038 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5039 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5040 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5041 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5042 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5043 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5044 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5045
5046 // The Google C++ Testing and Mocking Framework (Google Test)
5047 //
5048 // This file implements just enough of the matcher interface to allow
5049 // EXPECT_DEATH and friends to accept a matcher argument.
5050
5051 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
5052 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
5053
5054 #include <atomic>
5055 #include <memory>
5056 #include <ostream>
5057 #include <string>
5058 #include <type_traits>
5059
5060 // Copyright 2007, Google Inc.
5061 // All rights reserved.
5062 //
5063 // Redistribution and use in source and binary forms, with or without
5064 // modification, are permitted provided that the following conditions are
5065 // met:
5066 //
5067 // * Redistributions of source code must retain the above copyright
5068 // notice, this list of conditions and the following disclaimer.
5069 // * Redistributions in binary form must reproduce the above
5070 // copyright notice, this list of conditions and the following disclaimer
5071 // in the documentation and/or other materials provided with the
5072 // distribution.
5073 // * Neither the name of Google Inc. nor the names of its
5074 // contributors may be used to endorse or promote products derived from
5075 // this software without specific prior written permission.
5076 //
5077 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5078 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5079 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5080 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5081 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5082 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5083 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5084 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5085 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5086 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5087 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5088
5089
5090 // Google Test - The Google C++ Testing and Mocking Framework
5091 //
5092 // This file implements a universal value printer that can print a
5093 // value of any type T:
5094 //
5095 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
5096 //
5097 // A user can teach this function how to print a class type T by
5098 // defining either operator<<() or PrintTo() in the namespace that
5099 // defines T. More specifically, the FIRST defined function in the
5100 // following list will be used (assuming T is defined in namespace
5101 // foo):
5102 //
5103 // 1. foo::PrintTo(const T&, ostream*)
5104 // 2. operator<<(ostream&, const T&) defined in either foo or the
5105 // global namespace.
5106 //
5107 // However if T is an STL-style container then it is printed element-wise
5108 // unless foo::PrintTo(const T&, ostream*) is defined. Note that
5109 // operator<<() is ignored for container types.
5110 //
5111 // If none of the above is defined, it will print the debug string of
5112 // the value if it is a protocol buffer, or print the raw bytes in the
5113 // value otherwise.
5114 //
5115 // To aid debugging: when T is a reference type, the address of the
5116 // value is also printed; when T is a (const) char pointer, both the
5117 // pointer value and the NUL-terminated string it points to are
5118 // printed.
5119 //
5120 // We also provide some convenient wrappers:
5121 //
5122 // // Prints a value to a string. For a (const or not) char
5123 // // pointer, the NUL-terminated string (but not the pointer) is
5124 // // printed.
5125 // std::string ::testing::PrintToString(const T& value);
5126 //
5127 // // Prints a value tersely: for a reference type, the referenced
5128 // // value (but not the address) is printed; for a (const or not) char
5129 // // pointer, the NUL-terminated string (but not the pointer) is
5130 // // printed.
5131 // void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
5132 //
5133 // // Prints value using the type inferred by the compiler. The difference
5134 // // from UniversalTersePrint() is that this function prints both the
5135 // // pointer and the NUL-terminated string for a (const or not) char pointer.
5136 // void ::testing::internal::UniversalPrint(const T& value, ostream*);
5137 //
5138 // // Prints the fields of a tuple tersely to a string vector, one
5139 // // element for each field. Tuple support must be enabled in
5140 // // gtest-port.h.
5141 // std::vector<string> UniversalTersePrintTupleFieldsToStrings(
5142 // const Tuple& value);
5143 //
5144 // Known limitation:
5145 //
5146 // The print primitives print the elements of an STL-style container
5147 // using the compiler-inferred type of *iter where iter is a
5148 // const_iterator of the container. When const_iterator is an input
5149 // iterator but not a forward iterator, this inferred type may not
5150 // match value_type, and the print output may be incorrect. In
5151 // practice, this is rarely a problem as for most containers
5152 // const_iterator is a forward iterator. We'll fix this if there's an
5153 // actual need for it. Note that this fix cannot rely on value_type
5154 // being defined as many user-defined container types don't have
5155 // value_type.
5156
5157 // GOOGLETEST_CM0001 DO NOT DELETE
5158
5159 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
5160 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
5161
5162 #include <functional>
5163 #include <memory>
5164 #include <ostream> // NOLINT
5165 #include <sstream>
5166 #include <string>
5167 #include <tuple>
5168 #include <type_traits>
5169 #include <utility>
5170 #include <vector>
5171
5172
5173 #if GTEST_HAS_RTTI
5174 #include <typeindex>
5175 #include <typeinfo>
5176 #endif // GTEST_HAS_RTTI
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_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 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 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 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 #if GTEST_HAS_RTTI
5733 inline void PrintTo(const ::std::type_info& value, ::std::ostream* os) {
5734 internal::PrintTo<::std::type_info>(value, os);
5735 *os << " (\"" << value.name() << "\")";
5736 }
5737
5738 inline void PrintTo(const ::std::type_index& value, ::std::ostream* os) {
5739 internal::PrintTo<::std::type_index>(value, os);
5740 *os << " (\"" << value.name() << "\")";
5741 }
5742 #endif // GTEST_HAS_RTTI
5743
5744 // Implements printing a non-reference type T by letting the compiler
5745 // pick the right overload of PrintTo() for T.
5746 template <typename T>
5747 class UniversalPrinter {
5748 public:
5749 // MSVC warns about adding const to a function type, so we want to
5750 // disable the warning.
5751 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
5752
5753 // Note: we deliberately don't call this PrintTo(), as that name
5754 // conflicts with ::testing::internal::PrintTo in the body of the
5755 // function.
5756 static void Print(const T& value, ::std::ostream* os) {
5757 // By default, ::testing::internal::PrintTo() is used for printing
5758 // the value.
5759 //
5760 // Thanks to Koenig look-up, if T is a class and has its own
5761 // PrintTo() function defined in its namespace, that function will
5762 // be visible here. Since it is more specific than the generic ones
5763 // in ::testing::internal, it will be picked by the compiler in the
5764 // following statement - exactly what we want.
5765 PrintTo(value, os);
5766 }
5767
5768 GTEST_DISABLE_MSC_WARNINGS_POP_()
5769 };
5770
5771 // Remove any const-qualifiers before passing a type to UniversalPrinter.
5772 template <typename T>
5773 class UniversalPrinter<const T> : public UniversalPrinter<T> {};
5774
5775 #if GTEST_INTERNAL_HAS_ANY
5776
5777 // Printer for std::any / absl::any
5778
5779 template <>
5780 class UniversalPrinter<Any> {
5781 public:
5782 static void Print(const Any& value, ::std::ostream* os) {
5783 if (value.has_value()) {
5784 *os << "value of type " << GetTypeName(value);
5785 } else {
5786 *os << "no value";
5787 }
5788 }
5789
5790 private:
5791 static std::string GetTypeName(const Any& value) {
5792 #if GTEST_HAS_RTTI
5793 return internal::GetTypeName(value.type());
5794 #else
5795 static_cast<void>(value); // possibly unused
5796 return "<unknown_type>";
5797 #endif // GTEST_HAS_RTTI
5798 }
5799 };
5800
5801 #endif // GTEST_INTERNAL_HAS_ANY
5802
5803 #if GTEST_INTERNAL_HAS_OPTIONAL
5804
5805 // Printer for std::optional / absl::optional
5806
5807 template <typename T>
5808 class UniversalPrinter<Optional<T>> {
5809 public:
5810 static void Print(const Optional<T>& value, ::std::ostream* os) {
5811 *os << '(';
5812 if (!value) {
5813 *os << "nullopt";
5814 } else {
5815 UniversalPrint(*value, os);
5816 }
5817 *os << ')';
5818 }
5819 };
5820
5821 #endif // GTEST_INTERNAL_HAS_OPTIONAL
5822
5823 #if GTEST_INTERNAL_HAS_VARIANT
5824
5825 // Printer for std::variant / absl::variant
5826
5827 template <typename... T>
5828 class UniversalPrinter<Variant<T...>> {
5829 public:
5830 static void Print(const Variant<T...>& value, ::std::ostream* os) {
5831 *os << '(';
5832 #if GTEST_HAS_ABSL
5833 absl::visit(Visitor{os, value.index()}, value);
5834 #else
5835 std::visit(Visitor{os, value.index()}, value);
5836 #endif // GTEST_HAS_ABSL
5837 *os << ')';
5838 }
5839
5840 private:
5841 struct Visitor {
5842 template <typename U>
5843 void operator()(const U& u) const {
5844 *os << "'" << GetTypeName<U>() << "(index = " << index
5845 << ")' with value ";
5846 UniversalPrint(u, os);
5847 }
5848 ::std::ostream* os;
5849 std::size_t index;
5850 };
5851 };
5852
5853 #endif // GTEST_INTERNAL_HAS_VARIANT
5854
5855 // UniversalPrintArray(begin, len, os) prints an array of 'len'
5856 // elements, starting at address 'begin'.
5857 template <typename T>
5858 void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
5859 if (len == 0) {
5860 *os << "{}";
5861 } else {
5862 *os << "{ ";
5863 const size_t kThreshold = 18;
5864 const size_t kChunkSize = 8;
5865 // If the array has more than kThreshold elements, we'll have to
5866 // omit some details by printing only the first and the last
5867 // kChunkSize elements.
5868 if (len <= kThreshold) {
5869 PrintRawArrayTo(begin, len, os);
5870 } else {
5871 PrintRawArrayTo(begin, kChunkSize, os);
5872 *os << ", ..., ";
5873 PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
5874 }
5875 *os << " }";
5876 }
5877 }
5878 // This overload prints a (const) char array compactly.
5879 GTEST_API_ void UniversalPrintArray(
5880 const char* begin, size_t len, ::std::ostream* os);
5881
5882 #ifdef __cpp_char8_t
5883 // This overload prints a (const) char8_t array compactly.
5884 GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
5885 ::std::ostream* os);
5886 #endif
5887
5888 // This overload prints a (const) char16_t array compactly.
5889 GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
5890 ::std::ostream* os);
5891
5892 // This overload prints a (const) char32_t array compactly.
5893 GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
5894 ::std::ostream* os);
5895
5896 // This overload prints a (const) wchar_t array compactly.
5897 GTEST_API_ void UniversalPrintArray(
5898 const wchar_t* begin, size_t len, ::std::ostream* os);
5899
5900 // Implements printing an array type T[N].
5901 template <typename T, size_t N>
5902 class UniversalPrinter<T[N]> {
5903 public:
5904 // Prints the given array, omitting some elements when there are too
5905 // many.
5906 static void Print(const T (&a)[N], ::std::ostream* os) {
5907 UniversalPrintArray(a, N, os);
5908 }
5909 };
5910
5911 // Implements printing a reference type T&.
5912 template <typename T>
5913 class UniversalPrinter<T&> {
5914 public:
5915 // MSVC warns about adding const to a function type, so we want to
5916 // disable the warning.
5917 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
5918
5919 static void Print(const T& value, ::std::ostream* os) {
5920 // Prints the address of the value. We use reinterpret_cast here
5921 // as static_cast doesn't compile when T is a function type.
5922 *os << "@" << reinterpret_cast<const void*>(&value) << " ";
5923
5924 // Then prints the value itself.
5925 UniversalPrint(value, os);
5926 }
5927
5928 GTEST_DISABLE_MSC_WARNINGS_POP_()
5929 };
5930
5931 // Prints a value tersely: for a reference type, the referenced value
5932 // (but not the address) is printed; for a (const) char pointer, the
5933 // NUL-terminated string (but not the pointer) is printed.
5934
5935 template <typename T>
5936 class UniversalTersePrinter {
5937 public:
5938 static void Print(const T& value, ::std::ostream* os) {
5939 UniversalPrint(value, os);
5940 }
5941 };
5942 template <typename T>
5943 class UniversalTersePrinter<T&> {
5944 public:
5945 static void Print(const T& value, ::std::ostream* os) {
5946 UniversalPrint(value, os);
5947 }
5948 };
5949 template <typename T, size_t N>
5950 class UniversalTersePrinter<T[N]> {
5951 public:
5952 static void Print(const T (&value)[N], ::std::ostream* os) {
5953 UniversalPrinter<T[N]>::Print(value, os);
5954 }
5955 };
5956 template <>
5957 class UniversalTersePrinter<const char*> {
5958 public:
5959 static void Print(const char* str, ::std::ostream* os) {
5960 if (str == nullptr) {
5961 *os << "NULL";
5962 } else {
5963 UniversalPrint(std::string(str), os);
5964 }
5965 }
5966 };
5967 template <>
5968 class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
5969 };
5970
5971 #ifdef __cpp_char8_t
5972 template <>
5973 class UniversalTersePrinter<const char8_t*> {
5974 public:
5975 static void Print(const char8_t* str, ::std::ostream* os) {
5976 if (str == nullptr) {
5977 *os << "NULL";
5978 } else {
5979 UniversalPrint(::std::u8string(str), os);
5980 }
5981 }
5982 };
5983 template <>
5984 class UniversalTersePrinter<char8_t*>
5985 : public UniversalTersePrinter<const char8_t*> {};
5986 #endif
5987
5988 template <>
5989 class UniversalTersePrinter<const char16_t*> {
5990 public:
5991 static void Print(const char16_t* str, ::std::ostream* os) {
5992 if (str == nullptr) {
5993 *os << "NULL";
5994 } else {
5995 UniversalPrint(::std::u16string(str), os);
5996 }
5997 }
5998 };
5999 template <>
6000 class UniversalTersePrinter<char16_t*>
6001 : public UniversalTersePrinter<const char16_t*> {};
6002
6003 template <>
6004 class UniversalTersePrinter<const char32_t*> {
6005 public:
6006 static void Print(const char32_t* str, ::std::ostream* os) {
6007 if (str == nullptr) {
6008 *os << "NULL";
6009 } else {
6010 UniversalPrint(::std::u32string(str), os);
6011 }
6012 }
6013 };
6014 template <>
6015 class UniversalTersePrinter<char32_t*>
6016 : public UniversalTersePrinter<const char32_t*> {};
6017
6018 #if GTEST_HAS_STD_WSTRING
6019 template <>
6020 class UniversalTersePrinter<const wchar_t*> {
6021 public:
6022 static void Print(const wchar_t* str, ::std::ostream* os) {
6023 if (str == nullptr) {
6024 *os << "NULL";
6025 } else {
6026 UniversalPrint(::std::wstring(str), os);
6027 }
6028 }
6029 };
6030 #endif
6031
6032 template <>
6033 class UniversalTersePrinter<wchar_t*> {
6034 public:
6035 static void Print(wchar_t* str, ::std::ostream* os) {
6036 UniversalTersePrinter<const wchar_t*>::Print(str, os);
6037 }
6038 };
6039
6040 template <typename T>
6041 void UniversalTersePrint(const T& value, ::std::ostream* os) {
6042 UniversalTersePrinter<T>::Print(value, os);
6043 }
6044
6045 // Prints a value using the type inferred by the compiler. The
6046 // difference between this and UniversalTersePrint() is that for a
6047 // (const) char pointer, this prints both the pointer and the
6048 // NUL-terminated string.
6049 template <typename T>
6050 void UniversalPrint(const T& value, ::std::ostream* os) {
6051 // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
6052 // UniversalPrinter with T directly.
6053 typedef T T1;
6054 UniversalPrinter<T1>::Print(value, os);
6055 }
6056
6057 typedef ::std::vector< ::std::string> Strings;
6058
6059 // Tersely prints the first N fields of a tuple to a string vector,
6060 // one element for each field.
6061 template <typename Tuple>
6062 void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
6063 Strings*) {}
6064 template <typename Tuple, size_t I>
6065 void TersePrintPrefixToStrings(const Tuple& t,
6066 std::integral_constant<size_t, I>,
6067 Strings* strings) {
6068 TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
6069 strings);
6070 ::std::stringstream ss;
6071 UniversalTersePrint(std::get<I - 1>(t), &ss);
6072 strings->push_back(ss.str());
6073 }
6074
6075 // Prints the fields of a tuple tersely to a string vector, one
6076 // element for each field. See the comment before
6077 // UniversalTersePrint() for how we define "tersely".
6078 template <typename Tuple>
6079 Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
6080 Strings result;
6081 TersePrintPrefixToStrings(
6082 value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
6083 &result);
6084 return result;
6085 }
6086
6087 } // namespace internal
6088
6089 template <typename T>
6090 ::std::string PrintToString(const T& value) {
6091 ::std::stringstream ss;
6092 internal::UniversalTersePrinter<T>::Print(value, &ss);
6093 return ss.str();
6094 }
6095
6096 } // namespace testing
6097
6098 // Include any custom printer added by the local installation.
6099 // We must include this header at the end to make sure it can use the
6100 // declarations from this file.
6101 // Copyright 2015, Google Inc.
6102 // All rights reserved.
6103 //
6104 // Redistribution and use in source and binary forms, with or without
6105 // modification, are permitted provided that the following conditions are
6106 // met:
6107 //
6108 // * Redistributions of source code must retain the above copyright
6109 // notice, this list of conditions and the following disclaimer.
6110 // * Redistributions in binary form must reproduce the above
6111 // copyright notice, this list of conditions and the following disclaimer
6112 // in the documentation and/or other materials provided with the
6113 // distribution.
6114 // * Neither the name of Google Inc. nor the names of its
6115 // contributors may be used to endorse or promote products derived from
6116 // this software without specific prior written permission.
6117 //
6118 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6119 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6120 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6121 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6122 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6123 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6124 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6125 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6126 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6127 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6128 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6129 //
6130 // This file provides an injection point for custom printers in a local
6131 // installation of gTest.
6132 // It will be included from gtest-printers.h and the overrides in this file
6133 // will be visible to everyone.
6134 //
6135 // Injection point for custom user configurations. See README for details
6136 //
6137 // ** Custom implementation starts here **
6138
6139 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
6140 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
6141
6142 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
6143
6144 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
6145
6146 // MSVC warning C5046 is new as of VS2017 version 15.8.
6147 #if defined(_MSC_VER) && _MSC_VER >= 1915
6148 #define GTEST_MAYBE_5046_ 5046
6149 #else
6150 #define GTEST_MAYBE_5046_
6151 #endif
6152
6153 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
6154 4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
6155 clients of class B */
6156 /* Symbol involving type with internal linkage not defined */)
6157
6158 namespace testing {
6159
6160 // To implement a matcher Foo for type T, define:
6161 // 1. a class FooMatcherMatcher that implements the matcher interface:
6162 // using is_gtest_matcher = void;
6163 // bool MatchAndExplain(const T&, std::ostream*);
6164 // (MatchResultListener* can also be used instead of std::ostream*)
6165 // void DescribeTo(std::ostream*);
6166 // void DescribeNegationTo(std::ostream*);
6167 //
6168 // 2. a factory function that creates a Matcher<T> object from a
6169 // FooMatcherMatcher.
6170
6171 class MatchResultListener {
6172 public:
6173 // Creates a listener object with the given underlying ostream. The
6174 // listener does not own the ostream, and does not dereference it
6175 // in the constructor or destructor.
6176 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
6177 virtual ~MatchResultListener() = 0; // Makes this class abstract.
6178
6179 // Streams x to the underlying ostream; does nothing if the ostream
6180 // is NULL.
6181 template <typename T>
6182 MatchResultListener& operator<<(const T& x) {
6183 if (stream_ != nullptr) *stream_ << x;
6184 return *this;
6185 }
6186
6187 // Returns the underlying ostream.
6188 ::std::ostream* stream() { return stream_; }
6189
6190 // Returns true if and only if the listener is interested in an explanation
6191 // of the match result. A matcher's MatchAndExplain() method can use
6192 // this information to avoid generating the explanation when no one
6193 // intends to hear it.
6194 bool IsInterested() const { return stream_ != nullptr; }
6195
6196 private:
6197 ::std::ostream* const stream_;
6198
6199 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
6200 };
6201
6202 inline MatchResultListener::~MatchResultListener() {
6203 }
6204
6205 // An instance of a subclass of this knows how to describe itself as a
6206 // matcher.
6207 class MatcherDescriberInterface {
6208 public:
6209 virtual ~MatcherDescriberInterface() {}
6210
6211 // Describes this matcher to an ostream. The function should print
6212 // a verb phrase that describes the property a value matching this
6213 // matcher should have. The subject of the verb phrase is the value
6214 // being matched. For example, the DescribeTo() method of the Gt(7)
6215 // matcher prints "is greater than 7".
6216 virtual void DescribeTo(::std::ostream* os) const = 0;
6217
6218 // Describes the negation of this matcher to an ostream. For
6219 // example, if the description of this matcher is "is greater than
6220 // 7", the negated description could be "is not greater than 7".
6221 // You are not required to override this when implementing
6222 // MatcherInterface, but it is highly advised so that your matcher
6223 // can produce good error messages.
6224 virtual void DescribeNegationTo(::std::ostream* os) const {
6225 *os << "not (";
6226 DescribeTo(os);
6227 *os << ")";
6228 }
6229 };
6230
6231 // The implementation of a matcher.
6232 template <typename T>
6233 class MatcherInterface : public MatcherDescriberInterface {
6234 public:
6235 // Returns true if and only if the matcher matches x; also explains the
6236 // match result to 'listener' if necessary (see the next paragraph), in
6237 // the form of a non-restrictive relative clause ("which ...",
6238 // "whose ...", etc) that describes x. For example, the
6239 // MatchAndExplain() method of the Pointee(...) matcher should
6240 // generate an explanation like "which points to ...".
6241 //
6242 // Implementations of MatchAndExplain() should add an explanation of
6243 // the match result *if and only if* they can provide additional
6244 // information that's not already present (or not obvious) in the
6245 // print-out of x and the matcher's description. Whether the match
6246 // succeeds is not a factor in deciding whether an explanation is
6247 // needed, as sometimes the caller needs to print a failure message
6248 // when the match succeeds (e.g. when the matcher is used inside
6249 // Not()).
6250 //
6251 // For example, a "has at least 10 elements" matcher should explain
6252 // what the actual element count is, regardless of the match result,
6253 // as it is useful information to the reader; on the other hand, an
6254 // "is empty" matcher probably only needs to explain what the actual
6255 // size is when the match fails, as it's redundant to say that the
6256 // size is 0 when the value is already known to be empty.
6257 //
6258 // You should override this method when defining a new matcher.
6259 //
6260 // It's the responsibility of the caller (Google Test) to guarantee
6261 // that 'listener' is not NULL. This helps to simplify a matcher's
6262 // implementation when it doesn't care about the performance, as it
6263 // can talk to 'listener' without checking its validity first.
6264 // However, in order to implement dummy listeners efficiently,
6265 // listener->stream() may be NULL.
6266 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
6267
6268 // Inherits these methods from MatcherDescriberInterface:
6269 // virtual void DescribeTo(::std::ostream* os) const = 0;
6270 // virtual void DescribeNegationTo(::std::ostream* os) const;
6271 };
6272
6273 namespace internal {
6274
6275 struct AnyEq {
6276 template <typename A, typename B>
6277 bool operator()(const A& a, const B& b) const { return a == b; }
6278 };
6279 struct AnyNe {
6280 template <typename A, typename B>
6281 bool operator()(const A& a, const B& b) const { return a != b; }
6282 };
6283 struct AnyLt {
6284 template <typename A, typename B>
6285 bool operator()(const A& a, const B& b) const { return a < b; }
6286 };
6287 struct AnyGt {
6288 template <typename A, typename B>
6289 bool operator()(const A& a, const B& b) const { return a > b; }
6290 };
6291 struct AnyLe {
6292 template <typename A, typename B>
6293 bool operator()(const A& a, const B& b) const { return a <= b; }
6294 };
6295 struct AnyGe {
6296 template <typename A, typename B>
6297 bool operator()(const A& a, const B& b) const { return a >= b; }
6298 };
6299
6300 // A match result listener that ignores the explanation.
6301 class DummyMatchResultListener : public MatchResultListener {
6302 public:
6303 DummyMatchResultListener() : MatchResultListener(nullptr) {}
6304
6305 private:
6306 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
6307 };
6308
6309 // A match result listener that forwards the explanation to a given
6310 // ostream. The difference between this and MatchResultListener is
6311 // that the former is concrete.
6312 class StreamMatchResultListener : public MatchResultListener {
6313 public:
6314 explicit StreamMatchResultListener(::std::ostream* os)
6315 : MatchResultListener(os) {}
6316
6317 private:
6318 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
6319 };
6320
6321 struct SharedPayloadBase {
6322 std::atomic<int> ref{1};
6323 void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
6324 bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
6325 };
6326
6327 template <typename T>
6328 struct SharedPayload : SharedPayloadBase {
6329 explicit SharedPayload(const T& v) : value(v) {}
6330 explicit SharedPayload(T&& v) : value(std::move(v)) {}
6331
6332 static void Destroy(SharedPayloadBase* shared) {
6333 delete static_cast<SharedPayload*>(shared);
6334 }
6335
6336 T value;
6337 };
6338
6339 template <typename T>
6340 using is_trivially_copy_constructible =
6341 #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 5
6342 std::has_trivial_copy_constructor<T>;
6343 #else
6344 std::is_trivially_copy_constructible<T>;
6345 #endif
6346
6347 // An internal class for implementing Matcher<T>, which will derive
6348 // from it. We put functionalities common to all Matcher<T>
6349 // specializations here to avoid code duplication.
6350 template <typename T>
6351 class MatcherBase : private MatcherDescriberInterface {
6352 public:
6353 // Returns true if and only if the matcher matches x; also explains the
6354 // match result to 'listener'.
6355 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
6356 GTEST_CHECK_(vtable_ != nullptr);
6357 return vtable_->match_and_explain(*this, x, listener);
6358 }
6359
6360 // Returns true if and only if this matcher matches x.
6361 bool Matches(const T& x) const {
6362 DummyMatchResultListener dummy;
6363 return MatchAndExplain(x, &dummy);
6364 }
6365
6366 // Describes this matcher to an ostream.
6367 void DescribeTo(::std::ostream* os) const final {
6368 GTEST_CHECK_(vtable_ != nullptr);
6369 vtable_->describe(*this, os, false);
6370 }
6371
6372 // Describes the negation of this matcher to an ostream.
6373 void DescribeNegationTo(::std::ostream* os) const final {
6374 GTEST_CHECK_(vtable_ != nullptr);
6375 vtable_->describe(*this, os, true);
6376 }
6377
6378 // Explains why x matches, or doesn't match, the matcher.
6379 void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
6380 StreamMatchResultListener listener(os);
6381 MatchAndExplain(x, &listener);
6382 }
6383
6384 // Returns the describer for this matcher object; retains ownership
6385 // of the describer, which is only guaranteed to be alive when
6386 // this matcher object is alive.
6387 const MatcherDescriberInterface* GetDescriber() const {
6388 if (vtable_ == nullptr) return nullptr;
6389 return vtable_->get_describer(*this);
6390 }
6391
6392 protected:
6393 MatcherBase() : vtable_(nullptr) {}
6394
6395 // Constructs a matcher from its implementation.
6396 template <typename U>
6397 explicit MatcherBase(const MatcherInterface<U>* impl) {
6398 Init(impl);
6399 }
6400
6401 template <typename M, typename = typename std::remove_reference<
6402 M>::type::is_gtest_matcher>
6403 MatcherBase(M&& m) { // NOLINT
6404 Init(std::forward<M>(m));
6405 }
6406
6407 MatcherBase(const MatcherBase& other)
6408 : vtable_(other.vtable_), buffer_(other.buffer_) {
6409 if (IsShared()) buffer_.shared->Ref();
6410 }
6411
6412 MatcherBase& operator=(const MatcherBase& other) {
6413 if (this == &other) return *this;
6414 Destroy();
6415 vtable_ = other.vtable_;
6416 buffer_ = other.buffer_;
6417 if (IsShared()) buffer_.shared->Ref();
6418 return *this;
6419 }
6420
6421 MatcherBase(MatcherBase&& other)
6422 : vtable_(other.vtable_), buffer_(other.buffer_) {
6423 other.vtable_ = nullptr;
6424 }
6425
6426 MatcherBase& operator=(MatcherBase&& other) {
6427 if (this == &other) return *this;
6428 Destroy();
6429 vtable_ = other.vtable_;
6430 buffer_ = other.buffer_;
6431 other.vtable_ = nullptr;
6432 return *this;
6433 }
6434
6435 ~MatcherBase() override { Destroy(); }
6436
6437 private:
6438 struct VTable {
6439 bool (*match_and_explain)(const MatcherBase&, const T&,
6440 MatchResultListener*);
6441 void (*describe)(const MatcherBase&, std::ostream*, bool negation);
6442 // Returns the captured object if it implements the interface, otherwise
6443 // returns the MatcherBase itself.
6444 const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
6445 // Called on shared instances when the reference count reaches 0.
6446 void (*shared_destroy)(SharedPayloadBase*);
6447 };
6448
6449 bool IsShared() const {
6450 return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
6451 }
6452
6453 // If the implementation uses a listener, call that.
6454 template <typename P>
6455 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
6456 MatchResultListener* listener)
6457 -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
6458 return P::Get(m).MatchAndExplain(value, listener->stream());
6459 }
6460
6461 template <typename P>
6462 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
6463 MatchResultListener* listener)
6464 -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
6465 return P::Get(m).MatchAndExplain(value, listener);
6466 }
6467
6468 template <typename P>
6469 static void DescribeImpl(const MatcherBase& m, std::ostream* os,
6470 bool negation) {
6471 if (negation) {
6472 P::Get(m).DescribeNegationTo(os);
6473 } else {
6474 P::Get(m).DescribeTo(os);
6475 }
6476 }
6477
6478 template <typename P>
6479 static const MatcherDescriberInterface* GetDescriberImpl(
6480 const MatcherBase& m) {
6481 // If the impl is a MatcherDescriberInterface, then return it.
6482 // Otherwise use MatcherBase itself.
6483 // This allows us to implement the GetDescriber() function without support
6484 // from the impl, but some users really want to get their impl back when
6485 // they call GetDescriber().
6486 // We use std::get on a tuple as a workaround of not having `if constexpr`.
6487 return std::get<(
6488 std::is_convertible<decltype(&P::Get(m)),
6489 const MatcherDescriberInterface*>::value
6490 ? 1
6491 : 0)>(std::make_tuple(&m, &P::Get(m)));
6492 }
6493
6494 template <typename P>
6495 const VTable* GetVTable() {
6496 static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
6497 &DescribeImpl<P>, &GetDescriberImpl<P>,
6498 P::shared_destroy};
6499 return &kVTable;
6500 }
6501
6502 union Buffer {
6503 // Add some types to give Buffer some common alignment/size use cases.
6504 void* ptr;
6505 double d;
6506 int64_t i;
6507 // And add one for the out-of-line cases.
6508 SharedPayloadBase* shared;
6509 };
6510
6511 void Destroy() {
6512 if (IsShared() && buffer_.shared->Unref()) {
6513 vtable_->shared_destroy(buffer_.shared);
6514 }
6515 }
6516
6517 template <typename M>
6518 static constexpr bool IsInlined() {
6519 return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
6520 is_trivially_copy_constructible<M>::value &&
6521 std::is_trivially_destructible<M>::value;
6522 }
6523
6524 template <typename M, bool = MatcherBase::IsInlined<M>()>
6525 struct ValuePolicy {
6526 static const M& Get(const MatcherBase& m) {
6527 // When inlined along with Init, need to be explicit to avoid violating
6528 // strict aliasing rules.
6529 const M *ptr = static_cast<const M*>(
6530 static_cast<const void*>(&m.buffer_));
6531 return *ptr;
6532 }
6533 static void Init(MatcherBase& m, M impl) {
6534 ::new (static_cast<void*>(&m.buffer_)) M(impl);
6535 }
6536 static constexpr auto shared_destroy = nullptr;
6537 };
6538
6539 template <typename M>
6540 struct ValuePolicy<M, false> {
6541 using Shared = SharedPayload<M>;
6542 static const M& Get(const MatcherBase& m) {
6543 return static_cast<Shared*>(m.buffer_.shared)->value;
6544 }
6545 template <typename Arg>
6546 static void Init(MatcherBase& m, Arg&& arg) {
6547 m.buffer_.shared = new Shared(std::forward<Arg>(arg));
6548 }
6549 static constexpr auto shared_destroy = &Shared::Destroy;
6550 };
6551
6552 template <typename U, bool B>
6553 struct ValuePolicy<const MatcherInterface<U>*, B> {
6554 using M = const MatcherInterface<U>;
6555 using Shared = SharedPayload<std::unique_ptr<M>>;
6556 static const M& Get(const MatcherBase& m) {
6557 return *static_cast<Shared*>(m.buffer_.shared)->value;
6558 }
6559 static void Init(MatcherBase& m, M* impl) {
6560 m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
6561 }
6562
6563 static constexpr auto shared_destroy = &Shared::Destroy;
6564 };
6565
6566 template <typename M>
6567 void Init(M&& m) {
6568 using MM = typename std::decay<M>::type;
6569 using Policy = ValuePolicy<MM>;
6570 vtable_ = GetVTable<Policy>();
6571 Policy::Init(*this, std::forward<M>(m));
6572 }
6573
6574 const VTable* vtable_;
6575 Buffer buffer_;
6576 };
6577
6578 } // namespace internal
6579
6580 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
6581 // object that can check whether a value of type T matches. The
6582 // implementation of Matcher<T> is just a std::shared_ptr to const
6583 // MatcherInterface<T>. Don't inherit from Matcher!
6584 template <typename T>
6585 class Matcher : public internal::MatcherBase<T> {
6586 public:
6587 // Constructs a null matcher. Needed for storing Matcher objects in STL
6588 // containers. A default-constructed matcher is not yet initialized. You
6589 // cannot use it until a valid value has been assigned to it.
6590 explicit Matcher() {} // NOLINT
6591
6592 // Constructs a matcher from its implementation.
6593 explicit Matcher(const MatcherInterface<const T&>* impl)
6594 : internal::MatcherBase<T>(impl) {}
6595
6596 template <typename U>
6597 explicit Matcher(
6598 const MatcherInterface<U>* impl,
6599 typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
6600 nullptr)
6601 : internal::MatcherBase<T>(impl) {}
6602
6603 template <typename M, typename = typename std::remove_reference<
6604 M>::type::is_gtest_matcher>
6605 Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
6606
6607 // Implicit constructor here allows people to write
6608 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
6609 Matcher(T value); // NOLINT
6610 };
6611
6612 // The following two specializations allow the user to write str
6613 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
6614 // matcher is expected.
6615 template <>
6616 class GTEST_API_ Matcher<const std::string&>
6617 : public internal::MatcherBase<const std::string&> {
6618 public:
6619 Matcher() {}
6620
6621 explicit Matcher(const MatcherInterface<const std::string&>* impl)
6622 : internal::MatcherBase<const std::string&>(impl) {}
6623
6624 template <typename M, typename = typename std::remove_reference<
6625 M>::type::is_gtest_matcher>
6626 Matcher(M&& m) // NOLINT
6627 : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
6628
6629 // Allows the user to write str instead of Eq(str) sometimes, where
6630 // str is a std::string object.
6631 Matcher(const std::string& s); // NOLINT
6632
6633 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6634 Matcher(const char* s); // NOLINT
6635 };
6636
6637 template <>
6638 class GTEST_API_ Matcher<std::string>
6639 : public internal::MatcherBase<std::string> {
6640 public:
6641 Matcher() {}
6642
6643 explicit Matcher(const MatcherInterface<const std::string&>* impl)
6644 : internal::MatcherBase<std::string>(impl) {}
6645 explicit Matcher(const MatcherInterface<std::string>* impl)
6646 : internal::MatcherBase<std::string>(impl) {}
6647
6648 template <typename M, typename = typename std::remove_reference<
6649 M>::type::is_gtest_matcher>
6650 Matcher(M&& m) // NOLINT
6651 : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
6652
6653 // Allows the user to write str instead of Eq(str) sometimes, where
6654 // str is a string object.
6655 Matcher(const std::string& s); // NOLINT
6656
6657 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6658 Matcher(const char* s); // NOLINT
6659 };
6660
6661 #if GTEST_INTERNAL_HAS_STRING_VIEW
6662 // The following two specializations allow the user to write str
6663 // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
6664 // matcher is expected.
6665 template <>
6666 class GTEST_API_ Matcher<const internal::StringView&>
6667 : public internal::MatcherBase<const internal::StringView&> {
6668 public:
6669 Matcher() {}
6670
6671 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
6672 : internal::MatcherBase<const internal::StringView&>(impl) {}
6673
6674 template <typename M, typename = typename std::remove_reference<
6675 M>::type::is_gtest_matcher>
6676 Matcher(M&& m) // NOLINT
6677 : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
6678 }
6679
6680 // Allows the user to write str instead of Eq(str) sometimes, where
6681 // str is a std::string object.
6682 Matcher(const std::string& s); // NOLINT
6683
6684 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6685 Matcher(const char* s); // NOLINT
6686
6687 // Allows the user to pass absl::string_views or std::string_views directly.
6688 Matcher(internal::StringView s); // NOLINT
6689 };
6690
6691 template <>
6692 class GTEST_API_ Matcher<internal::StringView>
6693 : public internal::MatcherBase<internal::StringView> {
6694 public:
6695 Matcher() {}
6696
6697 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
6698 : internal::MatcherBase<internal::StringView>(impl) {}
6699 explicit Matcher(const MatcherInterface<internal::StringView>* impl)
6700 : internal::MatcherBase<internal::StringView>(impl) {}
6701
6702 template <typename M, typename = typename std::remove_reference<
6703 M>::type::is_gtest_matcher>
6704 Matcher(M&& m) // NOLINT
6705 : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
6706
6707 // Allows the user to write str instead of Eq(str) sometimes, where
6708 // str is a std::string object.
6709 Matcher(const std::string& s); // NOLINT
6710
6711 // Allows the user to write "foo" instead of Eq("foo") sometimes.
6712 Matcher(const char* s); // NOLINT
6713
6714 // Allows the user to pass absl::string_views or std::string_views directly.
6715 Matcher(internal::StringView s); // NOLINT
6716 };
6717 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
6718
6719 // Prints a matcher in a human-readable format.
6720 template <typename T>
6721 std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
6722 matcher.DescribeTo(&os);
6723 return os;
6724 }
6725
6726 // The PolymorphicMatcher class template makes it easy to implement a
6727 // polymorphic matcher (i.e. a matcher that can match values of more
6728 // than one type, e.g. Eq(n) and NotNull()).
6729 //
6730 // To define a polymorphic matcher, a user should provide an Impl
6731 // class that has a DescribeTo() method and a DescribeNegationTo()
6732 // method, and define a member function (or member function template)
6733 //
6734 // bool MatchAndExplain(const Value& value,
6735 // MatchResultListener* listener) const;
6736 //
6737 // See the definition of NotNull() for a complete example.
6738 template <class Impl>
6739 class PolymorphicMatcher {
6740 public:
6741 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
6742
6743 // Returns a mutable reference to the underlying matcher
6744 // implementation object.
6745 Impl& mutable_impl() { return impl_; }
6746
6747 // Returns an immutable reference to the underlying matcher
6748 // implementation object.
6749 const Impl& impl() const { return impl_; }
6750
6751 template <typename T>
6752 operator Matcher<T>() const {
6753 return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
6754 }
6755
6756 private:
6757 template <typename T>
6758 class MonomorphicImpl : public MatcherInterface<T> {
6759 public:
6760 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
6761
6762 void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
6763
6764 void DescribeNegationTo(::std::ostream* os) const override {
6765 impl_.DescribeNegationTo(os);
6766 }
6767
6768 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
6769 return impl_.MatchAndExplain(x, listener);
6770 }
6771
6772 private:
6773 const Impl impl_;
6774 };
6775
6776 Impl impl_;
6777 };
6778
6779 // Creates a matcher from its implementation.
6780 // DEPRECATED: Especially in the generic code, prefer:
6781 // Matcher<T>(new MyMatcherImpl<const T&>(...));
6782 //
6783 // MakeMatcher may create a Matcher that accepts its argument by value, which
6784 // leads to unnecessary copies & lack of support for non-copyable types.
6785 template <typename T>
6786 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
6787 return Matcher<T>(impl);
6788 }
6789
6790 // Creates a polymorphic matcher from its implementation. This is
6791 // easier to use than the PolymorphicMatcher<Impl> constructor as it
6792 // doesn't require you to explicitly write the template argument, e.g.
6793 //
6794 // MakePolymorphicMatcher(foo);
6795 // vs
6796 // PolymorphicMatcher<TypeOfFoo>(foo);
6797 template <class Impl>
6798 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
6799 return PolymorphicMatcher<Impl>(impl);
6800 }
6801
6802 namespace internal {
6803 // Implements a matcher that compares a given value with a
6804 // pre-supplied value using one of the ==, <=, <, etc, operators. The
6805 // two values being compared don't have to have the same type.
6806 //
6807 // The matcher defined here is polymorphic (for example, Eq(5) can be
6808 // used to match an int, a short, a double, etc). Therefore we use
6809 // a template type conversion operator in the implementation.
6810 //
6811 // The following template definition assumes that the Rhs parameter is
6812 // a "bare" type (i.e. neither 'const T' nor 'T&').
6813 template <typename D, typename Rhs, typename Op>
6814 class ComparisonBase {
6815 public:
6816 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
6817
6818 using is_gtest_matcher = void;
6819
6820 template <typename Lhs>
6821 bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
6822 return Op()(lhs, Unwrap(rhs_));
6823 }
6824 void DescribeTo(std::ostream* os) const {
6825 *os << D::Desc() << " ";
6826 UniversalPrint(Unwrap(rhs_), os);
6827 }
6828 void DescribeNegationTo(std::ostream* os) const {
6829 *os << D::NegatedDesc() << " ";
6830 UniversalPrint(Unwrap(rhs_), os);
6831 }
6832
6833 private:
6834 template <typename T>
6835 static const T& Unwrap(const T& v) {
6836 return v;
6837 }
6838 template <typename T>
6839 static const T& Unwrap(std::reference_wrapper<T> v) {
6840 return v;
6841 }
6842
6843 Rhs rhs_;
6844 };
6845
6846 template <typename Rhs>
6847 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
6848 public:
6849 explicit EqMatcher(const Rhs& rhs)
6850 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
6851 static const char* Desc() { return "is equal to"; }
6852 static const char* NegatedDesc() { return "isn't equal to"; }
6853 };
6854 template <typename Rhs>
6855 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
6856 public:
6857 explicit NeMatcher(const Rhs& rhs)
6858 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
6859 static const char* Desc() { return "isn't equal to"; }
6860 static const char* NegatedDesc() { return "is equal to"; }
6861 };
6862 template <typename Rhs>
6863 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
6864 public:
6865 explicit LtMatcher(const Rhs& rhs)
6866 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
6867 static const char* Desc() { return "is <"; }
6868 static const char* NegatedDesc() { return "isn't <"; }
6869 };
6870 template <typename Rhs>
6871 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
6872 public:
6873 explicit GtMatcher(const Rhs& rhs)
6874 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
6875 static const char* Desc() { return "is >"; }
6876 static const char* NegatedDesc() { return "isn't >"; }
6877 };
6878 template <typename Rhs>
6879 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
6880 public:
6881 explicit LeMatcher(const Rhs& rhs)
6882 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
6883 static const char* Desc() { return "is <="; }
6884 static const char* NegatedDesc() { return "isn't <="; }
6885 };
6886 template <typename Rhs>
6887 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
6888 public:
6889 explicit GeMatcher(const Rhs& rhs)
6890 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
6891 static const char* Desc() { return "is >="; }
6892 static const char* NegatedDesc() { return "isn't >="; }
6893 };
6894
6895 template <typename T, typename = typename std::enable_if<
6896 std::is_constructible<std::string, T>::value>::type>
6897 using StringLike = T;
6898
6899 // Implements polymorphic matchers MatchesRegex(regex) and
6900 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
6901 // T can be converted to a string.
6902 class MatchesRegexMatcher {
6903 public:
6904 MatchesRegexMatcher(const RE* regex, bool full_match)
6905 : regex_(regex), full_match_(full_match) {}
6906
6907 #if GTEST_INTERNAL_HAS_STRING_VIEW
6908 bool MatchAndExplain(const internal::StringView& s,
6909 MatchResultListener* listener) const {
6910 return MatchAndExplain(std::string(s), listener);
6911 }
6912 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
6913
6914 // Accepts pointer types, particularly:
6915 // const char*
6916 // char*
6917 // const wchar_t*
6918 // wchar_t*
6919 template <typename CharType>
6920 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
6921 return s != nullptr && MatchAndExplain(std::string(s), listener);
6922 }
6923
6924 // Matches anything that can convert to std::string.
6925 //
6926 // This is a template, not just a plain function with const std::string&,
6927 // because absl::string_view has some interfering non-explicit constructors.
6928 template <class MatcheeStringType>
6929 bool MatchAndExplain(const MatcheeStringType& s,
6930 MatchResultListener* /* listener */) const {
6931 const std::string& s2(s);
6932 return full_match_ ? RE::FullMatch(s2, *regex_)
6933 : RE::PartialMatch(s2, *regex_);
6934 }
6935
6936 void DescribeTo(::std::ostream* os) const {
6937 *os << (full_match_ ? "matches" : "contains") << " regular expression ";
6938 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
6939 }
6940
6941 void DescribeNegationTo(::std::ostream* os) const {
6942 *os << "doesn't " << (full_match_ ? "match" : "contain")
6943 << " regular expression ";
6944 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
6945 }
6946
6947 private:
6948 const std::shared_ptr<const RE> regex_;
6949 const bool full_match_;
6950 };
6951 } // namespace internal
6952
6953 // Matches a string that fully matches regular expression 'regex'.
6954 // The matcher takes ownership of 'regex'.
6955 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
6956 const internal::RE* regex) {
6957 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
6958 }
6959 template <typename T = std::string>
6960 PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
6961 const internal::StringLike<T>& regex) {
6962 return MatchesRegex(new internal::RE(std::string(regex)));
6963 }
6964
6965 // Matches a string that contains regular expression 'regex'.
6966 // The matcher takes ownership of 'regex'.
6967 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
6968 const internal::RE* regex) {
6969 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
6970 }
6971 template <typename T = std::string>
6972 PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
6973 const internal::StringLike<T>& regex) {
6974 return ContainsRegex(new internal::RE(std::string(regex)));
6975 }
6976
6977 // Creates a polymorphic matcher that matches anything equal to x.
6978 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
6979 // wouldn't compile.
6980 template <typename T>
6981 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
6982
6983 // Constructs a Matcher<T> from a 'value' of type T. The constructed
6984 // matcher matches any value that's equal to 'value'.
6985 template <typename T>
6986 Matcher<T>::Matcher(T value) { *this = Eq(value); }
6987
6988 // Creates a monomorphic matcher that matches anything with type Lhs
6989 // and equal to rhs. A user may need to use this instead of Eq(...)
6990 // in order to resolve an overloading ambiguity.
6991 //
6992 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
6993 // or Matcher<T>(x), but more readable than the latter.
6994 //
6995 // We could define similar monomorphic matchers for other comparison
6996 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
6997 // it yet as those are used much less than Eq() in practice. A user
6998 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
6999 // for example.
7000 template <typename Lhs, typename Rhs>
7001 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
7002
7003 // Creates a polymorphic matcher that matches anything >= x.
7004 template <typename Rhs>
7005 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
7006 return internal::GeMatcher<Rhs>(x);
7007 }
7008
7009 // Creates a polymorphic matcher that matches anything > x.
7010 template <typename Rhs>
7011 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
7012 return internal::GtMatcher<Rhs>(x);
7013 }
7014
7015 // Creates a polymorphic matcher that matches anything <= x.
7016 template <typename Rhs>
7017 inline internal::LeMatcher<Rhs> Le(Rhs x) {
7018 return internal::LeMatcher<Rhs>(x);
7019 }
7020
7021 // Creates a polymorphic matcher that matches anything < x.
7022 template <typename Rhs>
7023 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
7024 return internal::LtMatcher<Rhs>(x);
7025 }
7026
7027 // Creates a polymorphic matcher that matches anything != x.
7028 template <typename Rhs>
7029 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
7030 return internal::NeMatcher<Rhs>(x);
7031 }
7032 } // namespace testing
7033
7034 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
7035
7036 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
7037
7038 #include <stdio.h>
7039 #include <memory>
7040
7041 namespace testing {
7042 namespace internal {
7043
7044 GTEST_DECLARE_string_(internal_run_death_test);
7045
7046 // Names of the flags (needed for parsing Google Test flags).
7047 const char kDeathTestStyleFlag[] = "death_test_style";
7048 const char kDeathTestUseFork[] = "death_test_use_fork";
7049 const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
7050
7051 #if GTEST_HAS_DEATH_TEST
7052
7053 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
7054 /* class A needs to have dll-interface to be used by clients of class B */)
7055
7056 // DeathTest is a class that hides much of the complexity of the
7057 // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
7058 // returns a concrete class that depends on the prevailing death test
7059 // style, as defined by the --gtest_death_test_style and/or
7060 // --gtest_internal_run_death_test flags.
7061
7062 // In describing the results of death tests, these terms are used with
7063 // the corresponding definitions:
7064 //
7065 // exit status: The integer exit information in the format specified
7066 // by wait(2)
7067 // exit code: The integer code passed to exit(3), _exit(2), or
7068 // returned from main()
7069 class GTEST_API_ DeathTest {
7070 public:
7071 // Create returns false if there was an error determining the
7072 // appropriate action to take for the current death test; for example,
7073 // if the gtest_death_test_style flag is set to an invalid value.
7074 // The LastMessage method will return a more detailed message in that
7075 // case. Otherwise, the DeathTest pointer pointed to by the "test"
7076 // argument is set. If the death test should be skipped, the pointer
7077 // is set to NULL; otherwise, it is set to the address of a new concrete
7078 // DeathTest object that controls the execution of the current test.
7079 static bool Create(const char* statement, Matcher<const std::string&> matcher,
7080 const char* file, int line, DeathTest** test);
7081 DeathTest();
7082 virtual ~DeathTest() { }
7083
7084 // A helper class that aborts a death test when it's deleted.
7085 class ReturnSentinel {
7086 public:
7087 explicit ReturnSentinel(DeathTest* test) : test_(test) { }
7088 ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
7089 private:
7090 DeathTest* const test_;
7091 GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
7092 } GTEST_ATTRIBUTE_UNUSED_;
7093
7094 // An enumeration of possible roles that may be taken when a death
7095 // test is encountered. EXECUTE means that the death test logic should
7096 // be executed immediately. OVERSEE means that the program should prepare
7097 // the appropriate environment for a child process to execute the death
7098 // test, then wait for it to complete.
7099 enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
7100
7101 // An enumeration of the three reasons that a test might be aborted.
7102 enum AbortReason {
7103 TEST_ENCOUNTERED_RETURN_STATEMENT,
7104 TEST_THREW_EXCEPTION,
7105 TEST_DID_NOT_DIE
7106 };
7107
7108 // Assumes one of the above roles.
7109 virtual TestRole AssumeRole() = 0;
7110
7111 // Waits for the death test to finish and returns its status.
7112 virtual int Wait() = 0;
7113
7114 // Returns true if the death test passed; that is, the test process
7115 // exited during the test, its exit status matches a user-supplied
7116 // predicate, and its stderr output matches a user-supplied regular
7117 // expression.
7118 // The user-supplied predicate may be a macro expression rather
7119 // than a function pointer or functor, or else Wait and Passed could
7120 // be combined.
7121 virtual bool Passed(bool exit_status_ok) = 0;
7122
7123 // Signals that the death test did not die as expected.
7124 virtual void Abort(AbortReason reason) = 0;
7125
7126 // Returns a human-readable outcome message regarding the outcome of
7127 // the last death test.
7128 static const char* LastMessage();
7129
7130 static void set_last_death_test_message(const std::string& message);
7131
7132 private:
7133 // A string containing a description of the outcome of the last death test.
7134 static std::string last_death_test_message_;
7135
7136 GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
7137 };
7138
7139 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
7140
7141 // Factory interface for death tests. May be mocked out for testing.
7142 class DeathTestFactory {
7143 public:
7144 virtual ~DeathTestFactory() { }
7145 virtual bool Create(const char* statement,
7146 Matcher<const std::string&> matcher, const char* file,
7147 int line, DeathTest** test) = 0;
7148 };
7149
7150 // A concrete DeathTestFactory implementation for normal use.
7151 class DefaultDeathTestFactory : public DeathTestFactory {
7152 public:
7153 bool Create(const char* statement, Matcher<const std::string&> matcher,
7154 const char* file, int line, DeathTest** test) override;
7155 };
7156
7157 // Returns true if exit_status describes a process that was terminated
7158 // by a signal, or exited normally with a nonzero exit code.
7159 GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
7160
7161 // A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
7162 // and interpreted as a regex (rather than an Eq matcher) for legacy
7163 // compatibility.
7164 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7165 ::testing::internal::RE regex) {
7166 return ContainsRegex(regex.pattern());
7167 }
7168 inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
7169 return ContainsRegex(regex);
7170 }
7171 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7172 const ::std::string& regex) {
7173 return ContainsRegex(regex);
7174 }
7175
7176 // If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
7177 // used directly.
7178 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7179 Matcher<const ::std::string&> matcher) {
7180 return matcher;
7181 }
7182
7183 // Traps C++ exceptions escaping statement and reports them as test
7184 // failures. Note that trapping SEH exceptions is not implemented here.
7185 # if GTEST_HAS_EXCEPTIONS
7186 # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
7187 try { \
7188 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7189 } catch (const ::std::exception& gtest_exception) { \
7190 fprintf(\
7191 stderr, \
7192 "\n%s: Caught std::exception-derived exception escaping the " \
7193 "death test statement. Exception message: %s\n", \
7194 ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
7195 gtest_exception.what()); \
7196 fflush(stderr); \
7197 death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
7198 } catch (...) { \
7199 death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
7200 }
7201
7202 # else
7203 # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
7204 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
7205
7206 # endif
7207
7208 // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
7209 // ASSERT_EXIT*, and EXPECT_EXIT*.
7210 #define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \
7211 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7212 if (::testing::internal::AlwaysTrue()) { \
7213 ::testing::internal::DeathTest* gtest_dt; \
7214 if (!::testing::internal::DeathTest::Create( \
7215 #statement, \
7216 ::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \
7217 __FILE__, __LINE__, &gtest_dt)) { \
7218 goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
7219 } \
7220 if (gtest_dt != nullptr) { \
7221 std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
7222 switch (gtest_dt->AssumeRole()) { \
7223 case ::testing::internal::DeathTest::OVERSEE_TEST: \
7224 if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
7225 goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
7226 } \
7227 break; \
7228 case ::testing::internal::DeathTest::EXECUTE_TEST: { \
7229 ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
7230 gtest_dt); \
7231 GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
7232 gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
7233 break; \
7234 } \
7235 default: \
7236 break; \
7237 } \
7238 } \
7239 } else \
7240 GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
7241 : fail(::testing::internal::DeathTest::LastMessage())
7242 // The symbol "fail" here expands to something into which a message
7243 // can be streamed.
7244
7245 // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
7246 // NDEBUG mode. In this case we need the statements to be executed and the macro
7247 // must accept a streamed message even though the message is never printed.
7248 // The regex object is not evaluated, but it is used to prevent "unused"
7249 // warnings and to avoid an expression that doesn't compile in debug mode.
7250 #define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
7251 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7252 if (::testing::internal::AlwaysTrue()) { \
7253 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7254 } else if (!::testing::internal::AlwaysTrue()) { \
7255 ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
7256 } else \
7257 ::testing::Message()
7258
7259 // A class representing the parsed contents of the
7260 // --gtest_internal_run_death_test flag, as it existed when
7261 // RUN_ALL_TESTS was called.
7262 class InternalRunDeathTestFlag {
7263 public:
7264 InternalRunDeathTestFlag(const std::string& a_file,
7265 int a_line,
7266 int an_index,
7267 int a_write_fd)
7268 : file_(a_file), line_(a_line), index_(an_index),
7269 write_fd_(a_write_fd) {}
7270
7271 ~InternalRunDeathTestFlag() {
7272 if (write_fd_ >= 0)
7273 posix::Close(write_fd_);
7274 }
7275
7276 const std::string& file() const { return file_; }
7277 int line() const { return line_; }
7278 int index() const { return index_; }
7279 int write_fd() const { return write_fd_; }
7280
7281 private:
7282 std::string file_;
7283 int line_;
7284 int index_;
7285 int write_fd_;
7286
7287 GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
7288 };
7289
7290 // Returns a newly created InternalRunDeathTestFlag object with fields
7291 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7292 // the flag is specified; otherwise returns NULL.
7293 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
7294
7295 #endif // GTEST_HAS_DEATH_TEST
7296
7297 } // namespace internal
7298 } // namespace testing
7299
7300 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
7301
7302 namespace testing {
7303
7304 // This flag controls the style of death tests. Valid values are "threadsafe",
7305 // meaning that the death test child process will re-execute the test binary
7306 // from the start, running only a single death test, or "fast",
7307 // meaning that the child process will execute the test logic immediately
7308 // after forking.
7309 GTEST_DECLARE_string_(death_test_style);
7310
7311 #if GTEST_HAS_DEATH_TEST
7312
7313 namespace internal {
7314
7315 // Returns a Boolean value indicating whether the caller is currently
7316 // executing in the context of the death test child process. Tools such as
7317 // Valgrind heap checkers may need this to modify their behavior in death
7318 // tests. IMPORTANT: This is an internal utility. Using it may break the
7319 // implementation of death tests. User code MUST NOT use it.
7320 GTEST_API_ bool InDeathTestChild();
7321
7322 } // namespace internal
7323
7324 // The following macros are useful for writing death tests.
7325
7326 // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
7327 // executed:
7328 //
7329 // 1. It generates a warning if there is more than one active
7330 // thread. This is because it's safe to fork() or clone() only
7331 // when there is a single thread.
7332 //
7333 // 2. The parent process clone()s a sub-process and runs the death
7334 // test in it; the sub-process exits with code 0 at the end of the
7335 // death test, if it hasn't exited already.
7336 //
7337 // 3. The parent process waits for the sub-process to terminate.
7338 //
7339 // 4. The parent process checks the exit code and error message of
7340 // the sub-process.
7341 //
7342 // Examples:
7343 //
7344 // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
7345 // for (int i = 0; i < 5; i++) {
7346 // EXPECT_DEATH(server.ProcessRequest(i),
7347 // "Invalid request .* in ProcessRequest()")
7348 // << "Failed to die on request " << i;
7349 // }
7350 //
7351 // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
7352 //
7353 // bool KilledBySIGHUP(int exit_code) {
7354 // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
7355 // }
7356 //
7357 // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
7358 //
7359 // On the regular expressions used in death tests:
7360 //
7361 // GOOGLETEST_CM0005 DO NOT DELETE
7362 // On POSIX-compliant systems (*nix), we use the <regex.h> library,
7363 // which uses the POSIX extended regex syntax.
7364 //
7365 // On other platforms (e.g. Windows or Mac), we only support a simple regex
7366 // syntax implemented as part of Google Test. This limited
7367 // implementation should be enough most of the time when writing
7368 // death tests; though it lacks many features you can find in PCRE
7369 // or POSIX extended regex syntax. For example, we don't support
7370 // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
7371 // repetition count ("x{5,7}"), among others.
7372 //
7373 // Below is the syntax that we do support. We chose it to be a
7374 // subset of both PCRE and POSIX extended regex, so it's easy to
7375 // learn wherever you come from. In the following: 'A' denotes a
7376 // literal character, period (.), or a single \\ escape sequence;
7377 // 'x' and 'y' denote regular expressions; 'm' and 'n' are for
7378 // natural numbers.
7379 //
7380 // c matches any literal character c
7381 // \\d matches any decimal digit
7382 // \\D matches any character that's not a decimal digit
7383 // \\f matches \f
7384 // \\n matches \n
7385 // \\r matches \r
7386 // \\s matches any ASCII whitespace, including \n
7387 // \\S matches any character that's not a whitespace
7388 // \\t matches \t
7389 // \\v matches \v
7390 // \\w matches any letter, _, or decimal digit
7391 // \\W matches any character that \\w doesn't match
7392 // \\c matches any literal character c, which must be a punctuation
7393 // . matches any single character except \n
7394 // A? matches 0 or 1 occurrences of A
7395 // A* matches 0 or many occurrences of A
7396 // A+ matches 1 or many occurrences of A
7397 // ^ matches the beginning of a string (not that of each line)
7398 // $ matches the end of a string (not that of each line)
7399 // xy matches x followed by y
7400 //
7401 // If you accidentally use PCRE or POSIX extended regex features
7402 // not implemented by us, you will get a run-time failure. In that
7403 // case, please try to rewrite your regular expression within the
7404 // above syntax.
7405 //
7406 // This implementation is *not* meant to be as highly tuned or robust
7407 // as a compiled regex library, but should perform well enough for a
7408 // death test, which already incurs significant overhead by launching
7409 // a child process.
7410 //
7411 // Known caveats:
7412 //
7413 // A "threadsafe" style death test obtains the path to the test
7414 // program from argv[0] and re-executes it in the sub-process. For
7415 // simplicity, the current implementation doesn't search the PATH
7416 // when launching the sub-process. This means that the user must
7417 // invoke the test program via a path that contains at least one
7418 // path separator (e.g. path/to/foo_test and
7419 // /absolute/path/to/bar_test are fine, but foo_test is not). This
7420 // is rarely a problem as people usually don't put the test binary
7421 // directory in PATH.
7422 //
7423
7424 // Asserts that a given statement causes the program to exit, with an
7425 // integer exit status that satisfies predicate, and emitting error output
7426 // that matches regex.
7427 # define ASSERT_EXIT(statement, predicate, regex) \
7428 GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
7429
7430 // Like ASSERT_EXIT, but continues on to successive tests in the
7431 // test suite, if any:
7432 # define EXPECT_EXIT(statement, predicate, regex) \
7433 GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_)
7434
7435 // Asserts that a given statement causes the program to exit, either by
7436 // explicitly exiting with a nonzero exit code or being killed by a
7437 // signal, and emitting error output that matches regex.
7438 # define ASSERT_DEATH(statement, regex) \
7439 ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
7440
7441 // Like ASSERT_DEATH, but continues on to successive tests in the
7442 // test suite, if any:
7443 # define EXPECT_DEATH(statement, regex) \
7444 EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
7445
7446 // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
7447
7448 // Tests that an exit code describes a normal exit with a given exit code.
7449 class GTEST_API_ ExitedWithCode {
7450 public:
7451 explicit ExitedWithCode(int exit_code);
7452 ExitedWithCode(const ExitedWithCode&) = default;
7453 void operator=(const ExitedWithCode& other) = delete;
7454 bool operator()(int exit_status) const;
7455 private:
7456 const int exit_code_;
7457 };
7458
7459 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7460 // Tests that an exit code describes an exit due to termination by a
7461 // given signal.
7462 // GOOGLETEST_CM0006 DO NOT DELETE
7463 class GTEST_API_ KilledBySignal {
7464 public:
7465 explicit KilledBySignal(int signum);
7466 bool operator()(int exit_status) const;
7467 private:
7468 const int signum_;
7469 };
7470 # endif // !GTEST_OS_WINDOWS
7471
7472 // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
7473 // The death testing framework causes this to have interesting semantics,
7474 // since the sideeffects of the call are only visible in opt mode, and not
7475 // in debug mode.
7476 //
7477 // In practice, this can be used to test functions that utilize the
7478 // LOG(DFATAL) macro using the following style:
7479 //
7480 // int DieInDebugOr12(int* sideeffect) {
7481 // if (sideeffect) {
7482 // *sideeffect = 12;
7483 // }
7484 // LOG(DFATAL) << "death";
7485 // return 12;
7486 // }
7487 //
7488 // TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
7489 // int sideeffect = 0;
7490 // // Only asserts in dbg.
7491 // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
7492 //
7493 // #ifdef NDEBUG
7494 // // opt-mode has sideeffect visible.
7495 // EXPECT_EQ(12, sideeffect);
7496 // #else
7497 // // dbg-mode no visible sideeffect.
7498 // EXPECT_EQ(0, sideeffect);
7499 // #endif
7500 // }
7501 //
7502 // This will assert that DieInDebugReturn12InOpt() crashes in debug
7503 // mode, usually due to a DCHECK or LOG(DFATAL), but returns the
7504 // appropriate fallback value (12 in this case) in opt mode. If you
7505 // need to test that a function has appropriate side-effects in opt
7506 // mode, include assertions against the side-effects. A general
7507 // pattern for this is:
7508 //
7509 // EXPECT_DEBUG_DEATH({
7510 // // Side-effects here will have an effect after this statement in
7511 // // opt mode, but none in debug mode.
7512 // EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
7513 // }, "death");
7514 //
7515 # ifdef NDEBUG
7516
7517 # define EXPECT_DEBUG_DEATH(statement, regex) \
7518 GTEST_EXECUTE_STATEMENT_(statement, regex)
7519
7520 # define ASSERT_DEBUG_DEATH(statement, regex) \
7521 GTEST_EXECUTE_STATEMENT_(statement, regex)
7522
7523 # else
7524
7525 # define EXPECT_DEBUG_DEATH(statement, regex) \
7526 EXPECT_DEATH(statement, regex)
7527
7528 # define ASSERT_DEBUG_DEATH(statement, regex) \
7529 ASSERT_DEATH(statement, regex)
7530
7531 # endif // NDEBUG for EXPECT_DEBUG_DEATH
7532 #endif // GTEST_HAS_DEATH_TEST
7533
7534 // This macro is used for implementing macros such as
7535 // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
7536 // death tests are not supported. Those macros must compile on such systems
7537 // if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
7538 // on systems that support death tests. This allows one to write such a macro on
7539 // a system that does not support death tests and be sure that it will compile
7540 // on a death-test supporting system. It is exposed publicly so that systems
7541 // that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
7542 // can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
7543 // ASSERT_DEATH_IF_SUPPORTED.
7544 //
7545 // Parameters:
7546 // statement - A statement that a macro such as EXPECT_DEATH would test
7547 // for program termination. This macro has to make sure this
7548 // statement is compiled but not executed, to ensure that
7549 // EXPECT_DEATH_IF_SUPPORTED compiles with a certain
7550 // parameter if and only if EXPECT_DEATH compiles with it.
7551 // regex - A regex that a macro such as EXPECT_DEATH would use to test
7552 // the output of statement. This parameter has to be
7553 // compiled but not evaluated by this macro, to ensure that
7554 // this macro only accepts expressions that a macro such as
7555 // EXPECT_DEATH would accept.
7556 // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
7557 // and a return statement for ASSERT_DEATH_IF_SUPPORTED.
7558 // This ensures that ASSERT_DEATH_IF_SUPPORTED will not
7559 // compile inside functions where ASSERT_DEATH doesn't
7560 // compile.
7561 //
7562 // The branch that has an always false condition is used to ensure that
7563 // statement and regex are compiled (and thus syntactically correct) but
7564 // never executed. The unreachable code macro protects the terminator
7565 // statement from generating an 'unreachable code' warning in case
7566 // statement unconditionally returns or throws. The Message constructor at
7567 // the end allows the syntax of streaming additional messages into the
7568 // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
7569 # define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
7570 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7571 if (::testing::internal::AlwaysTrue()) { \
7572 GTEST_LOG_(WARNING) \
7573 << "Death tests are not supported on this platform.\n" \
7574 << "Statement '" #statement "' cannot be verified."; \
7575 } else if (::testing::internal::AlwaysFalse()) { \
7576 ::testing::internal::RE::PartialMatch(".*", (regex)); \
7577 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7578 terminator; \
7579 } else \
7580 ::testing::Message()
7581
7582 // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
7583 // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
7584 // death tests are supported; otherwise they just issue a warning. This is
7585 // useful when you are combining death test assertions with normal test
7586 // assertions in one test.
7587 #if GTEST_HAS_DEATH_TEST
7588 # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
7589 EXPECT_DEATH(statement, regex)
7590 # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
7591 ASSERT_DEATH(statement, regex)
7592 #else
7593 # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
7594 GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
7595 # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
7596 GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
7597 #endif
7598
7599 } // namespace testing
7600
7601 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
7602 // Copyright 2008, Google Inc.
7603 // All rights reserved.
7604 //
7605 // Redistribution and use in source and binary forms, with or without
7606 // modification, are permitted provided that the following conditions are
7607 // met:
7608 //
7609 // * Redistributions of source code must retain the above copyright
7610 // notice, this list of conditions and the following disclaimer.
7611 // * Redistributions in binary form must reproduce the above
7612 // copyright notice, this list of conditions and the following disclaimer
7613 // in the documentation and/or other materials provided with the
7614 // distribution.
7615 // * Neither the name of Google Inc. nor the names of its
7616 // contributors may be used to endorse or promote products derived from
7617 // this software without specific prior written permission.
7618 //
7619 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7620 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7621 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7622 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7623 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7624 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7625 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7626 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7627 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7628 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7629 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7630 //
7631 // Macros and functions for implementing parameterized tests
7632 // in Google C++ Testing and Mocking Framework (Google Test)
7633 //
7634 // GOOGLETEST_CM0001 DO NOT DELETE
7635 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
7636 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
7637
7638 // Value-parameterized tests allow you to test your code with different
7639 // parameters without writing multiple copies of the same test.
7640 //
7641 // Here is how you use value-parameterized tests:
7642
7643 #if 0
7644
7645 // To write value-parameterized tests, first you should define a fixture
7646 // class. It is usually derived from testing::TestWithParam<T> (see below for
7647 // another inheritance scheme that's sometimes useful in more complicated
7648 // class hierarchies), where the type of your parameter values.
7649 // TestWithParam<T> is itself derived from testing::Test. T can be any
7650 // copyable type. If it's a raw pointer, you are responsible for managing the
7651 // lifespan of the pointed values.
7652
7653 class FooTest : public ::testing::TestWithParam<const char*> {
7654 // You can implement all the usual class fixture members here.
7655 };
7656
7657 // Then, use the TEST_P macro to define as many parameterized tests
7658 // for this fixture as you want. The _P suffix is for "parameterized"
7659 // or "pattern", whichever you prefer to think.
7660
7661 TEST_P(FooTest, DoesBlah) {
7662 // Inside a test, access the test parameter with the GetParam() method
7663 // of the TestWithParam<T> class:
7664 EXPECT_TRUE(foo.Blah(GetParam()));
7665 ...
7666 }
7667
7668 TEST_P(FooTest, HasBlahBlah) {
7669 ...
7670 }
7671
7672 // Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test
7673 // case with any set of parameters you want. Google Test defines a number
7674 // of functions for generating test parameters. They return what we call
7675 // (surprise!) parameter generators. Here is a summary of them, which
7676 // are all in the testing namespace:
7677 //
7678 //
7679 // Range(begin, end [, step]) - Yields values {begin, begin+step,
7680 // begin+step+step, ...}. The values do not
7681 // include end. step defaults to 1.
7682 // Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}.
7683 // ValuesIn(container) - Yields values from a C-style array, an STL
7684 // ValuesIn(begin,end) container, or an iterator range [begin, end).
7685 // Bool() - Yields sequence {false, true}.
7686 // Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product
7687 // for the math savvy) of the values generated
7688 // by the N generators.
7689 //
7690 // For more details, see comments at the definitions of these functions below
7691 // in this file.
7692 //
7693 // The following statement will instantiate tests from the FooTest test suite
7694 // each with parameter values "meeny", "miny", and "moe".
7695
7696 INSTANTIATE_TEST_SUITE_P(InstantiationName,
7697 FooTest,
7698 Values("meeny", "miny", "moe"));
7699
7700 // To distinguish different instances of the pattern, (yes, you
7701 // can instantiate it more than once) the first argument to the
7702 // INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
7703 // actual test suite name. Remember to pick unique prefixes for different
7704 // instantiations. The tests from the instantiation above will have
7705 // these names:
7706 //
7707 // * InstantiationName/FooTest.DoesBlah/0 for "meeny"
7708 // * InstantiationName/FooTest.DoesBlah/1 for "miny"
7709 // * InstantiationName/FooTest.DoesBlah/2 for "moe"
7710 // * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
7711 // * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
7712 // * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
7713 //
7714 // You can use these names in --gtest_filter.
7715 //
7716 // This statement will instantiate all tests from FooTest again, each
7717 // with parameter values "cat" and "dog":
7718
7719 const char* pets[] = {"cat", "dog"};
7720 INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
7721
7722 // The tests from the instantiation above will have these names:
7723 //
7724 // * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
7725 // * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
7726 // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
7727 // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
7728 //
7729 // Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests
7730 // in the given test suite, whether their definitions come before or
7731 // AFTER the INSTANTIATE_TEST_SUITE_P statement.
7732 //
7733 // Please also note that generator expressions (including parameters to the
7734 // generators) are evaluated in InitGoogleTest(), after main() has started.
7735 // This allows the user on one hand, to adjust generator parameters in order
7736 // to dynamically determine a set of tests to run and on the other hand,
7737 // give the user a chance to inspect the generated tests with Google Test
7738 // reflection API before RUN_ALL_TESTS() is executed.
7739 //
7740 // You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
7741 // for more examples.
7742 //
7743 // In the future, we plan to publish the API for defining new parameter
7744 // generators. But for now this interface remains part of the internal
7745 // implementation and is subject to change.
7746 //
7747 //
7748 // A parameterized test fixture must be derived from testing::Test and from
7749 // testing::WithParamInterface<T>, where T is the type of the parameter
7750 // values. Inheriting from TestWithParam<T> satisfies that requirement because
7751 // TestWithParam<T> inherits from both Test and WithParamInterface. In more
7752 // complicated hierarchies, however, it is occasionally useful to inherit
7753 // separately from Test and WithParamInterface. For example:
7754
7755 class BaseTest : public ::testing::Test {
7756 // You can inherit all the usual members for a non-parameterized test
7757 // fixture here.
7758 };
7759
7760 class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
7761 // The usual test fixture members go here too.
7762 };
7763
7764 TEST_F(BaseTest, HasFoo) {
7765 // This is an ordinary non-parameterized test.
7766 }
7767
7768 TEST_P(DerivedTest, DoesBlah) {
7769 // GetParam works just the same here as if you inherit from TestWithParam.
7770 EXPECT_TRUE(foo.Blah(GetParam()));
7771 }
7772
7773 #endif // 0
7774
7775 #include <iterator>
7776 #include <utility>
7777
7778 // Copyright 2008 Google Inc.
7779 // All Rights Reserved.
7780 //
7781 // Redistribution and use in source and binary forms, with or without
7782 // modification, are permitted provided that the following conditions are
7783 // met:
7784 //
7785 // * Redistributions of source code must retain the above copyright
7786 // notice, this list of conditions and the following disclaimer.
7787 // * Redistributions in binary form must reproduce the above
7788 // copyright notice, this list of conditions and the following disclaimer
7789 // in the documentation and/or other materials provided with the
7790 // distribution.
7791 // * Neither the name of Google Inc. nor the names of its
7792 // contributors may be used to endorse or promote products derived from
7793 // this software without specific prior written permission.
7794 //
7795 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7796 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7797 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7798 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7799 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7800 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7801 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7802 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7803 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7804 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7805 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7806
7807
7808 // Type and function utilities for implementing parameterized tests.
7809
7810 // GOOGLETEST_CM0001 DO NOT DELETE
7811
7812 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
7813 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
7814
7815 #include <ctype.h>
7816
7817 #include <cassert>
7818 #include <iterator>
7819 #include <memory>
7820 #include <set>
7821 #include <tuple>
7822 #include <type_traits>
7823 #include <utility>
7824 #include <vector>
7825
7826 // Copyright 2008, Google Inc.
7827 // All rights reserved.
7828 //
7829 // Redistribution and use in source and binary forms, with or without
7830 // modification, are permitted provided that the following conditions are
7831 // met:
7832 //
7833 // * Redistributions of source code must retain the above copyright
7834 // notice, this list of conditions and the following disclaimer.
7835 // * Redistributions in binary form must reproduce the above
7836 // copyright notice, this list of conditions and the following disclaimer
7837 // in the documentation and/or other materials provided with the
7838 // distribution.
7839 // * Neither the name of Google Inc. nor the names of its
7840 // contributors may be used to endorse or promote products derived from
7841 // this software without specific prior written permission.
7842 //
7843 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7844 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7845 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7846 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7847 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7848 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7849 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7850 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7851 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7852 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7853 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7854 //
7855 // GOOGLETEST_CM0001 DO NOT DELETE
7856
7857 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7858 #define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7859
7860 #include <iosfwd>
7861 #include <vector>
7862
7863 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
7864 /* class A needs to have dll-interface to be used by clients of class B */)
7865
7866 namespace testing {
7867
7868 // A copyable object representing the result of a test part (i.e. an
7869 // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
7870 //
7871 // Don't inherit from TestPartResult as its destructor is not virtual.
7872 class GTEST_API_ TestPartResult {
7873 public:
7874 // The possible outcomes of a test part (i.e. an assertion or an
7875 // explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
7876 enum Type {
7877 kSuccess, // Succeeded.
7878 kNonFatalFailure, // Failed but the test can continue.
7879 kFatalFailure, // Failed and the test should be terminated.
7880 kSkip // Skipped.
7881 };
7882
7883 // C'tor. TestPartResult does NOT have a default constructor.
7884 // Always use this constructor (with parameters) to create a
7885 // TestPartResult object.
7886 TestPartResult(Type a_type, const char* a_file_name, int a_line_number,
7887 const char* a_message)
7888 : type_(a_type),
7889 file_name_(a_file_name == nullptr ? "" : a_file_name),
7890 line_number_(a_line_number),
7891 summary_(ExtractSummary(a_message)),
7892 message_(a_message) {}
7893
7894 // Gets the outcome of the test part.
7895 Type type() const { return type_; }
7896
7897 // Gets the name of the source file where the test part took place, or
7898 // NULL if it's unknown.
7899 const char* file_name() const {
7900 return file_name_.empty() ? nullptr : file_name_.c_str();
7901 }
7902
7903 // Gets the line in the source file where the test part took place,
7904 // or -1 if it's unknown.
7905 int line_number() const { return line_number_; }
7906
7907 // Gets the summary of the failure message.
7908 const char* summary() const { return summary_.c_str(); }
7909
7910 // Gets the message associated with the test part.
7911 const char* message() const { return message_.c_str(); }
7912
7913 // Returns true if and only if the test part was skipped.
7914 bool skipped() const { return type_ == kSkip; }
7915
7916 // Returns true if and only if the test part passed.
7917 bool passed() const { return type_ == kSuccess; }
7918
7919 // Returns true if and only if the test part non-fatally failed.
7920 bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
7921
7922 // Returns true if and only if the test part fatally failed.
7923 bool fatally_failed() const { return type_ == kFatalFailure; }
7924
7925 // Returns true if and only if the test part failed.
7926 bool failed() const { return fatally_failed() || nonfatally_failed(); }
7927
7928 private:
7929 Type type_;
7930
7931 // Gets the summary of the failure message by omitting the stack
7932 // trace in it.
7933 static std::string ExtractSummary(const char* message);
7934
7935 // The name of the source file where the test part took place, or
7936 // "" if the source file is unknown.
7937 std::string file_name_;
7938 // The line in the source file where the test part took place, or -1
7939 // if the line number is unknown.
7940 int line_number_;
7941 std::string summary_; // The test failure summary.
7942 std::string message_; // The test failure message.
7943 };
7944
7945 // Prints a TestPartResult object.
7946 std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
7947
7948 // An array of TestPartResult objects.
7949 //
7950 // Don't inherit from TestPartResultArray as its destructor is not
7951 // virtual.
7952 class GTEST_API_ TestPartResultArray {
7953 public:
7954 TestPartResultArray() {}
7955
7956 // Appends the given TestPartResult to the array.
7957 void Append(const TestPartResult& result);
7958
7959 // Returns the TestPartResult at the given index (0-based).
7960 const TestPartResult& GetTestPartResult(int index) const;
7961
7962 // Returns the number of TestPartResult objects in the array.
7963 int size() const;
7964
7965 private:
7966 std::vector<TestPartResult> array_;
7967
7968 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
7969 };
7970
7971 // This interface knows how to report a test part result.
7972 class GTEST_API_ TestPartResultReporterInterface {
7973 public:
7974 virtual ~TestPartResultReporterInterface() {}
7975
7976 virtual void ReportTestPartResult(const TestPartResult& result) = 0;
7977 };
7978
7979 namespace internal {
7980
7981 // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
7982 // statement generates new fatal failures. To do so it registers itself as the
7983 // current test part result reporter. Besides checking if fatal failures were
7984 // reported, it only delegates the reporting to the former result reporter.
7985 // The original result reporter is restored in the destructor.
7986 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
7987 class GTEST_API_ HasNewFatalFailureHelper
7988 : public TestPartResultReporterInterface {
7989 public:
7990 HasNewFatalFailureHelper();
7991 ~HasNewFatalFailureHelper() override;
7992 void ReportTestPartResult(const TestPartResult& result) override;
7993 bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
7994 private:
7995 bool has_new_fatal_failure_;
7996 TestPartResultReporterInterface* original_reporter_;
7997
7998 GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
7999 };
8000
8001 } // namespace internal
8002
8003 } // namespace testing
8004
8005 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
8006
8007 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
8008
8009 namespace testing {
8010 // Input to a parameterized test name generator, describing a test parameter.
8011 // Consists of the parameter value and the integer parameter index.
8012 template <class ParamType>
8013 struct TestParamInfo {
8014 TestParamInfo(const ParamType& a_param, size_t an_index) :
8015 param(a_param),
8016 index(an_index) {}
8017 ParamType param;
8018 size_t index;
8019 };
8020
8021 // A builtin parameterized test name generator which returns the result of
8022 // testing::PrintToString.
8023 struct PrintToStringParamName {
8024 template <class ParamType>
8025 std::string operator()(const TestParamInfo<ParamType>& info) const {
8026 return PrintToString(info.param);
8027 }
8028 };
8029
8030 namespace internal {
8031
8032 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8033 // Utility Functions
8034
8035 // Outputs a message explaining invalid registration of different
8036 // fixture class for the same test suite. This may happen when
8037 // TEST_P macro is used to define two tests with the same name
8038 // but in different namespaces.
8039 GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
8040 CodeLocation code_location);
8041
8042 template <typename> class ParamGeneratorInterface;
8043 template <typename> class ParamGenerator;
8044
8045 // Interface for iterating over elements provided by an implementation
8046 // of ParamGeneratorInterface<T>.
8047 template <typename T>
8048 class ParamIteratorInterface {
8049 public:
8050 virtual ~ParamIteratorInterface() {}
8051 // A pointer to the base generator instance.
8052 // Used only for the purposes of iterator comparison
8053 // to make sure that two iterators belong to the same generator.
8054 virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
8055 // Advances iterator to point to the next element
8056 // provided by the generator. The caller is responsible
8057 // for not calling Advance() on an iterator equal to
8058 // BaseGenerator()->End().
8059 virtual void Advance() = 0;
8060 // Clones the iterator object. Used for implementing copy semantics
8061 // of ParamIterator<T>.
8062 virtual ParamIteratorInterface* Clone() const = 0;
8063 // Dereferences the current iterator and provides (read-only) access
8064 // to the pointed value. It is the caller's responsibility not to call
8065 // Current() on an iterator equal to BaseGenerator()->End().
8066 // Used for implementing ParamGenerator<T>::operator*().
8067 virtual const T* Current() const = 0;
8068 // Determines whether the given iterator and other point to the same
8069 // element in the sequence generated by the generator.
8070 // Used for implementing ParamGenerator<T>::operator==().
8071 virtual bool Equals(const ParamIteratorInterface& other) const = 0;
8072 };
8073
8074 // Class iterating over elements provided by an implementation of
8075 // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
8076 // and implements the const forward iterator concept.
8077 template <typename T>
8078 class ParamIterator {
8079 public:
8080 typedef T value_type;
8081 typedef const T& reference;
8082 typedef ptrdiff_t difference_type;
8083
8084 // ParamIterator assumes ownership of the impl_ pointer.
8085 ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
8086 ParamIterator& operator=(const ParamIterator& other) {
8087 if (this != &other)
8088 impl_.reset(other.impl_->Clone());
8089 return *this;
8090 }
8091
8092 const T& operator*() const { return *impl_->Current(); }
8093 const T* operator->() const { return impl_->Current(); }
8094 // Prefix version of operator++.
8095 ParamIterator& operator++() {
8096 impl_->Advance();
8097 return *this;
8098 }
8099 // Postfix version of operator++.
8100 ParamIterator operator++(int /*unused*/) {
8101 ParamIteratorInterface<T>* clone = impl_->Clone();
8102 impl_->Advance();
8103 return ParamIterator(clone);
8104 }
8105 bool operator==(const ParamIterator& other) const {
8106 return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
8107 }
8108 bool operator!=(const ParamIterator& other) const {
8109 return !(*this == other);
8110 }
8111
8112 private:
8113 friend class ParamGenerator<T>;
8114 explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
8115 std::unique_ptr<ParamIteratorInterface<T> > impl_;
8116 };
8117
8118 // ParamGeneratorInterface<T> is the binary interface to access generators
8119 // defined in other translation units.
8120 template <typename T>
8121 class ParamGeneratorInterface {
8122 public:
8123 typedef T ParamType;
8124
8125 virtual ~ParamGeneratorInterface() {}
8126
8127 // Generator interface definition
8128 virtual ParamIteratorInterface<T>* Begin() const = 0;
8129 virtual ParamIteratorInterface<T>* End() const = 0;
8130 };
8131
8132 // Wraps ParamGeneratorInterface<T> and provides general generator syntax
8133 // compatible with the STL Container concept.
8134 // This class implements copy initialization semantics and the contained
8135 // ParamGeneratorInterface<T> instance is shared among all copies
8136 // of the original object. This is possible because that instance is immutable.
8137 template<typename T>
8138 class ParamGenerator {
8139 public:
8140 typedef ParamIterator<T> iterator;
8141
8142 explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
8143 ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
8144
8145 ParamGenerator& operator=(const ParamGenerator& other) {
8146 impl_ = other.impl_;
8147 return *this;
8148 }
8149
8150 iterator begin() const { return iterator(impl_->Begin()); }
8151 iterator end() const { return iterator(impl_->End()); }
8152
8153 private:
8154 std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
8155 };
8156
8157 // Generates values from a range of two comparable values. Can be used to
8158 // generate sequences of user-defined types that implement operator+() and
8159 // operator<().
8160 // This class is used in the Range() function.
8161 template <typename T, typename IncrementT>
8162 class RangeGenerator : public ParamGeneratorInterface<T> {
8163 public:
8164 RangeGenerator(T begin, T end, IncrementT step)
8165 : begin_(begin), end_(end),
8166 step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
8167 ~RangeGenerator() override {}
8168
8169 ParamIteratorInterface<T>* Begin() const override {
8170 return new Iterator(this, begin_, 0, step_);
8171 }
8172 ParamIteratorInterface<T>* End() const override {
8173 return new Iterator(this, end_, end_index_, step_);
8174 }
8175
8176 private:
8177 class Iterator : public ParamIteratorInterface<T> {
8178 public:
8179 Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
8180 IncrementT step)
8181 : base_(base), value_(value), index_(index), step_(step) {}
8182 ~Iterator() override {}
8183
8184 const ParamGeneratorInterface<T>* BaseGenerator() const override {
8185 return base_;
8186 }
8187 void Advance() override {
8188 value_ = static_cast<T>(value_ + step_);
8189 index_++;
8190 }
8191 ParamIteratorInterface<T>* Clone() const override {
8192 return new Iterator(*this);
8193 }
8194 const T* Current() const override { return &value_; }
8195 bool Equals(const ParamIteratorInterface<T>& other) const override {
8196 // Having the same base generator guarantees that the other
8197 // iterator is of the same type and we can downcast.
8198 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8199 << "The program attempted to compare iterators "
8200 << "from different generators." << std::endl;
8201 const int other_index =
8202 CheckedDowncastToActualType<const Iterator>(&other)->index_;
8203 return index_ == other_index;
8204 }
8205
8206 private:
8207 Iterator(const Iterator& other)
8208 : ParamIteratorInterface<T>(),
8209 base_(other.base_), value_(other.value_), index_(other.index_),
8210 step_(other.step_) {}
8211
8212 // No implementation - assignment is unsupported.
8213 void operator=(const Iterator& other);
8214
8215 const ParamGeneratorInterface<T>* const base_;
8216 T value_;
8217 int index_;
8218 const IncrementT step_;
8219 }; // class RangeGenerator::Iterator
8220
8221 static int CalculateEndIndex(const T& begin,
8222 const T& end,
8223 const IncrementT& step) {
8224 int end_index = 0;
8225 for (T i = begin; i < end; i = static_cast<T>(i + step))
8226 end_index++;
8227 return end_index;
8228 }
8229
8230 // No implementation - assignment is unsupported.
8231 void operator=(const RangeGenerator& other);
8232
8233 const T begin_;
8234 const T end_;
8235 const IncrementT step_;
8236 // The index for the end() iterator. All the elements in the generated
8237 // sequence are indexed (0-based) to aid iterator comparison.
8238 const int end_index_;
8239 }; // class RangeGenerator
8240
8241
8242 // Generates values from a pair of STL-style iterators. Used in the
8243 // ValuesIn() function. The elements are copied from the source range
8244 // since the source can be located on the stack, and the generator
8245 // is likely to persist beyond that stack frame.
8246 template <typename T>
8247 class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
8248 public:
8249 template <typename ForwardIterator>
8250 ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
8251 : container_(begin, end) {}
8252 ~ValuesInIteratorRangeGenerator() override {}
8253
8254 ParamIteratorInterface<T>* Begin() const override {
8255 return new Iterator(this, container_.begin());
8256 }
8257 ParamIteratorInterface<T>* End() const override {
8258 return new Iterator(this, container_.end());
8259 }
8260
8261 private:
8262 typedef typename ::std::vector<T> ContainerType;
8263
8264 class Iterator : public ParamIteratorInterface<T> {
8265 public:
8266 Iterator(const ParamGeneratorInterface<T>* base,
8267 typename ContainerType::const_iterator iterator)
8268 : base_(base), iterator_(iterator) {}
8269 ~Iterator() override {}
8270
8271 const ParamGeneratorInterface<T>* BaseGenerator() const override {
8272 return base_;
8273 }
8274 void Advance() override {
8275 ++iterator_;
8276 value_.reset();
8277 }
8278 ParamIteratorInterface<T>* Clone() const override {
8279 return new Iterator(*this);
8280 }
8281 // We need to use cached value referenced by iterator_ because *iterator_
8282 // can return a temporary object (and of type other then T), so just
8283 // having "return &*iterator_;" doesn't work.
8284 // value_ is updated here and not in Advance() because Advance()
8285 // can advance iterator_ beyond the end of the range, and we cannot
8286 // detect that fact. The client code, on the other hand, is
8287 // responsible for not calling Current() on an out-of-range iterator.
8288 const T* Current() const override {
8289 if (value_.get() == nullptr) value_.reset(new T(*iterator_));
8290 return value_.get();
8291 }
8292 bool Equals(const ParamIteratorInterface<T>& other) const override {
8293 // Having the same base generator guarantees that the other
8294 // iterator is of the same type and we can downcast.
8295 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8296 << "The program attempted to compare iterators "
8297 << "from different generators." << std::endl;
8298 return iterator_ ==
8299 CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
8300 }
8301
8302 private:
8303 Iterator(const Iterator& other)
8304 // The explicit constructor call suppresses a false warning
8305 // emitted by gcc when supplied with the -Wextra option.
8306 : ParamIteratorInterface<T>(),
8307 base_(other.base_),
8308 iterator_(other.iterator_) {}
8309
8310 const ParamGeneratorInterface<T>* const base_;
8311 typename ContainerType::const_iterator iterator_;
8312 // A cached value of *iterator_. We keep it here to allow access by
8313 // pointer in the wrapping iterator's operator->().
8314 // value_ needs to be mutable to be accessed in Current().
8315 // Use of std::unique_ptr helps manage cached value's lifetime,
8316 // which is bound by the lifespan of the iterator itself.
8317 mutable std::unique_ptr<const T> value_;
8318 }; // class ValuesInIteratorRangeGenerator::Iterator
8319
8320 // No implementation - assignment is unsupported.
8321 void operator=(const ValuesInIteratorRangeGenerator& other);
8322
8323 const ContainerType container_;
8324 }; // class ValuesInIteratorRangeGenerator
8325
8326 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8327 //
8328 // Default parameterized test name generator, returns a string containing the
8329 // integer test parameter index.
8330 template <class ParamType>
8331 std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
8332 Message name_stream;
8333 name_stream << info.index;
8334 return name_stream.GetString();
8335 }
8336
8337 template <typename T = int>
8338 void TestNotEmpty() {
8339 static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");
8340 }
8341 template <typename T = int>
8342 void TestNotEmpty(const T&) {}
8343
8344 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8345 //
8346 // Stores a parameter value and later creates tests parameterized with that
8347 // value.
8348 template <class TestClass>
8349 class ParameterizedTestFactory : public TestFactoryBase {
8350 public:
8351 typedef typename TestClass::ParamType ParamType;
8352 explicit ParameterizedTestFactory(ParamType parameter) :
8353 parameter_(parameter) {}
8354 Test* CreateTest() override {
8355 TestClass::SetParam(&parameter_);
8356 return new TestClass();
8357 }
8358
8359 private:
8360 const ParamType parameter_;
8361
8362 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
8363 };
8364
8365 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8366 //
8367 // TestMetaFactoryBase is a base class for meta-factories that create
8368 // test factories for passing into MakeAndRegisterTestInfo function.
8369 template <class ParamType>
8370 class TestMetaFactoryBase {
8371 public:
8372 virtual ~TestMetaFactoryBase() {}
8373
8374 virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
8375 };
8376
8377 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8378 //
8379 // TestMetaFactory creates test factories for passing into
8380 // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
8381 // ownership of test factory pointer, same factory object cannot be passed
8382 // into that method twice. But ParameterizedTestSuiteInfo is going to call
8383 // it for each Test/Parameter value combination. Thus it needs meta factory
8384 // creator class.
8385 template <class TestSuite>
8386 class TestMetaFactory
8387 : public TestMetaFactoryBase<typename TestSuite::ParamType> {
8388 public:
8389 using ParamType = typename TestSuite::ParamType;
8390
8391 TestMetaFactory() {}
8392
8393 TestFactoryBase* CreateTestFactory(ParamType parameter) override {
8394 return new ParameterizedTestFactory<TestSuite>(parameter);
8395 }
8396
8397 private:
8398 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
8399 };
8400
8401 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8402 //
8403 // ParameterizedTestSuiteInfoBase is a generic interface
8404 // to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase
8405 // accumulates test information provided by TEST_P macro invocations
8406 // and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations
8407 // and uses that information to register all resulting test instances
8408 // in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
8409 // a collection of pointers to the ParameterizedTestSuiteInfo objects
8410 // and calls RegisterTests() on each of them when asked.
8411 class ParameterizedTestSuiteInfoBase {
8412 public:
8413 virtual ~ParameterizedTestSuiteInfoBase() {}
8414
8415 // Base part of test suite name for display purposes.
8416 virtual const std::string& GetTestSuiteName() const = 0;
8417 // Test suite id to verify identity.
8418 virtual TypeId GetTestSuiteTypeId() const = 0;
8419 // UnitTest class invokes this method to register tests in this
8420 // test suite right before running them in RUN_ALL_TESTS macro.
8421 // This method should not be called more than once on any single
8422 // instance of a ParameterizedTestSuiteInfoBase derived class.
8423 virtual void RegisterTests() = 0;
8424
8425 protected:
8426 ParameterizedTestSuiteInfoBase() {}
8427
8428 private:
8429 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
8430 };
8431
8432 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8433 //
8434 // Report a the name of a test_suit as safe to ignore
8435 // as the side effect of construction of this type.
8436 struct MarkAsIgnored {
8437 explicit MarkAsIgnored(const char* test_suite);
8438 };
8439
8440 GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
8441 CodeLocation location, bool has_test_p);
8442
8443 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8444 //
8445 // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
8446 // macro invocations for a particular test suite and generators
8447 // obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that
8448 // test suite. It registers tests with all values generated by all
8449 // generators when asked.
8450 template <class TestSuite>
8451 class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
8452 public:
8453 // ParamType and GeneratorCreationFunc are private types but are required
8454 // for declarations of public methods AddTestPattern() and
8455 // AddTestSuiteInstantiation().
8456 using ParamType = typename TestSuite::ParamType;
8457 // A function that returns an instance of appropriate generator type.
8458 typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
8459 using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
8460
8461 explicit ParameterizedTestSuiteInfo(const char* name,
8462 CodeLocation code_location)
8463 : test_suite_name_(name), code_location_(code_location) {}
8464
8465 // Test suite base name for display purposes.
8466 const std::string& GetTestSuiteName() const override {
8467 return test_suite_name_;
8468 }
8469 // Test suite id to verify identity.
8470 TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
8471 // TEST_P macro uses AddTestPattern() to record information
8472 // about a single test in a LocalTestInfo structure.
8473 // test_suite_name is the base name of the test suite (without invocation
8474 // prefix). test_base_name is the name of an individual test without
8475 // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
8476 // test suite base name and DoBar is test base name.
8477 void AddTestPattern(const char* test_suite_name, const char* test_base_name,
8478 TestMetaFactoryBase<ParamType>* meta_factory,
8479 CodeLocation code_location) {
8480 tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
8481 test_suite_name, test_base_name, meta_factory, code_location)));
8482 }
8483 // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
8484 // about a generator.
8485 int AddTestSuiteInstantiation(const std::string& instantiation_name,
8486 GeneratorCreationFunc* func,
8487 ParamNameGeneratorFunc* name_func,
8488 const char* file, int line) {
8489 instantiations_.push_back(
8490 InstantiationInfo(instantiation_name, func, name_func, file, line));
8491 return 0; // Return value used only to run this method in namespace scope.
8492 }
8493 // UnitTest class invokes this method to register tests in this test suite
8494 // right before running tests in RUN_ALL_TESTS macro.
8495 // This method should not be called more than once on any single
8496 // instance of a ParameterizedTestSuiteInfoBase derived class.
8497 // UnitTest has a guard to prevent from calling this method more than once.
8498 void RegisterTests() override {
8499 bool generated_instantiations = false;
8500
8501 for (typename TestInfoContainer::iterator test_it = tests_.begin();
8502 test_it != tests_.end(); ++test_it) {
8503 std::shared_ptr<TestInfo> test_info = *test_it;
8504 for (typename InstantiationContainer::iterator gen_it =
8505 instantiations_.begin(); gen_it != instantiations_.end();
8506 ++gen_it) {
8507 const std::string& instantiation_name = gen_it->name;
8508 ParamGenerator<ParamType> generator((*gen_it->generator)());
8509 ParamNameGeneratorFunc* name_func = gen_it->name_func;
8510 const char* file = gen_it->file;
8511 int line = gen_it->line;
8512
8513 std::string test_suite_name;
8514 if ( !instantiation_name.empty() )
8515 test_suite_name = instantiation_name + "/";
8516 test_suite_name += test_info->test_suite_base_name;
8517
8518 size_t i = 0;
8519 std::set<std::string> test_param_names;
8520 for (typename ParamGenerator<ParamType>::iterator param_it =
8521 generator.begin();
8522 param_it != generator.end(); ++param_it, ++i) {
8523 generated_instantiations = true;
8524
8525 Message test_name_stream;
8526
8527 std::string param_name = name_func(
8528 TestParamInfo<ParamType>(*param_it, i));
8529
8530 GTEST_CHECK_(IsValidParamName(param_name))
8531 << "Parameterized test name '" << param_name
8532 << "' is invalid, in " << file
8533 << " line " << line << std::endl;
8534
8535 GTEST_CHECK_(test_param_names.count(param_name) == 0)
8536 << "Duplicate parameterized test name '" << param_name
8537 << "', in " << file << " line " << line << std::endl;
8538
8539 test_param_names.insert(param_name);
8540
8541 if (!test_info->test_base_name.empty()) {
8542 test_name_stream << test_info->test_base_name << "/";
8543 }
8544 test_name_stream << param_name;
8545 MakeAndRegisterTestInfo(
8546 test_suite_name.c_str(), test_name_stream.GetString().c_str(),
8547 nullptr, // No type parameter.
8548 PrintToString(*param_it).c_str(), test_info->code_location,
8549 GetTestSuiteTypeId(),
8550 SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
8551 SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
8552 test_info->test_meta_factory->CreateTestFactory(*param_it));
8553 } // for param_it
8554 } // for gen_it
8555 } // for test_it
8556
8557 if (!generated_instantiations) {
8558 // There are no generaotrs, or they all generate nothing ...
8559 InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
8560 !tests_.empty());
8561 }
8562 } // RegisterTests
8563
8564 private:
8565 // LocalTestInfo structure keeps information about a single test registered
8566 // with TEST_P macro.
8567 struct TestInfo {
8568 TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
8569 TestMetaFactoryBase<ParamType>* a_test_meta_factory,
8570 CodeLocation a_code_location)
8571 : test_suite_base_name(a_test_suite_base_name),
8572 test_base_name(a_test_base_name),
8573 test_meta_factory(a_test_meta_factory),
8574 code_location(a_code_location) {}
8575
8576 const std::string test_suite_base_name;
8577 const std::string test_base_name;
8578 const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
8579 const CodeLocation code_location;
8580 };
8581 using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
8582 // Records data received from INSTANTIATE_TEST_SUITE_P macros:
8583 // <Instantiation name, Sequence generator creation function,
8584 // Name generator function, Source file, Source line>
8585 struct InstantiationInfo {
8586 InstantiationInfo(const std::string &name_in,
8587 GeneratorCreationFunc* generator_in,
8588 ParamNameGeneratorFunc* name_func_in,
8589 const char* file_in,
8590 int line_in)
8591 : name(name_in),
8592 generator(generator_in),
8593 name_func(name_func_in),
8594 file(file_in),
8595 line(line_in) {}
8596
8597 std::string name;
8598 GeneratorCreationFunc* generator;
8599 ParamNameGeneratorFunc* name_func;
8600 const char* file;
8601 int line;
8602 };
8603 typedef ::std::vector<InstantiationInfo> InstantiationContainer;
8604
8605 static bool IsValidParamName(const std::string& name) {
8606 // Check for empty string
8607 if (name.empty())
8608 return false;
8609
8610 // Check for invalid characters
8611 for (std::string::size_type index = 0; index < name.size(); ++index) {
8612 if (!isalnum(name[index]) && name[index] != '_')
8613 return false;
8614 }
8615
8616 return true;
8617 }
8618
8619 const std::string test_suite_name_;
8620 CodeLocation code_location_;
8621 TestInfoContainer tests_;
8622 InstantiationContainer instantiations_;
8623
8624 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
8625 }; // class ParameterizedTestSuiteInfo
8626
8627 // Legacy API is deprecated but still available
8628 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8629 template <class TestCase>
8630 using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
8631 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8632
8633 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8634 //
8635 // ParameterizedTestSuiteRegistry contains a map of
8636 // ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
8637 // and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
8638 // ParameterizedTestSuiteInfo descriptors.
8639 class ParameterizedTestSuiteRegistry {
8640 public:
8641 ParameterizedTestSuiteRegistry() {}
8642 ~ParameterizedTestSuiteRegistry() {
8643 for (auto& test_suite_info : test_suite_infos_) {
8644 delete test_suite_info;
8645 }
8646 }
8647
8648 // Looks up or creates and returns a structure containing information about
8649 // tests and instantiations of a particular test suite.
8650 template <class TestSuite>
8651 ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
8652 const char* test_suite_name, CodeLocation code_location) {
8653 ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
8654 for (auto& test_suite_info : test_suite_infos_) {
8655 if (test_suite_info->GetTestSuiteName() == test_suite_name) {
8656 if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
8657 // Complain about incorrect usage of Google Test facilities
8658 // and terminate the program since we cannot guaranty correct
8659 // test suite setup and tear-down in this case.
8660 ReportInvalidTestSuiteType(test_suite_name, code_location);
8661 posix::Abort();
8662 } else {
8663 // At this point we are sure that the object we found is of the same
8664 // type we are looking for, so we downcast it to that type
8665 // without further checks.
8666 typed_test_info = CheckedDowncastToActualType<
8667 ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
8668 }
8669 break;
8670 }
8671 }
8672 if (typed_test_info == nullptr) {
8673 typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
8674 test_suite_name, code_location);
8675 test_suite_infos_.push_back(typed_test_info);
8676 }
8677 return typed_test_info;
8678 }
8679 void RegisterTests() {
8680 for (auto& test_suite_info : test_suite_infos_) {
8681 test_suite_info->RegisterTests();
8682 }
8683 }
8684 // Legacy API is deprecated but still available
8685 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8686 template <class TestCase>
8687 ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
8688 const char* test_case_name, CodeLocation code_location) {
8689 return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
8690 }
8691
8692 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8693
8694 private:
8695 using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
8696
8697 TestSuiteInfoContainer test_suite_infos_;
8698
8699 GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
8700 };
8701
8702 // Keep track of what type-parameterized test suite are defined and
8703 // where as well as which are intatiated. This allows susequently
8704 // identifying suits that are defined but never used.
8705 class TypeParameterizedTestSuiteRegistry {
8706 public:
8707 // Add a suite definition
8708 void RegisterTestSuite(const char* test_suite_name,
8709 CodeLocation code_location);
8710
8711 // Add an instantiation of a suit.
8712 void RegisterInstantiation(const char* test_suite_name);
8713
8714 // For each suit repored as defined but not reported as instantiation,
8715 // emit a test that reports that fact (configurably, as an error).
8716 void CheckForInstantiations();
8717
8718 private:
8719 struct TypeParameterizedTestSuiteInfo {
8720 explicit TypeParameterizedTestSuiteInfo(CodeLocation c)
8721 : code_location(c), instantiated(false) {}
8722
8723 CodeLocation code_location;
8724 bool instantiated;
8725 };
8726
8727 std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;
8728 };
8729
8730 } // namespace internal
8731
8732 // Forward declarations of ValuesIn(), which is implemented in
8733 // include/gtest/gtest-param-test.h.
8734 template <class Container>
8735 internal::ParamGenerator<typename Container::value_type> ValuesIn(
8736 const Container& container);
8737
8738 namespace internal {
8739 // Used in the Values() function to provide polymorphic capabilities.
8740
8741 #ifdef _MSC_VER
8742 #pragma warning(push)
8743 #pragma warning(disable : 4100)
8744 #endif
8745
8746 template <typename... Ts>
8747 class ValueArray {
8748 public:
8749 explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
8750
8751 template <typename T>
8752 operator ParamGenerator<T>() const { // NOLINT
8753 return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
8754 }
8755
8756 private:
8757 template <typename T, size_t... I>
8758 std::vector<T> MakeVector(IndexSequence<I...>) const {
8759 return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
8760 }
8761
8762 FlatTuple<Ts...> v_;
8763 };
8764
8765 #ifdef _MSC_VER
8766 #pragma warning(pop)
8767 #endif
8768
8769 template <typename... T>
8770 class CartesianProductGenerator
8771 : public ParamGeneratorInterface<::std::tuple<T...>> {
8772 public:
8773 typedef ::std::tuple<T...> ParamType;
8774
8775 CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
8776 : generators_(g) {}
8777 ~CartesianProductGenerator() override {}
8778
8779 ParamIteratorInterface<ParamType>* Begin() const override {
8780 return new Iterator(this, generators_, false);
8781 }
8782 ParamIteratorInterface<ParamType>* End() const override {
8783 return new Iterator(this, generators_, true);
8784 }
8785
8786 private:
8787 template <class I>
8788 class IteratorImpl;
8789 template <size_t... I>
8790 class IteratorImpl<IndexSequence<I...>>
8791 : public ParamIteratorInterface<ParamType> {
8792 public:
8793 IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
8794 const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
8795 : base_(base),
8796 begin_(std::get<I>(generators).begin()...),
8797 end_(std::get<I>(generators).end()...),
8798 current_(is_end ? end_ : begin_) {
8799 ComputeCurrentValue();
8800 }
8801 ~IteratorImpl() override {}
8802
8803 const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
8804 return base_;
8805 }
8806 // Advance should not be called on beyond-of-range iterators
8807 // so no component iterators must be beyond end of range, either.
8808 void Advance() override {
8809 assert(!AtEnd());
8810 // Advance the last iterator.
8811 ++std::get<sizeof...(T) - 1>(current_);
8812 // if that reaches end, propagate that up.
8813 AdvanceIfEnd<sizeof...(T) - 1>();
8814 ComputeCurrentValue();
8815 }
8816 ParamIteratorInterface<ParamType>* Clone() const override {
8817 return new IteratorImpl(*this);
8818 }
8819
8820 const ParamType* Current() const override { return current_value_.get(); }
8821
8822 bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
8823 // Having the same base generator guarantees that the other
8824 // iterator is of the same type and we can downcast.
8825 GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8826 << "The program attempted to compare iterators "
8827 << "from different generators." << std::endl;
8828 const IteratorImpl* typed_other =
8829 CheckedDowncastToActualType<const IteratorImpl>(&other);
8830
8831 // We must report iterators equal if they both point beyond their
8832 // respective ranges. That can happen in a variety of fashions,
8833 // so we have to consult AtEnd().
8834 if (AtEnd() && typed_other->AtEnd()) return true;
8835
8836 bool same = true;
8837 bool dummy[] = {
8838 (same = same && std::get<I>(current_) ==
8839 std::get<I>(typed_other->current_))...};
8840 (void)dummy;
8841 return same;
8842 }
8843
8844 private:
8845 template <size_t ThisI>
8846 void AdvanceIfEnd() {
8847 if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
8848
8849 bool last = ThisI == 0;
8850 if (last) {
8851 // We are done. Nothing else to propagate.
8852 return;
8853 }
8854
8855 constexpr size_t NextI = ThisI - (ThisI != 0);
8856 std::get<ThisI>(current_) = std::get<ThisI>(begin_);
8857 ++std::get<NextI>(current_);
8858 AdvanceIfEnd<NextI>();
8859 }
8860
8861 void ComputeCurrentValue() {
8862 if (!AtEnd())
8863 current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
8864 }
8865 bool AtEnd() const {
8866 bool at_end = false;
8867 bool dummy[] = {
8868 (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
8869 (void)dummy;
8870 return at_end;
8871 }
8872
8873 const ParamGeneratorInterface<ParamType>* const base_;
8874 std::tuple<typename ParamGenerator<T>::iterator...> begin_;
8875 std::tuple<typename ParamGenerator<T>::iterator...> end_;
8876 std::tuple<typename ParamGenerator<T>::iterator...> current_;
8877 std::shared_ptr<ParamType> current_value_;
8878 };
8879
8880 using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
8881
8882 std::tuple<ParamGenerator<T>...> generators_;
8883 };
8884
8885 template <class... Gen>
8886 class CartesianProductHolder {
8887 public:
8888 CartesianProductHolder(const Gen&... g) : generators_(g...) {}
8889 template <typename... T>
8890 operator ParamGenerator<::std::tuple<T...>>() const {
8891 return ParamGenerator<::std::tuple<T...>>(
8892 new CartesianProductGenerator<T...>(generators_));
8893 }
8894
8895 private:
8896 std::tuple<Gen...> generators_;
8897 };
8898
8899 } // namespace internal
8900 } // namespace testing
8901
8902 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
8903
8904 namespace testing {
8905
8906 // Functions producing parameter generators.
8907 //
8908 // Google Test uses these generators to produce parameters for value-
8909 // parameterized tests. When a parameterized test suite is instantiated
8910 // with a particular generator, Google Test creates and runs tests
8911 // for each element in the sequence produced by the generator.
8912 //
8913 // In the following sample, tests from test suite FooTest are instantiated
8914 // each three times with parameter values 3, 5, and 8:
8915 //
8916 // class FooTest : public TestWithParam<int> { ... };
8917 //
8918 // TEST_P(FooTest, TestThis) {
8919 // }
8920 // TEST_P(FooTest, TestThat) {
8921 // }
8922 // INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));
8923 //
8924
8925 // Range() returns generators providing sequences of values in a range.
8926 //
8927 // Synopsis:
8928 // Range(start, end)
8929 // - returns a generator producing a sequence of values {start, start+1,
8930 // start+2, ..., }.
8931 // Range(start, end, step)
8932 // - returns a generator producing a sequence of values {start, start+step,
8933 // start+step+step, ..., }.
8934 // Notes:
8935 // * The generated sequences never include end. For example, Range(1, 5)
8936 // returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
8937 // returns a generator producing {1, 3, 5, 7}.
8938 // * start and end must have the same type. That type may be any integral or
8939 // floating-point type or a user defined type satisfying these conditions:
8940 // * It must be assignable (have operator=() defined).
8941 // * It must have operator+() (operator+(int-compatible type) for
8942 // two-operand version).
8943 // * It must have operator<() defined.
8944 // Elements in the resulting sequences will also have that type.
8945 // * Condition start < end must be satisfied in order for resulting sequences
8946 // to contain any elements.
8947 //
8948 template <typename T, typename IncrementT>
8949 internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
8950 return internal::ParamGenerator<T>(
8951 new internal::RangeGenerator<T, IncrementT>(start, end, step));
8952 }
8953
8954 template <typename T>
8955 internal::ParamGenerator<T> Range(T start, T end) {
8956 return Range(start, end, 1);
8957 }
8958
8959 // ValuesIn() function allows generation of tests with parameters coming from
8960 // a container.
8961 //
8962 // Synopsis:
8963 // ValuesIn(const T (&array)[N])
8964 // - returns a generator producing sequences with elements from
8965 // a C-style array.
8966 // ValuesIn(const Container& container)
8967 // - returns a generator producing sequences with elements from
8968 // an STL-style container.
8969 // ValuesIn(Iterator begin, Iterator end)
8970 // - returns a generator producing sequences with elements from
8971 // a range [begin, end) defined by a pair of STL-style iterators. These
8972 // iterators can also be plain C pointers.
8973 //
8974 // Please note that ValuesIn copies the values from the containers
8975 // passed in and keeps them to generate tests in RUN_ALL_TESTS().
8976 //
8977 // Examples:
8978 //
8979 // This instantiates tests from test suite StringTest
8980 // each with C-string values of "foo", "bar", and "baz":
8981 //
8982 // const char* strings[] = {"foo", "bar", "baz"};
8983 // INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));
8984 //
8985 // This instantiates tests from test suite StlStringTest
8986 // each with STL strings with values "a" and "b":
8987 //
8988 // ::std::vector< ::std::string> GetParameterStrings() {
8989 // ::std::vector< ::std::string> v;
8990 // v.push_back("a");
8991 // v.push_back("b");
8992 // return v;
8993 // }
8994 //
8995 // INSTANTIATE_TEST_SUITE_P(CharSequence,
8996 // StlStringTest,
8997 // ValuesIn(GetParameterStrings()));
8998 //
8999 //
9000 // This will also instantiate tests from CharTest
9001 // each with parameter values 'a' and 'b':
9002 //
9003 // ::std::list<char> GetParameterChars() {
9004 // ::std::list<char> list;
9005 // list.push_back('a');
9006 // list.push_back('b');
9007 // return list;
9008 // }
9009 // ::std::list<char> l = GetParameterChars();
9010 // INSTANTIATE_TEST_SUITE_P(CharSequence2,
9011 // CharTest,
9012 // ValuesIn(l.begin(), l.end()));
9013 //
9014 template <typename ForwardIterator>
9015 internal::ParamGenerator<
9016 typename std::iterator_traits<ForwardIterator>::value_type>
9017 ValuesIn(ForwardIterator begin, ForwardIterator end) {
9018 typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;
9019 return internal::ParamGenerator<ParamType>(
9020 new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
9021 }
9022
9023 template <typename T, size_t N>
9024 internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
9025 return ValuesIn(array, array + N);
9026 }
9027
9028 template <class Container>
9029 internal::ParamGenerator<typename Container::value_type> ValuesIn(
9030 const Container& container) {
9031 return ValuesIn(container.begin(), container.end());
9032 }
9033
9034 // Values() allows generating tests from explicitly specified list of
9035 // parameters.
9036 //
9037 // Synopsis:
9038 // Values(T v1, T v2, ..., T vN)
9039 // - returns a generator producing sequences with elements v1, v2, ..., vN.
9040 //
9041 // For example, this instantiates tests from test suite BarTest each
9042 // with values "one", "two", and "three":
9043 //
9044 // INSTANTIATE_TEST_SUITE_P(NumSequence,
9045 // BarTest,
9046 // Values("one", "two", "three"));
9047 //
9048 // This instantiates tests from test suite BazTest each with values 1, 2, 3.5.
9049 // The exact type of values will depend on the type of parameter in BazTest.
9050 //
9051 // INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
9052 //
9053 //
9054 template <typename... T>
9055 internal::ValueArray<T...> Values(T... v) {
9056 return internal::ValueArray<T...>(std::move(v)...);
9057 }
9058
9059 // Bool() allows generating tests with parameters in a set of (false, true).
9060 //
9061 // Synopsis:
9062 // Bool()
9063 // - returns a generator producing sequences with elements {false, true}.
9064 //
9065 // It is useful when testing code that depends on Boolean flags. Combinations
9066 // of multiple flags can be tested when several Bool()'s are combined using
9067 // Combine() function.
9068 //
9069 // In the following example all tests in the test suite FlagDependentTest
9070 // will be instantiated twice with parameters false and true.
9071 //
9072 // class FlagDependentTest : public testing::TestWithParam<bool> {
9073 // virtual void SetUp() {
9074 // external_flag = GetParam();
9075 // }
9076 // }
9077 // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
9078 //
9079 inline internal::ParamGenerator<bool> Bool() {
9080 return Values(false, true);
9081 }
9082
9083 // Combine() allows the user to combine two or more sequences to produce
9084 // values of a Cartesian product of those sequences' elements.
9085 //
9086 // Synopsis:
9087 // Combine(gen1, gen2, ..., genN)
9088 // - returns a generator producing sequences with elements coming from
9089 // the Cartesian product of elements from the sequences generated by
9090 // gen1, gen2, ..., genN. The sequence elements will have a type of
9091 // std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
9092 // of elements from sequences produces by gen1, gen2, ..., genN.
9093 //
9094 // Example:
9095 //
9096 // This will instantiate tests in test suite AnimalTest each one with
9097 // the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
9098 // tuple("dog", BLACK), and tuple("dog", WHITE):
9099 //
9100 // enum Color { BLACK, GRAY, WHITE };
9101 // class AnimalTest
9102 // : public testing::TestWithParam<std::tuple<const char*, Color> > {...};
9103 //
9104 // TEST_P(AnimalTest, AnimalLooksNice) {...}
9105 //
9106 // INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
9107 // Combine(Values("cat", "dog"),
9108 // Values(BLACK, WHITE)));
9109 //
9110 // This will instantiate tests in FlagDependentTest with all variations of two
9111 // Boolean flags:
9112 //
9113 // class FlagDependentTest
9114 // : public testing::TestWithParam<std::tuple<bool, bool> > {
9115 // virtual void SetUp() {
9116 // // Assigns external_flag_1 and external_flag_2 values from the tuple.
9117 // std::tie(external_flag_1, external_flag_2) = GetParam();
9118 // }
9119 // };
9120 //
9121 // TEST_P(FlagDependentTest, TestFeature1) {
9122 // // Test your code using external_flag_1 and external_flag_2 here.
9123 // }
9124 // INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,
9125 // Combine(Bool(), Bool()));
9126 //
9127 template <typename... Generator>
9128 internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
9129 return internal::CartesianProductHolder<Generator...>(g...);
9130 }
9131
9132 #define TEST_P(test_suite_name, test_name) \
9133 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
9134 : public test_suite_name { \
9135 public: \
9136 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
9137 void TestBody() override; \
9138 \
9139 private: \
9140 static int AddToRegistry() { \
9141 ::testing::UnitTest::GetInstance() \
9142 ->parameterized_test_registry() \
9143 .GetTestSuitePatternHolder<test_suite_name>( \
9144 GTEST_STRINGIFY_(test_suite_name), \
9145 ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
9146 ->AddTestPattern( \
9147 GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
9148 new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
9149 test_suite_name, test_name)>(), \
9150 ::testing::internal::CodeLocation(__FILE__, __LINE__)); \
9151 return 0; \
9152 } \
9153 static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
9154 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
9155 test_name)); \
9156 }; \
9157 int GTEST_TEST_CLASS_NAME_(test_suite_name, \
9158 test_name)::gtest_registering_dummy_ = \
9159 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \
9160 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
9161
9162 // The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify
9163 // generator and an optional function or functor that generates custom test name
9164 // suffixes based on the test parameters. Such a function or functor should
9165 // accept one argument of type testing::TestParamInfo<class ParamType>, and
9166 // return std::string.
9167 //
9168 // testing::PrintToStringParamName is a builtin test suffix generator that
9169 // returns the value of testing::PrintToString(GetParam()).
9170 //
9171 // Note: test names must be non-empty, unique, and may only contain ASCII
9172 // alphanumeric characters or underscore. Because PrintToString adds quotes
9173 // to std::string and C strings, it won't work for these types.
9174
9175 #define GTEST_EXPAND_(arg) arg
9176 #define GTEST_GET_FIRST_(first, ...) first
9177 #define GTEST_GET_SECOND_(first, second, ...) second
9178
9179 #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
9180 static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
9181 gtest_##prefix##test_suite_name##_EvalGenerator_() { \
9182 return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
9183 } \
9184 static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
9185 const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
9186 if (::testing::internal::AlwaysFalse()) { \
9187 ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
9188 __VA_ARGS__, \
9189 ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
9190 DUMMY_PARAM_))); \
9191 auto t = std::make_tuple(__VA_ARGS__); \
9192 static_assert(std::tuple_size<decltype(t)>::value <= 2, \
9193 "Too Many Args!"); \
9194 } \
9195 return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
9196 __VA_ARGS__, \
9197 ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
9198 DUMMY_PARAM_))))(info); \
9199 } \
9200 static int gtest_##prefix##test_suite_name##_dummy_ \
9201 GTEST_ATTRIBUTE_UNUSED_ = \
9202 ::testing::UnitTest::GetInstance() \
9203 ->parameterized_test_registry() \
9204 .GetTestSuitePatternHolder<test_suite_name>( \
9205 GTEST_STRINGIFY_(test_suite_name), \
9206 ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
9207 ->AddTestSuiteInstantiation( \
9208 GTEST_STRINGIFY_(prefix), \
9209 &gtest_##prefix##test_suite_name##_EvalGenerator_, \
9210 &gtest_##prefix##test_suite_name##_EvalGenerateName_, \
9211 __FILE__, __LINE__)
9212
9213
9214 // Allow Marking a Parameterized test class as not needing to be instantiated.
9215 #define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
9216 namespace gtest_do_not_use_outside_namespace_scope {} \
9217 static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
9218 GTEST_STRINGIFY_(T))
9219
9220 // Legacy API is deprecated but still available
9221 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9222 #define INSTANTIATE_TEST_CASE_P \
9223 static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \
9224 ""); \
9225 INSTANTIATE_TEST_SUITE_P
9226 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9227
9228 } // namespace testing
9229
9230 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
9231 // Copyright 2006, Google Inc.
9232 // All rights reserved.
9233 //
9234 // Redistribution and use in source and binary forms, with or without
9235 // modification, are permitted provided that the following conditions are
9236 // met:
9237 //
9238 // * Redistributions of source code must retain the above copyright
9239 // notice, this list of conditions and the following disclaimer.
9240 // * Redistributions in binary form must reproduce the above
9241 // copyright notice, this list of conditions and the following disclaimer
9242 // in the documentation and/or other materials provided with the
9243 // distribution.
9244 // * Neither the name of Google Inc. nor the names of its
9245 // contributors may be used to endorse or promote products derived from
9246 // this software without specific prior written permission.
9247 //
9248 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9249 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9250 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9251 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9252 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9253 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9254 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9255 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9256 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9257 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9258 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9259
9260 //
9261 // Google C++ Testing and Mocking Framework definitions useful in production code.
9262 // GOOGLETEST_CM0003 DO NOT DELETE
9263
9264 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9265 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9266
9267 // When you need to test the private or protected members of a class,
9268 // use the FRIEND_TEST macro to declare your tests as friends of the
9269 // class. For example:
9270 //
9271 // class MyClass {
9272 // private:
9273 // void PrivateMethod();
9274 // FRIEND_TEST(MyClassTest, PrivateMethodWorks);
9275 // };
9276 //
9277 // class MyClassTest : public testing::Test {
9278 // // ...
9279 // };
9280 //
9281 // TEST_F(MyClassTest, PrivateMethodWorks) {
9282 // // Can call MyClass::PrivateMethod() here.
9283 // }
9284 //
9285 // Note: The test class must be in the same namespace as the class being tested.
9286 // For example, putting MyClassTest in an anonymous namespace will not work.
9287
9288 #define FRIEND_TEST(test_case_name, test_name)\
9289 friend class test_case_name##_##test_name##_Test
9290
9291 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9292 // Copyright 2008 Google Inc.
9293 // All Rights Reserved.
9294 //
9295 // Redistribution and use in source and binary forms, with or without
9296 // modification, are permitted provided that the following conditions are
9297 // met:
9298 //
9299 // * Redistributions of source code must retain the above copyright
9300 // notice, this list of conditions and the following disclaimer.
9301 // * Redistributions in binary form must reproduce the above
9302 // copyright notice, this list of conditions and the following disclaimer
9303 // in the documentation and/or other materials provided with the
9304 // distribution.
9305 // * Neither the name of Google Inc. nor the names of its
9306 // contributors may be used to endorse or promote products derived from
9307 // this software without specific prior written permission.
9308 //
9309 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9310 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9311 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9312 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9313 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9314 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9315 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9316 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9317 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9318 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9319 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9320
9321 // GOOGLETEST_CM0001 DO NOT DELETE
9322
9323 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9324 #define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9325
9326 // This header implements typed tests and type-parameterized tests.
9327
9328 // Typed (aka type-driven) tests repeat the same test for types in a
9329 // list. You must know which types you want to test with when writing
9330 // typed tests. Here's how you do it:
9331
9332 #if 0
9333
9334 // First, define a fixture class template. It should be parameterized
9335 // by a type. Remember to derive it from testing::Test.
9336 template <typename T>
9337 class FooTest : public testing::Test {
9338 public:
9339 ...
9340 typedef std::list<T> List;
9341 static T shared_;
9342 T value_;
9343 };
9344
9345 // Next, associate a list of types with the test suite, which will be
9346 // repeated for each type in the list. The typedef is necessary for
9347 // the macro to parse correctly.
9348 typedef testing::Types<char, int, unsigned int> MyTypes;
9349 TYPED_TEST_SUITE(FooTest, MyTypes);
9350
9351 // If the type list contains only one type, you can write that type
9352 // directly without Types<...>:
9353 // TYPED_TEST_SUITE(FooTest, int);
9354
9355 // Then, use TYPED_TEST() instead of TEST_F() to define as many typed
9356 // tests for this test suite as you want.
9357 TYPED_TEST(FooTest, DoesBlah) {
9358 // Inside a test, refer to the special name TypeParam to get the type
9359 // parameter. Since we are inside a derived class template, C++ requires
9360 // us to visit the members of FooTest via 'this'.
9361 TypeParam n = this->value_;
9362
9363 // To visit static members of the fixture, add the TestFixture::
9364 // prefix.
9365 n += TestFixture::shared_;
9366
9367 // To refer to typedefs in the fixture, add the "typename
9368 // TestFixture::" prefix.
9369 typename TestFixture::List values;
9370 values.push_back(n);
9371 ...
9372 }
9373
9374 TYPED_TEST(FooTest, HasPropertyA) { ... }
9375
9376 // TYPED_TEST_SUITE takes an optional third argument which allows to specify a
9377 // class that generates custom test name suffixes based on the type. This should
9378 // be a class which has a static template function GetName(int index) returning
9379 // a string for each type. The provided integer index equals the index of the
9380 // type in the provided type list. In many cases the index can be ignored.
9381 //
9382 // For example:
9383 // class MyTypeNames {
9384 // public:
9385 // template <typename T>
9386 // static std::string GetName(int) {
9387 // if (std::is_same<T, char>()) return "char";
9388 // if (std::is_same<T, int>()) return "int";
9389 // if (std::is_same<T, unsigned int>()) return "unsignedInt";
9390 // }
9391 // };
9392 // TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);
9393
9394 #endif // 0
9395
9396 // Type-parameterized tests are abstract test patterns parameterized
9397 // by a type. Compared with typed tests, type-parameterized tests
9398 // allow you to define the test pattern without knowing what the type
9399 // parameters are. The defined pattern can be instantiated with
9400 // different types any number of times, in any number of translation
9401 // units.
9402 //
9403 // If you are designing an interface or concept, you can define a
9404 // suite of type-parameterized tests to verify properties that any
9405 // valid implementation of the interface/concept should have. Then,
9406 // each implementation can easily instantiate the test suite to verify
9407 // that it conforms to the requirements, without having to write
9408 // similar tests repeatedly. Here's an example:
9409
9410 #if 0
9411
9412 // First, define a fixture class template. It should be parameterized
9413 // by a type. Remember to derive it from testing::Test.
9414 template <typename T>
9415 class FooTest : public testing::Test {
9416 ...
9417 };
9418
9419 // Next, declare that you will define a type-parameterized test suite
9420 // (the _P suffix is for "parameterized" or "pattern", whichever you
9421 // prefer):
9422 TYPED_TEST_SUITE_P(FooTest);
9423
9424 // Then, use TYPED_TEST_P() to define as many type-parameterized tests
9425 // for this type-parameterized test suite as you want.
9426 TYPED_TEST_P(FooTest, DoesBlah) {
9427 // Inside a test, refer to TypeParam to get the type parameter.
9428 TypeParam n = 0;
9429 ...
9430 }
9431
9432 TYPED_TEST_P(FooTest, HasPropertyA) { ... }
9433
9434 // Now the tricky part: you need to register all test patterns before
9435 // you can instantiate them. The first argument of the macro is the
9436 // test suite name; the rest are the names of the tests in this test
9437 // case.
9438 REGISTER_TYPED_TEST_SUITE_P(FooTest,
9439 DoesBlah, HasPropertyA);
9440
9441 // Finally, you are free to instantiate the pattern with the types you
9442 // want. If you put the above code in a header file, you can #include
9443 // it in multiple C++ source files and instantiate it multiple times.
9444 //
9445 // To distinguish different instances of the pattern, the first
9446 // argument to the INSTANTIATE_* macro is a prefix that will be added
9447 // to the actual test suite name. Remember to pick unique prefixes for
9448 // different instances.
9449 typedef testing::Types<char, int, unsigned int> MyTypes;
9450 INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
9451
9452 // If the type list contains only one type, you can write that type
9453 // directly without Types<...>:
9454 // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
9455 //
9456 // Similar to the optional argument of TYPED_TEST_SUITE above,
9457 // INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to
9458 // generate custom names.
9459 // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);
9460
9461 #endif // 0
9462
9463
9464 // Implements typed tests.
9465
9466 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9467 //
9468 // Expands to the name of the typedef for the type parameters of the
9469 // given test suite.
9470 #define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_
9471
9472 // Expands to the name of the typedef for the NameGenerator, responsible for
9473 // creating the suffixes of the name.
9474 #define GTEST_NAME_GENERATOR_(TestSuiteName) \
9475 gtest_type_params_##TestSuiteName##_NameGenerator
9476
9477 #define TYPED_TEST_SUITE(CaseName, Types, ...) \
9478 typedef ::testing::internal::GenerateTypeList<Types>::type \
9479 GTEST_TYPE_PARAMS_(CaseName); \
9480 typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
9481 GTEST_NAME_GENERATOR_(CaseName)
9482
9483 #define TYPED_TEST(CaseName, TestName) \
9484 static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \
9485 "test-name must not be empty"); \
9486 template <typename gtest_TypeParam_> \
9487 class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
9488 : public CaseName<gtest_TypeParam_> { \
9489 private: \
9490 typedef CaseName<gtest_TypeParam_> TestFixture; \
9491 typedef gtest_TypeParam_ TypeParam; \
9492 void TestBody() override; \
9493 }; \
9494 static bool gtest_##CaseName##_##TestName##_registered_ \
9495 GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \
9496 CaseName, \
9497 ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
9498 TestName)>, \
9499 GTEST_TYPE_PARAMS_( \
9500 CaseName)>::Register("", \
9501 ::testing::internal::CodeLocation( \
9502 __FILE__, __LINE__), \
9503 GTEST_STRINGIFY_(CaseName), \
9504 GTEST_STRINGIFY_(TestName), 0, \
9505 ::testing::internal::GenerateNames< \
9506 GTEST_NAME_GENERATOR_(CaseName), \
9507 GTEST_TYPE_PARAMS_(CaseName)>()); \
9508 template <typename gtest_TypeParam_> \
9509 void GTEST_TEST_CLASS_NAME_(CaseName, \
9510 TestName)<gtest_TypeParam_>::TestBody()
9511
9512 // Legacy API is deprecated but still available
9513 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9514 #define TYPED_TEST_CASE \
9515 static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \
9516 TYPED_TEST_SUITE
9517 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9518
9519 // Implements type-parameterized tests.
9520
9521 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9522 //
9523 // Expands to the namespace name that the type-parameterized tests for
9524 // the given type-parameterized test suite are defined in. The exact
9525 // name of the namespace is subject to change without notice.
9526 #define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_
9527
9528 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9529 //
9530 // Expands to the name of the variable used to remember the names of
9531 // the defined tests in the given test suite.
9532 #define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \
9533 gtest_typed_test_suite_p_state_##TestSuiteName##_
9534
9535 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
9536 //
9537 // Expands to the name of the variable used to remember the names of
9538 // the registered tests in the given test suite.
9539 #define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \
9540 gtest_registered_test_names_##TestSuiteName##_
9541
9542 // The variables defined in the type-parameterized test macros are
9543 // static as typically these macros are used in a .h file that can be
9544 // #included in multiple translation units linked together.
9545 #define TYPED_TEST_SUITE_P(SuiteName) \
9546 static ::testing::internal::TypedTestSuitePState \
9547 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
9548
9549 // Legacy API is deprecated but still available
9550 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9551 #define TYPED_TEST_CASE_P \
9552 static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \
9553 TYPED_TEST_SUITE_P
9554 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9555
9556 #define TYPED_TEST_P(SuiteName, TestName) \
9557 namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
9558 template <typename gtest_TypeParam_> \
9559 class TestName : public SuiteName<gtest_TypeParam_> { \
9560 private: \
9561 typedef SuiteName<gtest_TypeParam_> TestFixture; \
9562 typedef gtest_TypeParam_ TypeParam; \
9563 void TestBody() override; \
9564 }; \
9565 static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
9566 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
9567 __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
9568 GTEST_STRINGIFY_(TestName)); \
9569 } \
9570 template <typename gtest_TypeParam_> \
9571 void GTEST_SUITE_NAMESPACE_( \
9572 SuiteName)::TestName<gtest_TypeParam_>::TestBody()
9573
9574 // Note: this won't work correctly if the trailing arguments are macros.
9575 #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
9576 namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
9577 typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
9578 } \
9579 static const char* const GTEST_REGISTERED_TEST_NAMES_( \
9580 SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
9581 GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
9582 GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
9583
9584 // Legacy API is deprecated but still available
9585 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9586 #define REGISTER_TYPED_TEST_CASE_P \
9587 static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \
9588 ""); \
9589 REGISTER_TYPED_TEST_SUITE_P
9590 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9591
9592 #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
9593 static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \
9594 "test-suit-prefix must not be empty"); \
9595 static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
9596 ::testing::internal::TypeParameterizedTestSuite< \
9597 SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
9598 ::testing::internal::GenerateTypeList<Types>::type>:: \
9599 Register(GTEST_STRINGIFY_(Prefix), \
9600 ::testing::internal::CodeLocation(__FILE__, __LINE__), \
9601 &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \
9602 GTEST_STRINGIFY_(SuiteName), \
9603 GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
9604 ::testing::internal::GenerateNames< \
9605 ::testing::internal::NameGeneratorSelector< \
9606 __VA_ARGS__>::type, \
9607 ::testing::internal::GenerateTypeList<Types>::type>())
9608
9609 // Legacy API is deprecated but still available
9610 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9611 #define INSTANTIATE_TYPED_TEST_CASE_P \
9612 static_assert( \
9613 ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \
9614 INSTANTIATE_TYPED_TEST_SUITE_P
9615 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9616
9617 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9618
9619 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
9620 /* class A needs to have dll-interface to be used by clients of class B */)
9621
9622 namespace testing {
9623
9624 // Silence C4100 (unreferenced formal parameter) and 4805
9625 // unsafe mix of type 'const int' and type 'const bool'
9626 #ifdef _MSC_VER
9627 # pragma warning(push)
9628 # pragma warning(disable:4805)
9629 # pragma warning(disable:4100)
9630 #endif
9631
9632
9633 // Declares the flags.
9634
9635 // This flag temporary enables the disabled tests.
9636 GTEST_DECLARE_bool_(also_run_disabled_tests);
9637
9638 // This flag brings the debugger on an assertion failure.
9639 GTEST_DECLARE_bool_(break_on_failure);
9640
9641 // This flag controls whether Google Test catches all test-thrown exceptions
9642 // and logs them as failures.
9643 GTEST_DECLARE_bool_(catch_exceptions);
9644
9645 // This flag enables using colors in terminal output. Available values are
9646 // "yes" to enable colors, "no" (disable colors), or "auto" (the default)
9647 // to let Google Test decide.
9648 GTEST_DECLARE_string_(color);
9649
9650 // This flag controls whether the test runner should continue execution past
9651 // first failure.
9652 GTEST_DECLARE_bool_(fail_fast);
9653
9654 // This flag sets up the filter to select by name using a glob pattern
9655 // the tests to run. If the filter is not given all tests are executed.
9656 GTEST_DECLARE_string_(filter);
9657
9658 // This flag controls whether Google Test installs a signal handler that dumps
9659 // debugging information when fatal signals are raised.
9660 GTEST_DECLARE_bool_(install_failure_signal_handler);
9661
9662 // This flag causes the Google Test to list tests. None of the tests listed
9663 // are actually run if the flag is provided.
9664 GTEST_DECLARE_bool_(list_tests);
9665
9666 // This flag controls whether Google Test emits a detailed XML report to a file
9667 // in addition to its normal textual output.
9668 GTEST_DECLARE_string_(output);
9669
9670 // This flags control whether Google Test prints only test failures.
9671 GTEST_DECLARE_bool_(brief);
9672
9673 // This flags control whether Google Test prints the elapsed time for each
9674 // test.
9675 GTEST_DECLARE_bool_(print_time);
9676
9677 // This flags control whether Google Test prints UTF8 characters as text.
9678 GTEST_DECLARE_bool_(print_utf8);
9679
9680 // This flag specifies the random number seed.
9681 GTEST_DECLARE_int32_(random_seed);
9682
9683 // This flag sets how many times the tests are repeated. The default value
9684 // is 1. If the value is -1 the tests are repeating forever.
9685 GTEST_DECLARE_int32_(repeat);
9686
9687 // This flag controls whether Google Test includes Google Test internal
9688 // stack frames in failure stack traces.
9689 GTEST_DECLARE_bool_(show_internal_stack_frames);
9690
9691 // When this flag is specified, tests' order is randomized on every iteration.
9692 GTEST_DECLARE_bool_(shuffle);
9693
9694 // This flag specifies the maximum number of stack frames to be
9695 // printed in a failure message.
9696 GTEST_DECLARE_int32_(stack_trace_depth);
9697
9698 // When this flag is specified, a failed assertion will throw an
9699 // exception if exceptions are enabled, or exit the program with a
9700 // non-zero code otherwise. For use with an external test framework.
9701 GTEST_DECLARE_bool_(throw_on_failure);
9702
9703 // When this flag is set with a "host:port" string, on supported
9704 // platforms test results are streamed to the specified port on
9705 // the specified host machine.
9706 GTEST_DECLARE_string_(stream_result_to);
9707
9708 #if GTEST_USE_OWN_FLAGFILE_FLAG_
9709 GTEST_DECLARE_string_(flagfile);
9710 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
9711
9712 // The upper limit for valid stack trace depths.
9713 const int kMaxStackTraceDepth = 100;
9714
9715 namespace internal {
9716
9717 class AssertHelper;
9718 class DefaultGlobalTestPartResultReporter;
9719 class ExecDeathTest;
9720 class NoExecDeathTest;
9721 class FinalSuccessChecker;
9722 class GTestFlagSaver;
9723 class StreamingListenerTest;
9724 class TestResultAccessor;
9725 class TestEventListenersAccessor;
9726 class TestEventRepeater;
9727 class UnitTestRecordPropertyTestHelper;
9728 class WindowsDeathTest;
9729 class FuchsiaDeathTest;
9730 class UnitTestImpl* GetUnitTestImpl();
9731 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
9732 const std::string& message);
9733 std::set<std::string>* GetIgnoredParameterizedTestSuites();
9734
9735 } // namespace internal
9736
9737 // The friend relationship of some of these classes is cyclic.
9738 // If we don't forward declare them the compiler might confuse the classes
9739 // in friendship clauses with same named classes on the scope.
9740 class Test;
9741 class TestSuite;
9742
9743 // Old API is still available but deprecated
9744 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9745 using TestCase = TestSuite;
9746 #endif
9747 class TestInfo;
9748 class UnitTest;
9749
9750 // A class for indicating whether an assertion was successful. When
9751 // the assertion wasn't successful, the AssertionResult object
9752 // remembers a non-empty message that describes how it failed.
9753 //
9754 // To create an instance of this class, use one of the factory functions
9755 // (AssertionSuccess() and AssertionFailure()).
9756 //
9757 // This class is useful for two purposes:
9758 // 1. Defining predicate functions to be used with Boolean test assertions
9759 // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
9760 // 2. Defining predicate-format functions to be
9761 // used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
9762 //
9763 // For example, if you define IsEven predicate:
9764 //
9765 // testing::AssertionResult IsEven(int n) {
9766 // if ((n % 2) == 0)
9767 // return testing::AssertionSuccess();
9768 // else
9769 // return testing::AssertionFailure() << n << " is odd";
9770 // }
9771 //
9772 // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
9773 // will print the message
9774 //
9775 // Value of: IsEven(Fib(5))
9776 // Actual: false (5 is odd)
9777 // Expected: true
9778 //
9779 // instead of a more opaque
9780 //
9781 // Value of: IsEven(Fib(5))
9782 // Actual: false
9783 // Expected: true
9784 //
9785 // in case IsEven is a simple Boolean predicate.
9786 //
9787 // If you expect your predicate to be reused and want to support informative
9788 // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
9789 // about half as often as positive ones in our tests), supply messages for
9790 // both success and failure cases:
9791 //
9792 // testing::AssertionResult IsEven(int n) {
9793 // if ((n % 2) == 0)
9794 // return testing::AssertionSuccess() << n << " is even";
9795 // else
9796 // return testing::AssertionFailure() << n << " is odd";
9797 // }
9798 //
9799 // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
9800 //
9801 // Value of: IsEven(Fib(6))
9802 // Actual: true (8 is even)
9803 // Expected: false
9804 //
9805 // NB: Predicates that support negative Boolean assertions have reduced
9806 // performance in positive ones so be careful not to use them in tests
9807 // that have lots (tens of thousands) of positive Boolean assertions.
9808 //
9809 // To use this class with EXPECT_PRED_FORMAT assertions such as:
9810 //
9811 // // Verifies that Foo() returns an even number.
9812 // EXPECT_PRED_FORMAT1(IsEven, Foo());
9813 //
9814 // you need to define:
9815 //
9816 // testing::AssertionResult IsEven(const char* expr, int n) {
9817 // if ((n % 2) == 0)
9818 // return testing::AssertionSuccess();
9819 // else
9820 // return testing::AssertionFailure()
9821 // << "Expected: " << expr << " is even\n Actual: it's " << n;
9822 // }
9823 //
9824 // If Foo() returns 5, you will see the following message:
9825 //
9826 // Expected: Foo() is even
9827 // Actual: it's 5
9828 //
9829 class GTEST_API_ AssertionResult {
9830 public:
9831 // Copy constructor.
9832 // Used in EXPECT_TRUE/FALSE(assertion_result).
9833 AssertionResult(const AssertionResult& other);
9834
9835 // C4800 is a level 3 warning in Visual Studio 2015 and earlier.
9836 // This warning is not emitted in Visual Studio 2017.
9837 // This warning is off by default starting in Visual Studio 2019 but can be
9838 // enabled with command-line options.
9839 #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
9840 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
9841 #endif
9842
9843 // Used in the EXPECT_TRUE/FALSE(bool_expression).
9844 //
9845 // T must be contextually convertible to bool.
9846 //
9847 // The second parameter prevents this overload from being considered if
9848 // the argument is implicitly convertible to AssertionResult. In that case
9849 // we want AssertionResult's copy constructor to be used.
9850 template <typename T>
9851 explicit AssertionResult(
9852 const T& success,
9853 typename std::enable_if<
9854 !std::is_convertible<T, AssertionResult>::value>::type*
9855 /*enabler*/
9856 = nullptr)
9857 : success_(success) {}
9858
9859 #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
9860 GTEST_DISABLE_MSC_WARNINGS_POP_()
9861 #endif
9862
9863 // Assignment operator.
9864 AssertionResult& operator=(AssertionResult other) {
9865 swap(other);
9866 return *this;
9867 }
9868
9869 // Returns true if and only if the assertion succeeded.
9870 operator bool() const { return success_; } // NOLINT
9871
9872 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
9873 AssertionResult operator!() const;
9874
9875 // Returns the text streamed into this AssertionResult. Test assertions
9876 // use it when they fail (i.e., the predicate's outcome doesn't match the
9877 // assertion's expectation). When nothing has been streamed into the
9878 // object, returns an empty string.
9879 const char* message() const {
9880 return message_.get() != nullptr ? message_->c_str() : "";
9881 }
9882 // Deprecated; please use message() instead.
9883 const char* failure_message() const { return message(); }
9884
9885 // Streams a custom failure message into this object.
9886 template <typename T> AssertionResult& operator<<(const T& value) {
9887 AppendMessage(Message() << value);
9888 return *this;
9889 }
9890
9891 // Allows streaming basic output manipulators such as endl or flush into
9892 // this object.
9893 AssertionResult& operator<<(
9894 ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
9895 AppendMessage(Message() << basic_manipulator);
9896 return *this;
9897 }
9898
9899 private:
9900 // Appends the contents of message to message_.
9901 void AppendMessage(const Message& a_message) {
9902 if (message_.get() == nullptr) message_.reset(new ::std::string);
9903 message_->append(a_message.GetString().c_str());
9904 }
9905
9906 // Swap the contents of this AssertionResult with other.
9907 void swap(AssertionResult& other);
9908
9909 // Stores result of the assertion predicate.
9910 bool success_;
9911 // Stores the message describing the condition in case the expectation
9912 // construct is not satisfied with the predicate's outcome.
9913 // Referenced via a pointer to avoid taking too much stack frame space
9914 // with test assertions.
9915 std::unique_ptr< ::std::string> message_;
9916 };
9917
9918 // Makes a successful assertion result.
9919 GTEST_API_ AssertionResult AssertionSuccess();
9920
9921 // Makes a failed assertion result.
9922 GTEST_API_ AssertionResult AssertionFailure();
9923
9924 // Makes a failed assertion result with the given failure message.
9925 // Deprecated; use AssertionFailure() << msg.
9926 GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
9927
9928 } // namespace testing
9929
9930 // Includes the auto-generated header that implements a family of generic
9931 // predicate assertion macros. This include comes late because it relies on
9932 // APIs declared above.
9933 // Copyright 2006, Google Inc.
9934 // All rights reserved.
9935 //
9936 // Redistribution and use in source and binary forms, with or without
9937 // modification, are permitted provided that the following conditions are
9938 // met:
9939 //
9940 // * Redistributions of source code must retain the above copyright
9941 // notice, this list of conditions and the following disclaimer.
9942 // * Redistributions in binary form must reproduce the above
9943 // copyright notice, this list of conditions and the following disclaimer
9944 // in the documentation and/or other materials provided with the
9945 // distribution.
9946 // * Neither the name of Google Inc. nor the names of its
9947 // contributors may be used to endorse or promote products derived from
9948 // this software without specific prior written permission.
9949 //
9950 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9951 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9952 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9953 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9954 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9955 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9956 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9957 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9958 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9959 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9960 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9961
9962 // This file is AUTOMATICALLY GENERATED on 01/02/2019 by command
9963 // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
9964 //
9965 // Implements a family of generic predicate assertion macros.
9966 // GOOGLETEST_CM0001 DO NOT DELETE
9967
9968 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
9969 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
9970
9971
9972 namespace testing {
9973
9974 // This header implements a family of generic predicate assertion
9975 // macros:
9976 //
9977 // ASSERT_PRED_FORMAT1(pred_format, v1)
9978 // ASSERT_PRED_FORMAT2(pred_format, v1, v2)
9979 // ...
9980 //
9981 // where pred_format is a function or functor that takes n (in the
9982 // case of ASSERT_PRED_FORMATn) values and their source expression
9983 // text, and returns a testing::AssertionResult. See the definition
9984 // of ASSERT_EQ in gtest.h for an example.
9985 //
9986 // If you don't care about formatting, you can use the more
9987 // restrictive version:
9988 //
9989 // ASSERT_PRED1(pred, v1)
9990 // ASSERT_PRED2(pred, v1, v2)
9991 // ...
9992 //
9993 // where pred is an n-ary function or functor that returns bool,
9994 // and the values v1, v2, ..., must support the << operator for
9995 // streaming to std::ostream.
9996 //
9997 // We also define the EXPECT_* variations.
9998 //
9999 // For now we only support predicates whose arity is at most 5.
10000 // Please email googletestframework@googlegroups.com if you need
10001 // support for higher arities.
10002
10003 // GTEST_ASSERT_ is the basic statement to which all of the assertions
10004 // in this file reduce. Don't use this in your code.
10005
10006 #define GTEST_ASSERT_(expression, on_failure) \
10007 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
10008 if (const ::testing::AssertionResult gtest_ar = (expression)) \
10009 ; \
10010 else \
10011 on_failure(gtest_ar.failure_message())
10012
10013
10014 // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
10015 // this in your code.
10016 template <typename Pred,
10017 typename T1>
10018 AssertionResult AssertPred1Helper(const char* pred_text,
10019 const char* e1,
10020 Pred pred,
10021 const T1& v1) {
10022 if (pred(v1)) return AssertionSuccess();
10023
10024 return AssertionFailure()
10025 << pred_text << "(" << e1 << ") evaluates to false, where"
10026 << "\n"
10027 << e1 << " evaluates to " << ::testing::PrintToString(v1);
10028 }
10029
10030 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
10031 // Don't use this in your code.
10032 #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
10033 GTEST_ASSERT_(pred_format(#v1, v1), \
10034 on_failure)
10035
10036 // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
10037 // this in your code.
10038 #define GTEST_PRED1_(pred, v1, on_failure)\
10039 GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
10040 #v1, \
10041 pred, \
10042 v1), on_failure)
10043
10044 // Unary predicate assertion macros.
10045 #define EXPECT_PRED_FORMAT1(pred_format, v1) \
10046 GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
10047 #define EXPECT_PRED1(pred, v1) \
10048 GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
10049 #define ASSERT_PRED_FORMAT1(pred_format, v1) \
10050 GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
10051 #define ASSERT_PRED1(pred, v1) \
10052 GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
10053
10054
10055
10056 // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
10057 // this in your code.
10058 template <typename Pred,
10059 typename T1,
10060 typename T2>
10061 AssertionResult AssertPred2Helper(const char* pred_text,
10062 const char* e1,
10063 const char* e2,
10064 Pred pred,
10065 const T1& v1,
10066 const T2& v2) {
10067 if (pred(v1, v2)) return AssertionSuccess();
10068
10069 return AssertionFailure()
10070 << pred_text << "(" << e1 << ", " << e2
10071 << ") evaluates to false, where"
10072 << "\n"
10073 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10074 << e2 << " evaluates to " << ::testing::PrintToString(v2);
10075 }
10076
10077 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
10078 // Don't use this in your code.
10079 #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
10080 GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
10081 on_failure)
10082
10083 // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
10084 // this in your code.
10085 #define GTEST_PRED2_(pred, v1, v2, on_failure)\
10086 GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
10087 #v1, \
10088 #v2, \
10089 pred, \
10090 v1, \
10091 v2), on_failure)
10092
10093 // Binary predicate assertion macros.
10094 #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
10095 GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
10096 #define EXPECT_PRED2(pred, v1, v2) \
10097 GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
10098 #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
10099 GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
10100 #define ASSERT_PRED2(pred, v1, v2) \
10101 GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
10102
10103
10104
10105 // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
10106 // this in your code.
10107 template <typename Pred,
10108 typename T1,
10109 typename T2,
10110 typename T3>
10111 AssertionResult AssertPred3Helper(const char* pred_text,
10112 const char* e1,
10113 const char* e2,
10114 const char* e3,
10115 Pred pred,
10116 const T1& v1,
10117 const T2& v2,
10118 const T3& v3) {
10119 if (pred(v1, v2, v3)) return AssertionSuccess();
10120
10121 return AssertionFailure()
10122 << pred_text << "(" << e1 << ", " << e2 << ", " << e3
10123 << ") evaluates to false, where"
10124 << "\n"
10125 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10126 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10127 << e3 << " evaluates to " << ::testing::PrintToString(v3);
10128 }
10129
10130 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
10131 // Don't use this in your code.
10132 #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
10133 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
10134 on_failure)
10135
10136 // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
10137 // this in your code.
10138 #define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
10139 GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
10140 #v1, \
10141 #v2, \
10142 #v3, \
10143 pred, \
10144 v1, \
10145 v2, \
10146 v3), on_failure)
10147
10148 // Ternary predicate assertion macros.
10149 #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
10150 GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
10151 #define EXPECT_PRED3(pred, v1, v2, v3) \
10152 GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
10153 #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
10154 GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
10155 #define ASSERT_PRED3(pred, v1, v2, v3) \
10156 GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
10157
10158
10159
10160 // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
10161 // this in your code.
10162 template <typename Pred,
10163 typename T1,
10164 typename T2,
10165 typename T3,
10166 typename T4>
10167 AssertionResult AssertPred4Helper(const char* pred_text,
10168 const char* e1,
10169 const char* e2,
10170 const char* e3,
10171 const char* e4,
10172 Pred pred,
10173 const T1& v1,
10174 const T2& v2,
10175 const T3& v3,
10176 const T4& v4) {
10177 if (pred(v1, v2, v3, v4)) return AssertionSuccess();
10178
10179 return AssertionFailure()
10180 << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
10181 << ") evaluates to false, where"
10182 << "\n"
10183 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10184 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10185 << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
10186 << e4 << " evaluates to " << ::testing::PrintToString(v4);
10187 }
10188
10189 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
10190 // Don't use this in your code.
10191 #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
10192 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
10193 on_failure)
10194
10195 // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
10196 // this in your code.
10197 #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
10198 GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
10199 #v1, \
10200 #v2, \
10201 #v3, \
10202 #v4, \
10203 pred, \
10204 v1, \
10205 v2, \
10206 v3, \
10207 v4), on_failure)
10208
10209 // 4-ary predicate assertion macros.
10210 #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
10211 GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
10212 #define EXPECT_PRED4(pred, v1, v2, v3, v4) \
10213 GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
10214 #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
10215 GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
10216 #define ASSERT_PRED4(pred, v1, v2, v3, v4) \
10217 GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
10218
10219
10220
10221 // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
10222 // this in your code.
10223 template <typename Pred,
10224 typename T1,
10225 typename T2,
10226 typename T3,
10227 typename T4,
10228 typename T5>
10229 AssertionResult AssertPred5Helper(const char* pred_text,
10230 const char* e1,
10231 const char* e2,
10232 const char* e3,
10233 const char* e4,
10234 const char* e5,
10235 Pred pred,
10236 const T1& v1,
10237 const T2& v2,
10238 const T3& v3,
10239 const T4& v4,
10240 const T5& v5) {
10241 if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
10242
10243 return AssertionFailure()
10244 << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
10245 << ", " << e5 << ") evaluates to false, where"
10246 << "\n"
10247 << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10248 << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10249 << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
10250 << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n"
10251 << e5 << " evaluates to " << ::testing::PrintToString(v5);
10252 }
10253
10254 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
10255 // Don't use this in your code.
10256 #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
10257 GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
10258 on_failure)
10259
10260 // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
10261 // this in your code.
10262 #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
10263 GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
10264 #v1, \
10265 #v2, \
10266 #v3, \
10267 #v4, \
10268 #v5, \
10269 pred, \
10270 v1, \
10271 v2, \
10272 v3, \
10273 v4, \
10274 v5), on_failure)
10275
10276 // 5-ary predicate assertion macros.
10277 #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
10278 GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
10279 #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
10280 GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
10281 #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
10282 GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
10283 #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
10284 GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
10285
10286
10287
10288 } // namespace testing
10289
10290 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
10291
10292 namespace testing {
10293
10294 // The abstract class that all tests inherit from.
10295 //
10296 // In Google Test, a unit test program contains one or many TestSuites, and
10297 // each TestSuite contains one or many Tests.
10298 //
10299 // When you define a test using the TEST macro, you don't need to
10300 // explicitly derive from Test - the TEST macro automatically does
10301 // this for you.
10302 //
10303 // The only time you derive from Test is when defining a test fixture
10304 // to be used in a TEST_F. For example:
10305 //
10306 // class FooTest : public testing::Test {
10307 // protected:
10308 // void SetUp() override { ... }
10309 // void TearDown() override { ... }
10310 // ...
10311 // };
10312 //
10313 // TEST_F(FooTest, Bar) { ... }
10314 // TEST_F(FooTest, Baz) { ... }
10315 //
10316 // Test is not copyable.
10317 class GTEST_API_ Test {
10318 public:
10319 friend class TestInfo;
10320
10321 // The d'tor is virtual as we intend to inherit from Test.
10322 virtual ~Test();
10323
10324 // Sets up the stuff shared by all tests in this test suite.
10325 //
10326 // Google Test will call Foo::SetUpTestSuite() before running the first
10327 // test in test suite Foo. Hence a sub-class can define its own
10328 // SetUpTestSuite() method to shadow the one defined in the super
10329 // class.
10330 static void SetUpTestSuite() {}
10331
10332 // Tears down the stuff shared by all tests in this test suite.
10333 //
10334 // Google Test will call Foo::TearDownTestSuite() after running the last
10335 // test in test suite Foo. Hence a sub-class can define its own
10336 // TearDownTestSuite() method to shadow the one defined in the super
10337 // class.
10338 static void TearDownTestSuite() {}
10339
10340 // Legacy API is deprecated but still available. Use SetUpTestSuite and
10341 // TearDownTestSuite instead.
10342 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10343 static void TearDownTestCase() {}
10344 static void SetUpTestCase() {}
10345 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10346
10347 // Returns true if and only if the current test has a fatal failure.
10348 static bool HasFatalFailure();
10349
10350 // Returns true if and only if the current test has a non-fatal failure.
10351 static bool HasNonfatalFailure();
10352
10353 // Returns true if and only if the current test was skipped.
10354 static bool IsSkipped();
10355
10356 // Returns true if and only if the current test has a (either fatal or
10357 // non-fatal) failure.
10358 static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
10359
10360 // Logs a property for the current test, test suite, or for the entire
10361 // invocation of the test program when used outside of the context of a
10362 // test suite. Only the last value for a given key is remembered. These
10363 // are public static so they can be called from utility functions that are
10364 // not members of the test fixture. Calls to RecordProperty made during
10365 // lifespan of the test (from the moment its constructor starts to the
10366 // moment its destructor finishes) will be output in XML as attributes of
10367 // the <testcase> element. Properties recorded from fixture's
10368 // SetUpTestSuite or TearDownTestSuite are logged as attributes of the
10369 // corresponding <testsuite> element. Calls to RecordProperty made in the
10370 // global context (before or after invocation of RUN_ALL_TESTS and from
10371 // SetUp/TearDown method of Environment objects registered with Google
10372 // Test) will be output as attributes of the <testsuites> element.
10373 static void RecordProperty(const std::string& key, const std::string& value);
10374 static void RecordProperty(const std::string& key, int value);
10375
10376 protected:
10377 // Creates a Test object.
10378 Test();
10379
10380 // Sets up the test fixture.
10381 virtual void SetUp();
10382
10383 // Tears down the test fixture.
10384 virtual void TearDown();
10385
10386 private:
10387 // Returns true if and only if the current test has the same fixture class
10388 // as the first test in the current test suite.
10389 static bool HasSameFixtureClass();
10390
10391 // Runs the test after the test fixture has been set up.
10392 //
10393 // A sub-class must implement this to define the test logic.
10394 //
10395 // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
10396 // Instead, use the TEST or TEST_F macro.
10397 virtual void TestBody() = 0;
10398
10399 // Sets up, executes, and tears down the test.
10400 void Run();
10401
10402 // Deletes self. We deliberately pick an unusual name for this
10403 // internal method to avoid clashing with names used in user TESTs.
10404 void DeleteSelf_() { delete this; }
10405
10406 const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;
10407
10408 // Often a user misspells SetUp() as Setup() and spends a long time
10409 // wondering why it is never called by Google Test. The declaration of
10410 // the following method is solely for catching such an error at
10411 // compile time:
10412 //
10413 // - The return type is deliberately chosen to be not void, so it
10414 // will be a conflict if void Setup() is declared in the user's
10415 // test fixture.
10416 //
10417 // - This method is private, so it will be another compiler error
10418 // if the method is called from the user's test fixture.
10419 //
10420 // DO NOT OVERRIDE THIS FUNCTION.
10421 //
10422 // If you see an error about overriding the following function or
10423 // about it being private, you have mis-spelled SetUp() as Setup().
10424 struct Setup_should_be_spelled_SetUp {};
10425 virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
10426
10427 // We disallow copying Tests.
10428 GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
10429 };
10430
10431 typedef internal::TimeInMillis TimeInMillis;
10432
10433 // A copyable object representing a user specified test property which can be
10434 // output as a key/value string pair.
10435 //
10436 // Don't inherit from TestProperty as its destructor is not virtual.
10437 class TestProperty {
10438 public:
10439 // C'tor. TestProperty does NOT have a default constructor.
10440 // Always use this constructor (with parameters) to create a
10441 // TestProperty object.
10442 TestProperty(const std::string& a_key, const std::string& a_value) :
10443 key_(a_key), value_(a_value) {
10444 }
10445
10446 // Gets the user supplied key.
10447 const char* key() const {
10448 return key_.c_str();
10449 }
10450
10451 // Gets the user supplied value.
10452 const char* value() const {
10453 return value_.c_str();
10454 }
10455
10456 // Sets a new value, overriding the one supplied in the constructor.
10457 void SetValue(const std::string& new_value) {
10458 value_ = new_value;
10459 }
10460
10461 private:
10462 // The key supplied by the user.
10463 std::string key_;
10464 // The value supplied by the user.
10465 std::string value_;
10466 };
10467
10468 // The result of a single Test. This includes a list of
10469 // TestPartResults, a list of TestProperties, a count of how many
10470 // death tests there are in the Test, and how much time it took to run
10471 // the Test.
10472 //
10473 // TestResult is not copyable.
10474 class GTEST_API_ TestResult {
10475 public:
10476 // Creates an empty TestResult.
10477 TestResult();
10478
10479 // D'tor. Do not inherit from TestResult.
10480 ~TestResult();
10481
10482 // Gets the number of all test parts. This is the sum of the number
10483 // of successful test parts and the number of failed test parts.
10484 int total_part_count() const;
10485
10486 // Returns the number of the test properties.
10487 int test_property_count() const;
10488
10489 // Returns true if and only if the test passed (i.e. no test part failed).
10490 bool Passed() const { return !Skipped() && !Failed(); }
10491
10492 // Returns true if and only if the test was skipped.
10493 bool Skipped() const;
10494
10495 // Returns true if and only if the test failed.
10496 bool Failed() const;
10497
10498 // Returns true if and only if the test fatally failed.
10499 bool HasFatalFailure() const;
10500
10501 // Returns true if and only if the test has a non-fatal failure.
10502 bool HasNonfatalFailure() const;
10503
10504 // Returns the elapsed time, in milliseconds.
10505 TimeInMillis elapsed_time() const { return elapsed_time_; }
10506
10507 // Gets the time of the test case start, in ms from the start of the
10508 // UNIX epoch.
10509 TimeInMillis start_timestamp() const { return start_timestamp_; }
10510
10511 // Returns the i-th test part result among all the results. i can range from 0
10512 // to total_part_count() - 1. If i is not in that range, aborts the program.
10513 const TestPartResult& GetTestPartResult(int i) const;
10514
10515 // Returns the i-th test property. i can range from 0 to
10516 // test_property_count() - 1. If i is not in that range, aborts the
10517 // program.
10518 const TestProperty& GetTestProperty(int i) const;
10519
10520 private:
10521 friend class TestInfo;
10522 friend class TestSuite;
10523 friend class UnitTest;
10524 friend class internal::DefaultGlobalTestPartResultReporter;
10525 friend class internal::ExecDeathTest;
10526 friend class internal::TestResultAccessor;
10527 friend class internal::UnitTestImpl;
10528 friend class internal::WindowsDeathTest;
10529 friend class internal::FuchsiaDeathTest;
10530
10531 // Gets the vector of TestPartResults.
10532 const std::vector<TestPartResult>& test_part_results() const {
10533 return test_part_results_;
10534 }
10535
10536 // Gets the vector of TestProperties.
10537 const std::vector<TestProperty>& test_properties() const {
10538 return test_properties_;
10539 }
10540
10541 // Sets the start time.
10542 void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }
10543
10544 // Sets the elapsed time.
10545 void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
10546
10547 // Adds a test property to the list. The property is validated and may add
10548 // a non-fatal failure if invalid (e.g., if it conflicts with reserved
10549 // key names). If a property is already recorded for the same key, the
10550 // value will be updated, rather than storing multiple values for the same
10551 // key. xml_element specifies the element for which the property is being
10552 // recorded and is used for validation.
10553 void RecordProperty(const std::string& xml_element,
10554 const TestProperty& test_property);
10555
10556 // Adds a failure if the key is a reserved attribute of Google Test
10557 // testsuite tags. Returns true if the property is valid.
10558 // FIXME: Validate attribute names are legal and human readable.
10559 static bool ValidateTestProperty(const std::string& xml_element,
10560 const TestProperty& test_property);
10561
10562 // Adds a test part result to the list.
10563 void AddTestPartResult(const TestPartResult& test_part_result);
10564
10565 // Returns the death test count.
10566 int death_test_count() const { return death_test_count_; }
10567
10568 // Increments the death test count, returning the new count.
10569 int increment_death_test_count() { return ++death_test_count_; }
10570
10571 // Clears the test part results.
10572 void ClearTestPartResults();
10573
10574 // Clears the object.
10575 void Clear();
10576
10577 // Protects mutable state of the property vector and of owned
10578 // properties, whose values may be updated.
10579 internal::Mutex test_properties_mutex_;
10580
10581 // The vector of TestPartResults
10582 std::vector<TestPartResult> test_part_results_;
10583 // The vector of TestProperties
10584 std::vector<TestProperty> test_properties_;
10585 // Running count of death tests.
10586 int death_test_count_;
10587 // The start time, in milliseconds since UNIX Epoch.
10588 TimeInMillis start_timestamp_;
10589 // The elapsed time, in milliseconds.
10590 TimeInMillis elapsed_time_;
10591
10592 // We disallow copying TestResult.
10593 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
10594 }; // class TestResult
10595
10596 // A TestInfo object stores the following information about a test:
10597 //
10598 // Test suite name
10599 // Test name
10600 // Whether the test should be run
10601 // A function pointer that creates the test object when invoked
10602 // Test result
10603 //
10604 // The constructor of TestInfo registers itself with the UnitTest
10605 // singleton such that the RUN_ALL_TESTS() macro knows which tests to
10606 // run.
10607 class GTEST_API_ TestInfo {
10608 public:
10609 // Destructs a TestInfo object. This function is not virtual, so
10610 // don't inherit from TestInfo.
10611 ~TestInfo();
10612
10613 // Returns the test suite name.
10614 const char* test_suite_name() const { return test_suite_name_.c_str(); }
10615
10616 // Legacy API is deprecated but still available
10617 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10618 const char* test_case_name() const { return test_suite_name(); }
10619 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10620
10621 // Returns the test name.
10622 const char* name() const { return name_.c_str(); }
10623
10624 // Returns the name of the parameter type, or NULL if this is not a typed
10625 // or a type-parameterized test.
10626 const char* type_param() const {
10627 if (type_param_.get() != nullptr) return type_param_->c_str();
10628 return nullptr;
10629 }
10630
10631 // Returns the text representation of the value parameter, or NULL if this
10632 // is not a value-parameterized test.
10633 const char* value_param() const {
10634 if (value_param_.get() != nullptr) return value_param_->c_str();
10635 return nullptr;
10636 }
10637
10638 // Returns the file name where this test is defined.
10639 const char* file() const { return location_.file.c_str(); }
10640
10641 // Returns the line where this test is defined.
10642 int line() const { return location_.line; }
10643
10644 // Return true if this test should not be run because it's in another shard.
10645 bool is_in_another_shard() const { return is_in_another_shard_; }
10646
10647 // Returns true if this test should run, that is if the test is not
10648 // disabled (or it is disabled but the also_run_disabled_tests flag has
10649 // been specified) and its full name matches the user-specified filter.
10650 //
10651 // Google Test allows the user to filter the tests by their full names.
10652 // The full name of a test Bar in test suite Foo is defined as
10653 // "Foo.Bar". Only the tests that match the filter will run.
10654 //
10655 // A filter is a colon-separated list of glob (not regex) patterns,
10656 // optionally followed by a '-' and a colon-separated list of
10657 // negative patterns (tests to exclude). A test is run if it
10658 // matches one of the positive patterns and does not match any of
10659 // the negative patterns.
10660 //
10661 // For example, *A*:Foo.* is a filter that matches any string that
10662 // contains the character 'A' or starts with "Foo.".
10663 bool should_run() const { return should_run_; }
10664
10665 // Returns true if and only if this test will appear in the XML report.
10666 bool is_reportable() const {
10667 // The XML report includes tests matching the filter, excluding those
10668 // run in other shards.
10669 return matches_filter_ && !is_in_another_shard_;
10670 }
10671
10672 // Returns the result of the test.
10673 const TestResult* result() const { return &result_; }
10674
10675 private:
10676 #if GTEST_HAS_DEATH_TEST
10677 friend class internal::DefaultDeathTestFactory;
10678 #endif // GTEST_HAS_DEATH_TEST
10679 friend class Test;
10680 friend class TestSuite;
10681 friend class internal::UnitTestImpl;
10682 friend class internal::StreamingListenerTest;
10683 friend TestInfo* internal::MakeAndRegisterTestInfo(
10684 const char* test_suite_name, const char* name, const char* type_param,
10685 const char* value_param, internal::CodeLocation code_location,
10686 internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
10687 internal::TearDownTestSuiteFunc tear_down_tc,
10688 internal::TestFactoryBase* factory);
10689
10690 // Constructs a TestInfo object. The newly constructed instance assumes
10691 // ownership of the factory object.
10692 TestInfo(const std::string& test_suite_name, const std::string& name,
10693 const char* a_type_param, // NULL if not a type-parameterized test
10694 const char* a_value_param, // NULL if not a value-parameterized test
10695 internal::CodeLocation a_code_location,
10696 internal::TypeId fixture_class_id,
10697 internal::TestFactoryBase* factory);
10698
10699 // Increments the number of death tests encountered in this test so
10700 // far.
10701 int increment_death_test_count() {
10702 return result_.increment_death_test_count();
10703 }
10704
10705 // Creates the test object, runs it, records its result, and then
10706 // deletes it.
10707 void Run();
10708
10709 // Skip and records the test result for this object.
10710 void Skip();
10711
10712 static void ClearTestResult(TestInfo* test_info) {
10713 test_info->result_.Clear();
10714 }
10715
10716 // These fields are immutable properties of the test.
10717 const std::string test_suite_name_; // test suite name
10718 const std::string name_; // Test name
10719 // Name of the parameter type, or NULL if this is not a typed or a
10720 // type-parameterized test.
10721 const std::unique_ptr<const ::std::string> type_param_;
10722 // Text representation of the value parameter, or NULL if this is not a
10723 // value-parameterized test.
10724 const std::unique_ptr<const ::std::string> value_param_;
10725 internal::CodeLocation location_;
10726 const internal::TypeId fixture_class_id_; // ID of the test fixture class
10727 bool should_run_; // True if and only if this test should run
10728 bool is_disabled_; // True if and only if this test is disabled
10729 bool matches_filter_; // True if this test matches the
10730 // user-specified filter.
10731 bool is_in_another_shard_; // Will be run in another shard.
10732 internal::TestFactoryBase* const factory_; // The factory that creates
10733 // the test object
10734
10735 // This field is mutable and needs to be reset before running the
10736 // test for the second time.
10737 TestResult result_;
10738
10739 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
10740 };
10741
10742 // A test suite, which consists of a vector of TestInfos.
10743 //
10744 // TestSuite is not copyable.
10745 class GTEST_API_ TestSuite {
10746 public:
10747 // Creates a TestSuite with the given name.
10748 //
10749 // TestSuite does NOT have a default constructor. Always use this
10750 // constructor to create a TestSuite object.
10751 //
10752 // Arguments:
10753 //
10754 // name: name of the test suite
10755 // a_type_param: the name of the test's type parameter, or NULL if
10756 // this is not a type-parameterized test.
10757 // set_up_tc: pointer to the function that sets up the test suite
10758 // tear_down_tc: pointer to the function that tears down the test suite
10759 TestSuite(const char* name, const char* a_type_param,
10760 internal::SetUpTestSuiteFunc set_up_tc,
10761 internal::TearDownTestSuiteFunc tear_down_tc);
10762
10763 // Destructor of TestSuite.
10764 virtual ~TestSuite();
10765
10766 // Gets the name of the TestSuite.
10767 const char* name() const { return name_.c_str(); }
10768
10769 // Returns the name of the parameter type, or NULL if this is not a
10770 // type-parameterized test suite.
10771 const char* type_param() const {
10772 if (type_param_.get() != nullptr) return type_param_->c_str();
10773 return nullptr;
10774 }
10775
10776 // Returns true if any test in this test suite should run.
10777 bool should_run() const { return should_run_; }
10778
10779 // Gets the number of successful tests in this test suite.
10780 int successful_test_count() const;
10781
10782 // Gets the number of skipped tests in this test suite.
10783 int skipped_test_count() const;
10784
10785 // Gets the number of failed tests in this test suite.
10786 int failed_test_count() const;
10787
10788 // Gets the number of disabled tests that will be reported in the XML report.
10789 int reportable_disabled_test_count() const;
10790
10791 // Gets the number of disabled tests in this test suite.
10792 int disabled_test_count() const;
10793
10794 // Gets the number of tests to be printed in the XML report.
10795 int reportable_test_count() const;
10796
10797 // Get the number of tests in this test suite that should run.
10798 int test_to_run_count() const;
10799
10800 // Gets the number of all tests in this test suite.
10801 int total_test_count() const;
10802
10803 // Returns true if and only if the test suite passed.
10804 bool Passed() const { return !Failed(); }
10805
10806 // Returns true if and only if the test suite failed.
10807 bool Failed() const {
10808 return failed_test_count() > 0 || ad_hoc_test_result().Failed();
10809 }
10810
10811 // Returns the elapsed time, in milliseconds.
10812 TimeInMillis elapsed_time() const { return elapsed_time_; }
10813
10814 // Gets the time of the test suite start, in ms from the start of the
10815 // UNIX epoch.
10816 TimeInMillis start_timestamp() const { return start_timestamp_; }
10817
10818 // Returns the i-th test among all the tests. i can range from 0 to
10819 // total_test_count() - 1. If i is not in that range, returns NULL.
10820 const TestInfo* GetTestInfo(int i) const;
10821
10822 // Returns the TestResult that holds test properties recorded during
10823 // execution of SetUpTestSuite and TearDownTestSuite.
10824 const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
10825
10826 private:
10827 friend class Test;
10828 friend class internal::UnitTestImpl;
10829
10830 // Gets the (mutable) vector of TestInfos in this TestSuite.
10831 std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
10832
10833 // Gets the (immutable) vector of TestInfos in this TestSuite.
10834 const std::vector<TestInfo*>& test_info_list() const {
10835 return test_info_list_;
10836 }
10837
10838 // Returns the i-th test among all the tests. i can range from 0 to
10839 // total_test_count() - 1. If i is not in that range, returns NULL.
10840 TestInfo* GetMutableTestInfo(int i);
10841
10842 // Sets the should_run member.
10843 void set_should_run(bool should) { should_run_ = should; }
10844
10845 // Adds a TestInfo to this test suite. Will delete the TestInfo upon
10846 // destruction of the TestSuite object.
10847 void AddTestInfo(TestInfo * test_info);
10848
10849 // Clears the results of all tests in this test suite.
10850 void ClearResult();
10851
10852 // Clears the results of all tests in the given test suite.
10853 static void ClearTestSuiteResult(TestSuite* test_suite) {
10854 test_suite->ClearResult();
10855 }
10856
10857 // Runs every test in this TestSuite.
10858 void Run();
10859
10860 // Skips the execution of tests under this TestSuite
10861 void Skip();
10862
10863 // Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
10864 // for catching exceptions thrown from SetUpTestSuite().
10865 void RunSetUpTestSuite() {
10866 if (set_up_tc_ != nullptr) {
10867 (*set_up_tc_)();
10868 }
10869 }
10870
10871 // Runs TearDownTestSuite() for this TestSuite. This wrapper is
10872 // needed for catching exceptions thrown from TearDownTestSuite().
10873 void RunTearDownTestSuite() {
10874 if (tear_down_tc_ != nullptr) {
10875 (*tear_down_tc_)();
10876 }
10877 }
10878
10879 // Returns true if and only if test passed.
10880 static bool TestPassed(const TestInfo* test_info) {
10881 return test_info->should_run() && test_info->result()->Passed();
10882 }
10883
10884 // Returns true if and only if test skipped.
10885 static bool TestSkipped(const TestInfo* test_info) {
10886 return test_info->should_run() && test_info->result()->Skipped();
10887 }
10888
10889 // Returns true if and only if test failed.
10890 static bool TestFailed(const TestInfo* test_info) {
10891 return test_info->should_run() && test_info->result()->Failed();
10892 }
10893
10894 // Returns true if and only if the test is disabled and will be reported in
10895 // the XML report.
10896 static bool TestReportableDisabled(const TestInfo* test_info) {
10897 return test_info->is_reportable() && test_info->is_disabled_;
10898 }
10899
10900 // Returns true if and only if test is disabled.
10901 static bool TestDisabled(const TestInfo* test_info) {
10902 return test_info->is_disabled_;
10903 }
10904
10905 // Returns true if and only if this test will appear in the XML report.
10906 static bool TestReportable(const TestInfo* test_info) {
10907 return test_info->is_reportable();
10908 }
10909
10910 // Returns true if the given test should run.
10911 static bool ShouldRunTest(const TestInfo* test_info) {
10912 return test_info->should_run();
10913 }
10914
10915 // Shuffles the tests in this test suite.
10916 void ShuffleTests(internal::Random* random);
10917
10918 // Restores the test order to before the first shuffle.
10919 void UnshuffleTests();
10920
10921 // Name of the test suite.
10922 std::string name_;
10923 // Name of the parameter type, or NULL if this is not a typed or a
10924 // type-parameterized test.
10925 const std::unique_ptr<const ::std::string> type_param_;
10926 // The vector of TestInfos in their original order. It owns the
10927 // elements in the vector.
10928 std::vector<TestInfo*> test_info_list_;
10929 // Provides a level of indirection for the test list to allow easy
10930 // shuffling and restoring the test order. The i-th element in this
10931 // vector is the index of the i-th test in the shuffled test list.
10932 std::vector<int> test_indices_;
10933 // Pointer to the function that sets up the test suite.
10934 internal::SetUpTestSuiteFunc set_up_tc_;
10935 // Pointer to the function that tears down the test suite.
10936 internal::TearDownTestSuiteFunc tear_down_tc_;
10937 // True if and only if any test in this test suite should run.
10938 bool should_run_;
10939 // The start time, in milliseconds since UNIX Epoch.
10940 TimeInMillis start_timestamp_;
10941 // Elapsed time, in milliseconds.
10942 TimeInMillis elapsed_time_;
10943 // Holds test properties recorded during execution of SetUpTestSuite and
10944 // TearDownTestSuite.
10945 TestResult ad_hoc_test_result_;
10946
10947 // We disallow copying TestSuites.
10948 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite);
10949 };
10950
10951 // An Environment object is capable of setting up and tearing down an
10952 // environment. You should subclass this to define your own
10953 // environment(s).
10954 //
10955 // An Environment object does the set-up and tear-down in virtual
10956 // methods SetUp() and TearDown() instead of the constructor and the
10957 // destructor, as:
10958 //
10959 // 1. You cannot safely throw from a destructor. This is a problem
10960 // as in some cases Google Test is used where exceptions are enabled, and
10961 // we may want to implement ASSERT_* using exceptions where they are
10962 // available.
10963 // 2. You cannot use ASSERT_* directly in a constructor or
10964 // destructor.
10965 class Environment {
10966 public:
10967 // The d'tor is virtual as we need to subclass Environment.
10968 virtual ~Environment() {}
10969
10970 // Override this to define how to set up the environment.
10971 virtual void SetUp() {}
10972
10973 // Override this to define how to tear down the environment.
10974 virtual void TearDown() {}
10975 private:
10976 // If you see an error about overriding the following function or
10977 // about it being private, you have mis-spelled SetUp() as Setup().
10978 struct Setup_should_be_spelled_SetUp {};
10979 virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
10980 };
10981
10982 #if GTEST_HAS_EXCEPTIONS
10983
10984 // Exception which can be thrown from TestEventListener::OnTestPartResult.
10985 class GTEST_API_ AssertionException
10986 : public internal::GoogleTestFailureException {
10987 public:
10988 explicit AssertionException(const TestPartResult& result)
10989 : GoogleTestFailureException(result) {}
10990 };
10991
10992 #endif // GTEST_HAS_EXCEPTIONS
10993
10994 // The interface for tracing execution of tests. The methods are organized in
10995 // the order the corresponding events are fired.
10996 class TestEventListener {
10997 public:
10998 virtual ~TestEventListener() {}
10999
11000 // Fired before any test activity starts.
11001 virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
11002
11003 // Fired before each iteration of tests starts. There may be more than
11004 // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
11005 // index, starting from 0.
11006 virtual void OnTestIterationStart(const UnitTest& unit_test,
11007 int iteration) = 0;
11008
11009 // Fired before environment set-up for each iteration of tests starts.
11010 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
11011
11012 // Fired after environment set-up for each iteration of tests ends.
11013 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
11014
11015 // Fired before the test suite starts.
11016 virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}
11017
11018 // Legacy API is deprecated but still available
11019 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11020 virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
11021 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11022
11023 // Fired before the test starts.
11024 virtual void OnTestStart(const TestInfo& test_info) = 0;
11025
11026 // Fired after a failed assertion or a SUCCEED() invocation.
11027 // If you want to throw an exception from this function to skip to the next
11028 // TEST, it must be AssertionException defined above, or inherited from it.
11029 virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
11030
11031 // Fired after the test ends.
11032 virtual void OnTestEnd(const TestInfo& test_info) = 0;
11033
11034 // Fired after the test suite ends.
11035 virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}
11036
11037 // Legacy API is deprecated but still available
11038 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11039 virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
11040 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11041
11042 // Fired before environment tear-down for each iteration of tests starts.
11043 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
11044
11045 // Fired after environment tear-down for each iteration of tests ends.
11046 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
11047
11048 // Fired after each iteration of tests finishes.
11049 virtual void OnTestIterationEnd(const UnitTest& unit_test,
11050 int iteration) = 0;
11051
11052 // Fired after all test activities have ended.
11053 virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
11054 };
11055
11056 // The convenience class for users who need to override just one or two
11057 // methods and are not concerned that a possible change to a signature of
11058 // the methods they override will not be caught during the build. For
11059 // comments about each method please see the definition of TestEventListener
11060 // above.
11061 class EmptyTestEventListener : public TestEventListener {
11062 public:
11063 void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
11064 void OnTestIterationStart(const UnitTest& /*unit_test*/,
11065 int /*iteration*/) override {}
11066 void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
11067 void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
11068 void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
11069 // Legacy API is deprecated but still available
11070 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11071 void OnTestCaseStart(const TestCase& /*test_case*/) override {}
11072 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11073
11074 void OnTestStart(const TestInfo& /*test_info*/) override {}
11075 void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
11076 void OnTestEnd(const TestInfo& /*test_info*/) override {}
11077 void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
11078 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11079 void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
11080 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11081
11082 void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
11083 void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
11084 void OnTestIterationEnd(const UnitTest& /*unit_test*/,
11085 int /*iteration*/) override {}
11086 void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
11087 };
11088
11089 // TestEventListeners lets users add listeners to track events in Google Test.
11090 class GTEST_API_ TestEventListeners {
11091 public:
11092 TestEventListeners();
11093 ~TestEventListeners();
11094
11095 // Appends an event listener to the end of the list. Google Test assumes
11096 // the ownership of the listener (i.e. it will delete the listener when
11097 // the test program finishes).
11098 void Append(TestEventListener* listener);
11099
11100 // Removes the given event listener from the list and returns it. It then
11101 // becomes the caller's responsibility to delete the listener. Returns
11102 // NULL if the listener is not found in the list.
11103 TestEventListener* Release(TestEventListener* listener);
11104
11105 // Returns the standard listener responsible for the default console
11106 // output. Can be removed from the listeners list to shut down default
11107 // console output. Note that removing this object from the listener list
11108 // with Release transfers its ownership to the caller and makes this
11109 // function return NULL the next time.
11110 TestEventListener* default_result_printer() const {
11111 return default_result_printer_;
11112 }
11113
11114 // Returns the standard listener responsible for the default XML output
11115 // controlled by the --gtest_output=xml flag. Can be removed from the
11116 // listeners list by users who want to shut down the default XML output
11117 // controlled by this flag and substitute it with custom one. Note that
11118 // removing this object from the listener list with Release transfers its
11119 // ownership to the caller and makes this function return NULL the next
11120 // time.
11121 TestEventListener* default_xml_generator() const {
11122 return default_xml_generator_;
11123 }
11124
11125 private:
11126 friend class TestSuite;
11127 friend class TestInfo;
11128 friend class internal::DefaultGlobalTestPartResultReporter;
11129 friend class internal::NoExecDeathTest;
11130 friend class internal::TestEventListenersAccessor;
11131 friend class internal::UnitTestImpl;
11132
11133 // Returns repeater that broadcasts the TestEventListener events to all
11134 // subscribers.
11135 TestEventListener* repeater();
11136
11137 // Sets the default_result_printer attribute to the provided listener.
11138 // The listener is also added to the listener list and previous
11139 // default_result_printer is removed from it and deleted. The listener can
11140 // also be NULL in which case it will not be added to the list. Does
11141 // nothing if the previous and the current listener objects are the same.
11142 void SetDefaultResultPrinter(TestEventListener* listener);
11143
11144 // Sets the default_xml_generator attribute to the provided listener. The
11145 // listener is also added to the listener list and previous
11146 // default_xml_generator is removed from it and deleted. The listener can
11147 // also be NULL in which case it will not be added to the list. Does
11148 // nothing if the previous and the current listener objects are the same.
11149 void SetDefaultXmlGenerator(TestEventListener* listener);
11150
11151 // Controls whether events will be forwarded by the repeater to the
11152 // listeners in the list.
11153 bool EventForwardingEnabled() const;
11154 void SuppressEventForwarding();
11155
11156 // The actual list of listeners.
11157 internal::TestEventRepeater* repeater_;
11158 // Listener responsible for the standard result output.
11159 TestEventListener* default_result_printer_;
11160 // Listener responsible for the creation of the XML output file.
11161 TestEventListener* default_xml_generator_;
11162
11163 // We disallow copying TestEventListeners.
11164 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
11165 };
11166
11167 // A UnitTest consists of a vector of TestSuites.
11168 //
11169 // This is a singleton class. The only instance of UnitTest is
11170 // created when UnitTest::GetInstance() is first called. This
11171 // instance is never deleted.
11172 //
11173 // UnitTest is not copyable.
11174 //
11175 // This class is thread-safe as long as the methods are called
11176 // according to their specification.
11177 class GTEST_API_ UnitTest {
11178 public:
11179 // Gets the singleton UnitTest object. The first time this method
11180 // is called, a UnitTest object is constructed and returned.
11181 // Consecutive calls will return the same object.
11182 static UnitTest* GetInstance();
11183
11184 // Runs all tests in this UnitTest object and prints the result.
11185 // Returns 0 if successful, or 1 otherwise.
11186 //
11187 // This method can only be called from the main thread.
11188 //
11189 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11190 int Run() GTEST_MUST_USE_RESULT_;
11191
11192 // Returns the working directory when the first TEST() or TEST_F()
11193 // was executed. The UnitTest object owns the string.
11194 const char* original_working_dir() const;
11195
11196 // Returns the TestSuite object for the test that's currently running,
11197 // or NULL if no test is running.
11198 const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);
11199
11200 // Legacy API is still available but deprecated
11201 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11202 const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);
11203 #endif
11204
11205 // Returns the TestInfo object for the test that's currently running,
11206 // or NULL if no test is running.
11207 const TestInfo* current_test_info() const
11208 GTEST_LOCK_EXCLUDED_(mutex_);
11209
11210 // Returns the random seed used at the start of the current test run.
11211 int random_seed() const;
11212
11213 // Returns the ParameterizedTestSuiteRegistry object used to keep track of
11214 // value-parameterized tests and instantiate and register them.
11215 //
11216 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11217 internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()
11218 GTEST_LOCK_EXCLUDED_(mutex_);
11219
11220 // Gets the number of successful test suites.
11221 int successful_test_suite_count() const;
11222
11223 // Gets the number of failed test suites.
11224 int failed_test_suite_count() const;
11225
11226 // Gets the number of all test suites.
11227 int total_test_suite_count() const;
11228
11229 // Gets the number of all test suites that contain at least one test
11230 // that should run.
11231 int test_suite_to_run_count() const;
11232
11233 // Legacy API is deprecated but still available
11234 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11235 int successful_test_case_count() const;
11236 int failed_test_case_count() const;
11237 int total_test_case_count() const;
11238 int test_case_to_run_count() const;
11239 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11240
11241 // Gets the number of successful tests.
11242 int successful_test_count() const;
11243
11244 // Gets the number of skipped tests.
11245 int skipped_test_count() const;
11246
11247 // Gets the number of failed tests.
11248 int failed_test_count() const;
11249
11250 // Gets the number of disabled tests that will be reported in the XML report.
11251 int reportable_disabled_test_count() const;
11252
11253 // Gets the number of disabled tests.
11254 int disabled_test_count() const;
11255
11256 // Gets the number of tests to be printed in the XML report.
11257 int reportable_test_count() const;
11258
11259 // Gets the number of all tests.
11260 int total_test_count() const;
11261
11262 // Gets the number of tests that should run.
11263 int test_to_run_count() const;
11264
11265 // Gets the time of the test program start, in ms from the start of the
11266 // UNIX epoch.
11267 TimeInMillis start_timestamp() const;
11268
11269 // Gets the elapsed time, in milliseconds.
11270 TimeInMillis elapsed_time() const;
11271
11272 // Returns true if and only if the unit test passed (i.e. all test suites
11273 // passed).
11274 bool Passed() const;
11275
11276 // Returns true if and only if the unit test failed (i.e. some test suite
11277 // failed or something outside of all tests failed).
11278 bool Failed() const;
11279
11280 // Gets the i-th test suite among all the test suites. i can range from 0 to
11281 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
11282 const TestSuite* GetTestSuite(int i) const;
11283
11284 // Legacy API is deprecated but still available
11285 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11286 const TestCase* GetTestCase(int i) const;
11287 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11288
11289 // Returns the TestResult containing information on test failures and
11290 // properties logged outside of individual test suites.
11291 const TestResult& ad_hoc_test_result() const;
11292
11293 // Returns the list of event listeners that can be used to track events
11294 // inside Google Test.
11295 TestEventListeners& listeners();
11296
11297 private:
11298 // Registers and returns a global test environment. When a test
11299 // program is run, all global test environments will be set-up in
11300 // the order they were registered. After all tests in the program
11301 // have finished, all global test environments will be torn-down in
11302 // the *reverse* order they were registered.
11303 //
11304 // The UnitTest object takes ownership of the given environment.
11305 //
11306 // This method can only be called from the main thread.
11307 Environment* AddEnvironment(Environment* env);
11308
11309 // Adds a TestPartResult to the current TestResult object. All
11310 // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
11311 // eventually call this to report their results. The user code
11312 // should use the assertion macros instead of calling this directly.
11313 void AddTestPartResult(TestPartResult::Type result_type,
11314 const char* file_name,
11315 int line_number,
11316 const std::string& message,
11317 const std::string& os_stack_trace)
11318 GTEST_LOCK_EXCLUDED_(mutex_);
11319
11320 // Adds a TestProperty to the current TestResult object when invoked from
11321 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
11322 // from SetUpTestSuite or TearDownTestSuite, or to the global property set
11323 // when invoked elsewhere. If the result already contains a property with
11324 // the same key, the value will be updated.
11325 void RecordProperty(const std::string& key, const std::string& value);
11326
11327 // Gets the i-th test suite among all the test suites. i can range from 0 to
11328 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
11329 TestSuite* GetMutableTestSuite(int i);
11330
11331 // Accessors for the implementation object.
11332 internal::UnitTestImpl* impl() { return impl_; }
11333 const internal::UnitTestImpl* impl() const { return impl_; }
11334
11335 // These classes and functions are friends as they need to access private
11336 // members of UnitTest.
11337 friend class ScopedTrace;
11338 friend class Test;
11339 friend class internal::AssertHelper;
11340 friend class internal::StreamingListenerTest;
11341 friend class internal::UnitTestRecordPropertyTestHelper;
11342 friend Environment* AddGlobalTestEnvironment(Environment* env);
11343 friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
11344 friend internal::UnitTestImpl* internal::GetUnitTestImpl();
11345 friend void internal::ReportFailureInUnknownLocation(
11346 TestPartResult::Type result_type,
11347 const std::string& message);
11348
11349 // Creates an empty UnitTest.
11350 UnitTest();
11351
11352 // D'tor
11353 virtual ~UnitTest();
11354
11355 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
11356 // Google Test trace stack.
11357 void PushGTestTrace(const internal::TraceInfo& trace)
11358 GTEST_LOCK_EXCLUDED_(mutex_);
11359
11360 // Pops a trace from the per-thread Google Test trace stack.
11361 void PopGTestTrace()
11362 GTEST_LOCK_EXCLUDED_(mutex_);
11363
11364 // Protects mutable state in *impl_. This is mutable as some const
11365 // methods need to lock it too.
11366 mutable internal::Mutex mutex_;
11367
11368 // Opaque implementation object. This field is never changed once
11369 // the object is constructed. We don't mark it as const here, as
11370 // doing so will cause a warning in the constructor of UnitTest.
11371 // Mutable state in *impl_ is protected by mutex_.
11372 internal::UnitTestImpl* impl_;
11373
11374 // We disallow copying UnitTest.
11375 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
11376 };
11377
11378 // A convenient wrapper for adding an environment for the test
11379 // program.
11380 //
11381 // You should call this before RUN_ALL_TESTS() is called, probably in
11382 // main(). If you use gtest_main, you need to call this before main()
11383 // starts for it to take effect. For example, you can define a global
11384 // variable like this:
11385 //
11386 // testing::Environment* const foo_env =
11387 // testing::AddGlobalTestEnvironment(new FooEnvironment);
11388 //
11389 // However, we strongly recommend you to write your own main() and
11390 // call AddGlobalTestEnvironment() there, as relying on initialization
11391 // of global variables makes the code harder to read and may cause
11392 // problems when you register multiple environments from different
11393 // translation units and the environments have dependencies among them
11394 // (remember that the compiler doesn't guarantee the order in which
11395 // global variables from different translation units are initialized).
11396 inline Environment* AddGlobalTestEnvironment(Environment* env) {
11397 return UnitTest::GetInstance()->AddEnvironment(env);
11398 }
11399
11400 // Initializes Google Test. This must be called before calling
11401 // RUN_ALL_TESTS(). In particular, it parses a command line for the
11402 // flags that Google Test recognizes. Whenever a Google Test flag is
11403 // seen, it is removed from argv, and *argc is decremented.
11404 //
11405 // No value is returned. Instead, the Google Test flag variables are
11406 // updated.
11407 //
11408 // Calling the function for the second time has no user-visible effect.
11409 GTEST_API_ void InitGoogleTest(int* argc, char** argv);
11410
11411 // This overloaded version can be used in Windows programs compiled in
11412 // UNICODE mode.
11413 GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
11414
11415 // This overloaded version can be used on Arduino/embedded platforms where
11416 // there is no argc/argv.
11417 GTEST_API_ void InitGoogleTest();
11418
11419 namespace internal {
11420
11421 // Separate the error generating code from the code path to reduce the stack
11422 // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
11423 // when calling EXPECT_* in a tight loop.
11424 template <typename T1, typename T2>
11425 AssertionResult CmpHelperEQFailure(const char* lhs_expression,
11426 const char* rhs_expression,
11427 const T1& lhs, const T2& rhs) {
11428 return EqFailure(lhs_expression,
11429 rhs_expression,
11430 FormatForComparisonFailureMessage(lhs, rhs),
11431 FormatForComparisonFailureMessage(rhs, lhs),
11432 false);
11433 }
11434
11435 // This block of code defines operator==/!=
11436 // to block lexical scope lookup.
11437 // It prevents using invalid operator==/!= defined at namespace scope.
11438 struct faketype {};
11439 inline bool operator==(faketype, faketype) { return true; }
11440 inline bool operator!=(faketype, faketype) { return false; }
11441
11442 // The helper function for {ASSERT|EXPECT}_EQ.
11443 template <typename T1, typename T2>
11444 AssertionResult CmpHelperEQ(const char* lhs_expression,
11445 const char* rhs_expression,
11446 const T1& lhs,
11447 const T2& rhs) {
11448 if (lhs == rhs) {
11449 return AssertionSuccess();
11450 }
11451
11452 return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
11453 }
11454
11455 class EqHelper {
11456 public:
11457 // This templatized version is for the general case.
11458 template <
11459 typename T1, typename T2,
11460 // Disable this overload for cases where one argument is a pointer
11461 // and the other is the null pointer constant.
11462 typename std::enable_if<!std::is_integral<T1>::value ||
11463 !std::is_pointer<T2>::value>::type* = nullptr>
11464 static AssertionResult Compare(const char* lhs_expression,
11465 const char* rhs_expression, const T1& lhs,
11466 const T2& rhs) {
11467 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
11468 }
11469
11470 // With this overloaded version, we allow anonymous enums to be used
11471 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
11472 // enums can be implicitly cast to BiggestInt.
11473 //
11474 // Even though its body looks the same as the above version, we
11475 // cannot merge the two, as it will make anonymous enums unhappy.
11476 static AssertionResult Compare(const char* lhs_expression,
11477 const char* rhs_expression,
11478 BiggestInt lhs,
11479 BiggestInt rhs) {
11480 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
11481 }
11482
11483 template <typename T>
11484 static AssertionResult Compare(
11485 const char* lhs_expression, const char* rhs_expression,
11486 // Handle cases where '0' is used as a null pointer literal.
11487 std::nullptr_t /* lhs */, T* rhs) {
11488 // We already know that 'lhs' is a null pointer.
11489 return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),
11490 rhs);
11491 }
11492 };
11493
11494 // Separate the error generating code from the code path to reduce the stack
11495 // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
11496 // when calling EXPECT_OP in a tight loop.
11497 template <typename T1, typename T2>
11498 AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
11499 const T1& val1, const T2& val2,
11500 const char* op) {
11501 return AssertionFailure()
11502 << "Expected: (" << expr1 << ") " << op << " (" << expr2
11503 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
11504 << " vs " << FormatForComparisonFailureMessage(val2, val1);
11505 }
11506
11507 // A macro for implementing the helper functions needed to implement
11508 // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
11509 // of similar code.
11510 //
11511 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11512
11513 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
11514 template <typename T1, typename T2>\
11515 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
11516 const T1& val1, const T2& val2) {\
11517 if (val1 op val2) {\
11518 return AssertionSuccess();\
11519 } else {\
11520 return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
11521 }\
11522 }
11523
11524 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11525
11526 // Implements the helper function for {ASSERT|EXPECT}_NE
11527 GTEST_IMPL_CMP_HELPER_(NE, !=)
11528 // Implements the helper function for {ASSERT|EXPECT}_LE
11529 GTEST_IMPL_CMP_HELPER_(LE, <=)
11530 // Implements the helper function for {ASSERT|EXPECT}_LT
11531 GTEST_IMPL_CMP_HELPER_(LT, <)
11532 // Implements the helper function for {ASSERT|EXPECT}_GE
11533 GTEST_IMPL_CMP_HELPER_(GE, >=)
11534 // Implements the helper function for {ASSERT|EXPECT}_GT
11535 GTEST_IMPL_CMP_HELPER_(GT, >)
11536
11537 #undef GTEST_IMPL_CMP_HELPER_
11538
11539 // The helper function for {ASSERT|EXPECT}_STREQ.
11540 //
11541 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11542 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
11543 const char* s2_expression,
11544 const char* s1,
11545 const char* s2);
11546
11547 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
11548 //
11549 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11550 GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
11551 const char* s2_expression,
11552 const char* s1,
11553 const char* s2);
11554
11555 // The helper function for {ASSERT|EXPECT}_STRNE.
11556 //
11557 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11558 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
11559 const char* s2_expression,
11560 const char* s1,
11561 const char* s2);
11562
11563 // The helper function for {ASSERT|EXPECT}_STRCASENE.
11564 //
11565 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11566 GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
11567 const char* s2_expression,
11568 const char* s1,
11569 const char* s2);
11570
11571
11572 // Helper function for *_STREQ on wide strings.
11573 //
11574 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11575 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
11576 const char* s2_expression,
11577 const wchar_t* s1,
11578 const wchar_t* s2);
11579
11580 // Helper function for *_STRNE on wide strings.
11581 //
11582 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11583 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
11584 const char* s2_expression,
11585 const wchar_t* s1,
11586 const wchar_t* s2);
11587
11588 } // namespace internal
11589
11590 // IsSubstring() and IsNotSubstring() are intended to be used as the
11591 // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
11592 // themselves. They check whether needle is a substring of haystack
11593 // (NULL is considered a substring of itself only), and return an
11594 // appropriate error message when they fail.
11595 //
11596 // The {needle,haystack}_expr arguments are the stringified
11597 // expressions that generated the two real arguments.
11598 GTEST_API_ AssertionResult IsSubstring(
11599 const char* needle_expr, const char* haystack_expr,
11600 const char* needle, const char* haystack);
11601 GTEST_API_ AssertionResult IsSubstring(
11602 const char* needle_expr, const char* haystack_expr,
11603 const wchar_t* needle, const wchar_t* haystack);
11604 GTEST_API_ AssertionResult IsNotSubstring(
11605 const char* needle_expr, const char* haystack_expr,
11606 const char* needle, const char* haystack);
11607 GTEST_API_ AssertionResult IsNotSubstring(
11608 const char* needle_expr, const char* haystack_expr,
11609 const wchar_t* needle, const wchar_t* haystack);
11610 GTEST_API_ AssertionResult IsSubstring(
11611 const char* needle_expr, const char* haystack_expr,
11612 const ::std::string& needle, const ::std::string& haystack);
11613 GTEST_API_ AssertionResult IsNotSubstring(
11614 const char* needle_expr, const char* haystack_expr,
11615 const ::std::string& needle, const ::std::string& haystack);
11616
11617 #if GTEST_HAS_STD_WSTRING
11618 GTEST_API_ AssertionResult IsSubstring(
11619 const char* needle_expr, const char* haystack_expr,
11620 const ::std::wstring& needle, const ::std::wstring& haystack);
11621 GTEST_API_ AssertionResult IsNotSubstring(
11622 const char* needle_expr, const char* haystack_expr,
11623 const ::std::wstring& needle, const ::std::wstring& haystack);
11624 #endif // GTEST_HAS_STD_WSTRING
11625
11626 namespace internal {
11627
11628 // Helper template function for comparing floating-points.
11629 //
11630 // Template parameter:
11631 //
11632 // RawType: the raw floating-point type (either float or double)
11633 //
11634 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11635 template <typename RawType>
11636 AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
11637 const char* rhs_expression,
11638 RawType lhs_value,
11639 RawType rhs_value) {
11640 const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
11641
11642 if (lhs.AlmostEquals(rhs)) {
11643 return AssertionSuccess();
11644 }
11645
11646 ::std::stringstream lhs_ss;
11647 lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
11648 << lhs_value;
11649
11650 ::std::stringstream rhs_ss;
11651 rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
11652 << rhs_value;
11653
11654 return EqFailure(lhs_expression,
11655 rhs_expression,
11656 StringStreamToString(&lhs_ss),
11657 StringStreamToString(&rhs_ss),
11658 false);
11659 }
11660
11661 // Helper function for implementing ASSERT_NEAR.
11662 //
11663 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11664 GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
11665 const char* expr2,
11666 const char* abs_error_expr,
11667 double val1,
11668 double val2,
11669 double abs_error);
11670
11671 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
11672 // A class that enables one to stream messages to assertion macros
11673 class GTEST_API_ AssertHelper {
11674 public:
11675 // Constructor.
11676 AssertHelper(TestPartResult::Type type,
11677 const char* file,
11678 int line,
11679 const char* message);
11680 ~AssertHelper();
11681
11682 // Message assignment is a semantic trick to enable assertion
11683 // streaming; see the GTEST_MESSAGE_ macro below.
11684 void operator=(const Message& message) const;
11685
11686 private:
11687 // We put our data in a struct so that the size of the AssertHelper class can
11688 // be as small as possible. This is important because gcc is incapable of
11689 // re-using stack space even for temporary variables, so every EXPECT_EQ
11690 // reserves stack space for another AssertHelper.
11691 struct AssertHelperData {
11692 AssertHelperData(TestPartResult::Type t,
11693 const char* srcfile,
11694 int line_num,
11695 const char* msg)
11696 : type(t), file(srcfile), line(line_num), message(msg) { }
11697
11698 TestPartResult::Type const type;
11699 const char* const file;
11700 int const line;
11701 std::string const message;
11702
11703 private:
11704 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
11705 };
11706
11707 AssertHelperData* const data_;
11708
11709 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
11710 };
11711
11712 } // namespace internal
11713
11714 // The pure interface class that all value-parameterized tests inherit from.
11715 // A value-parameterized class must inherit from both ::testing::Test and
11716 // ::testing::WithParamInterface. In most cases that just means inheriting
11717 // from ::testing::TestWithParam, but more complicated test hierarchies
11718 // may need to inherit from Test and WithParamInterface at different levels.
11719 //
11720 // This interface has support for accessing the test parameter value via
11721 // the GetParam() method.
11722 //
11723 // Use it with one of the parameter generator defining functions, like Range(),
11724 // Values(), ValuesIn(), Bool(), and Combine().
11725 //
11726 // class FooTest : public ::testing::TestWithParam<int> {
11727 // protected:
11728 // FooTest() {
11729 // // Can use GetParam() here.
11730 // }
11731 // ~FooTest() override {
11732 // // Can use GetParam() here.
11733 // }
11734 // void SetUp() override {
11735 // // Can use GetParam() here.
11736 // }
11737 // void TearDown override {
11738 // // Can use GetParam() here.
11739 // }
11740 // };
11741 // TEST_P(FooTest, DoesBar) {
11742 // // Can use GetParam() method here.
11743 // Foo foo;
11744 // ASSERT_TRUE(foo.DoesBar(GetParam()));
11745 // }
11746 // INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
11747
11748 template <typename T>
11749 class WithParamInterface {
11750 public:
11751 typedef T ParamType;
11752 virtual ~WithParamInterface() {}
11753
11754 // The current parameter value. Is also available in the test fixture's
11755 // constructor.
11756 static const ParamType& GetParam() {
11757 GTEST_CHECK_(parameter_ != nullptr)
11758 << "GetParam() can only be called inside a value-parameterized test "
11759 << "-- did you intend to write TEST_P instead of TEST_F?";
11760 return *parameter_;
11761 }
11762
11763 private:
11764 // Sets parameter value. The caller is responsible for making sure the value
11765 // remains alive and unchanged throughout the current test.
11766 static void SetParam(const ParamType* parameter) {
11767 parameter_ = parameter;
11768 }
11769
11770 // Static value used for accessing parameter during a test lifetime.
11771 static const ParamType* parameter_;
11772
11773 // TestClass must be a subclass of WithParamInterface<T> and Test.
11774 template <class TestClass> friend class internal::ParameterizedTestFactory;
11775 };
11776
11777 template <typename T>
11778 const T* WithParamInterface<T>::parameter_ = nullptr;
11779
11780 // Most value-parameterized classes can ignore the existence of
11781 // WithParamInterface, and can just inherit from ::testing::TestWithParam.
11782
11783 template <typename T>
11784 class TestWithParam : public Test, public WithParamInterface<T> {
11785 };
11786
11787 // Macros for indicating success/failure in test code.
11788
11789 // Skips test in runtime.
11790 // Skipping test aborts current function.
11791 // Skipped tests are neither successful nor failed.
11792 #define GTEST_SKIP() GTEST_SKIP_("")
11793
11794 // ADD_FAILURE unconditionally adds a failure to the current test.
11795 // SUCCEED generates a success - it doesn't automatically make the
11796 // current test successful, as a test is only successful when it has
11797 // no failure.
11798 //
11799 // EXPECT_* verifies that a certain condition is satisfied. If not,
11800 // it behaves like ADD_FAILURE. In particular:
11801 //
11802 // EXPECT_TRUE verifies that a Boolean condition is true.
11803 // EXPECT_FALSE verifies that a Boolean condition is false.
11804 //
11805 // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
11806 // that they will also abort the current function on failure. People
11807 // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
11808 // writing data-driven tests often find themselves using ADD_FAILURE
11809 // and EXPECT_* more.
11810
11811 // Generates a nonfatal failure with a generic message.
11812 #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
11813
11814 // Generates a nonfatal failure at the given source file location with
11815 // a generic message.
11816 #define ADD_FAILURE_AT(file, line) \
11817 GTEST_MESSAGE_AT_(file, line, "Failed", \
11818 ::testing::TestPartResult::kNonFatalFailure)
11819
11820 // Generates a fatal failure with a generic message.
11821 #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
11822
11823 // Like GTEST_FAIL(), but at the given source file location.
11824 #define GTEST_FAIL_AT(file, line) \
11825 GTEST_MESSAGE_AT_(file, line, "Failed", \
11826 ::testing::TestPartResult::kFatalFailure)
11827
11828 // Define this macro to 1 to omit the definition of FAIL(), which is a
11829 // generic name and clashes with some other libraries.
11830 #if !GTEST_DONT_DEFINE_FAIL
11831 # define FAIL() GTEST_FAIL()
11832 #endif
11833
11834 // Generates a success with a generic message.
11835 #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
11836
11837 // Define this macro to 1 to omit the definition of SUCCEED(), which
11838 // is a generic name and clashes with some other libraries.
11839 #if !GTEST_DONT_DEFINE_SUCCEED
11840 # define SUCCEED() GTEST_SUCCEED()
11841 #endif
11842
11843 // Macros for testing exceptions.
11844 //
11845 // * {ASSERT|EXPECT}_THROW(statement, expected_exception):
11846 // Tests that the statement throws the expected exception.
11847 // * {ASSERT|EXPECT}_NO_THROW(statement):
11848 // Tests that the statement doesn't throw any exception.
11849 // * {ASSERT|EXPECT}_ANY_THROW(statement):
11850 // Tests that the statement throws an exception.
11851
11852 #define EXPECT_THROW(statement, expected_exception) \
11853 GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
11854 #define EXPECT_NO_THROW(statement) \
11855 GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
11856 #define EXPECT_ANY_THROW(statement) \
11857 GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
11858 #define ASSERT_THROW(statement, expected_exception) \
11859 GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
11860 #define ASSERT_NO_THROW(statement) \
11861 GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
11862 #define ASSERT_ANY_THROW(statement) \
11863 GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
11864
11865 // Boolean assertions. Condition can be either a Boolean expression or an
11866 // AssertionResult. For more information on how to use AssertionResult with
11867 // these macros see comments on that class.
11868 #define GTEST_EXPECT_TRUE(condition) \
11869 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
11870 GTEST_NONFATAL_FAILURE_)
11871 #define GTEST_EXPECT_FALSE(condition) \
11872 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
11873 GTEST_NONFATAL_FAILURE_)
11874 #define GTEST_ASSERT_TRUE(condition) \
11875 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
11876 GTEST_FATAL_FAILURE_)
11877 #define GTEST_ASSERT_FALSE(condition) \
11878 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
11879 GTEST_FATAL_FAILURE_)
11880
11881 // Define these macros to 1 to omit the definition of the corresponding
11882 // EXPECT or ASSERT, which clashes with some users' own code.
11883
11884 #if !GTEST_DONT_DEFINE_EXPECT_TRUE
11885 #define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
11886 #endif
11887
11888 #if !GTEST_DONT_DEFINE_EXPECT_FALSE
11889 #define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
11890 #endif
11891
11892 #if !GTEST_DONT_DEFINE_ASSERT_TRUE
11893 #define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
11894 #endif
11895
11896 #if !GTEST_DONT_DEFINE_ASSERT_FALSE
11897 #define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
11898 #endif
11899
11900 // Macros for testing equalities and inequalities.
11901 //
11902 // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
11903 // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
11904 // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
11905 // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
11906 // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
11907 // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
11908 //
11909 // When they are not, Google Test prints both the tested expressions and
11910 // their actual values. The values must be compatible built-in types,
11911 // or you will get a compiler error. By "compatible" we mean that the
11912 // values can be compared by the respective operator.
11913 //
11914 // Note:
11915 //
11916 // 1. It is possible to make a user-defined type work with
11917 // {ASSERT|EXPECT}_??(), but that requires overloading the
11918 // comparison operators and is thus discouraged by the Google C++
11919 // Usage Guide. Therefore, you are advised to use the
11920 // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
11921 // equal.
11922 //
11923 // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
11924 // pointers (in particular, C strings). Therefore, if you use it
11925 // with two C strings, you are testing how their locations in memory
11926 // are related, not how their content is related. To compare two C
11927 // strings by content, use {ASSERT|EXPECT}_STR*().
11928 //
11929 // 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
11930 // {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
11931 // what the actual value is when it fails, and similarly for the
11932 // other comparisons.
11933 //
11934 // 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
11935 // evaluate their arguments, which is undefined.
11936 //
11937 // 5. These macros evaluate their arguments exactly once.
11938 //
11939 // Examples:
11940 //
11941 // EXPECT_NE(Foo(), 5);
11942 // EXPECT_EQ(a_pointer, NULL);
11943 // ASSERT_LT(i, array_size);
11944 // ASSERT_GT(records.size(), 0) << "There is no record left.";
11945
11946 #define EXPECT_EQ(val1, val2) \
11947 EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
11948 #define EXPECT_NE(val1, val2) \
11949 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
11950 #define EXPECT_LE(val1, val2) \
11951 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
11952 #define EXPECT_LT(val1, val2) \
11953 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
11954 #define EXPECT_GE(val1, val2) \
11955 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
11956 #define EXPECT_GT(val1, val2) \
11957 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
11958
11959 #define GTEST_ASSERT_EQ(val1, val2) \
11960 ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
11961 #define GTEST_ASSERT_NE(val1, val2) \
11962 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
11963 #define GTEST_ASSERT_LE(val1, val2) \
11964 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
11965 #define GTEST_ASSERT_LT(val1, val2) \
11966 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
11967 #define GTEST_ASSERT_GE(val1, val2) \
11968 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
11969 #define GTEST_ASSERT_GT(val1, val2) \
11970 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
11971
11972 // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
11973 // ASSERT_XY(), which clashes with some users' own code.
11974
11975 #if !GTEST_DONT_DEFINE_ASSERT_EQ
11976 # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
11977 #endif
11978
11979 #if !GTEST_DONT_DEFINE_ASSERT_NE
11980 # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
11981 #endif
11982
11983 #if !GTEST_DONT_DEFINE_ASSERT_LE
11984 # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
11985 #endif
11986
11987 #if !GTEST_DONT_DEFINE_ASSERT_LT
11988 # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
11989 #endif
11990
11991 #if !GTEST_DONT_DEFINE_ASSERT_GE
11992 # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
11993 #endif
11994
11995 #if !GTEST_DONT_DEFINE_ASSERT_GT
11996 # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
11997 #endif
11998
11999 // C-string Comparisons. All tests treat NULL and any non-NULL string
12000 // as different. Two NULLs are equal.
12001 //
12002 // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
12003 // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
12004 // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
12005 // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
12006 //
12007 // For wide or narrow string objects, you can use the
12008 // {ASSERT|EXPECT}_??() macros.
12009 //
12010 // Don't depend on the order in which the arguments are evaluated,
12011 // which is undefined.
12012 //
12013 // These macros evaluate their arguments exactly once.
12014
12015 #define EXPECT_STREQ(s1, s2) \
12016 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
12017 #define EXPECT_STRNE(s1, s2) \
12018 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
12019 #define EXPECT_STRCASEEQ(s1, s2) \
12020 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
12021 #define EXPECT_STRCASENE(s1, s2)\
12022 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
12023
12024 #define ASSERT_STREQ(s1, s2) \
12025 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
12026 #define ASSERT_STRNE(s1, s2) \
12027 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
12028 #define ASSERT_STRCASEEQ(s1, s2) \
12029 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
12030 #define ASSERT_STRCASENE(s1, s2)\
12031 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
12032
12033 // Macros for comparing floating-point numbers.
12034 //
12035 // * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
12036 // Tests that two float values are almost equal.
12037 // * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
12038 // Tests that two double values are almost equal.
12039 // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
12040 // Tests that v1 and v2 are within the given distance to each other.
12041 //
12042 // Google Test uses ULP-based comparison to automatically pick a default
12043 // error bound that is appropriate for the operands. See the
12044 // FloatingPoint template class in gtest-internal.h if you are
12045 // interested in the implementation details.
12046
12047 #define EXPECT_FLOAT_EQ(val1, val2)\
12048 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
12049 val1, val2)
12050
12051 #define EXPECT_DOUBLE_EQ(val1, val2)\
12052 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
12053 val1, val2)
12054
12055 #define ASSERT_FLOAT_EQ(val1, val2)\
12056 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
12057 val1, val2)
12058
12059 #define ASSERT_DOUBLE_EQ(val1, val2)\
12060 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
12061 val1, val2)
12062
12063 #define EXPECT_NEAR(val1, val2, abs_error)\
12064 EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
12065 val1, val2, abs_error)
12066
12067 #define ASSERT_NEAR(val1, val2, abs_error)\
12068 ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
12069 val1, val2, abs_error)
12070
12071 // These predicate format functions work on floating-point values, and
12072 // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
12073 //
12074 // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
12075
12076 // Asserts that val1 is less than, or almost equal to, val2. Fails
12077 // otherwise. In particular, it fails if either val1 or val2 is NaN.
12078 GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
12079 float val1, float val2);
12080 GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
12081 double val1, double val2);
12082
12083
12084 #if GTEST_OS_WINDOWS
12085
12086 // Macros that test for HRESULT failure and success, these are only useful
12087 // on Windows, and rely on Windows SDK macros and APIs to compile.
12088 //
12089 // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
12090 //
12091 // When expr unexpectedly fails or succeeds, Google Test prints the
12092 // expected result and the actual result with both a human-readable
12093 // string representation of the error, if available, as well as the
12094 // hex result code.
12095 # define EXPECT_HRESULT_SUCCEEDED(expr) \
12096 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
12097
12098 # define ASSERT_HRESULT_SUCCEEDED(expr) \
12099 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
12100
12101 # define EXPECT_HRESULT_FAILED(expr) \
12102 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
12103
12104 # define ASSERT_HRESULT_FAILED(expr) \
12105 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
12106
12107 #endif // GTEST_OS_WINDOWS
12108
12109 // Macros that execute statement and check that it doesn't generate new fatal
12110 // failures in the current thread.
12111 //
12112 // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
12113 //
12114 // Examples:
12115 //
12116 // EXPECT_NO_FATAL_FAILURE(Process());
12117 // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
12118 //
12119 #define ASSERT_NO_FATAL_FAILURE(statement) \
12120 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
12121 #define EXPECT_NO_FATAL_FAILURE(statement) \
12122 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
12123
12124 // Causes a trace (including the given source file path and line number,
12125 // and the given message) to be included in every test failure message generated
12126 // by code in the scope of the lifetime of an instance of this class. The effect
12127 // is undone with the destruction of the instance.
12128 //
12129 // The message argument can be anything streamable to std::ostream.
12130 //
12131 // Example:
12132 // testing::ScopedTrace trace("file.cc", 123, "message");
12133 //
12134 class GTEST_API_ ScopedTrace {
12135 public:
12136 // The c'tor pushes the given source file location and message onto
12137 // a trace stack maintained by Google Test.
12138
12139 // Template version. Uses Message() to convert the values into strings.
12140 // Slow, but flexible.
12141 template <typename T>
12142 ScopedTrace(const char* file, int line, const T& message) {
12143 PushTrace(file, line, (Message() << message).GetString());
12144 }
12145
12146 // Optimize for some known types.
12147 ScopedTrace(const char* file, int line, const char* message) {
12148 PushTrace(file, line, message ? message : "(null)");
12149 }
12150
12151 ScopedTrace(const char* file, int line, const std::string& message) {
12152 PushTrace(file, line, message);
12153 }
12154
12155 // The d'tor pops the info pushed by the c'tor.
12156 //
12157 // Note that the d'tor is not virtual in order to be efficient.
12158 // Don't inherit from ScopedTrace!
12159 ~ScopedTrace();
12160
12161 private:
12162 void PushTrace(const char* file, int line, std::string message);
12163
12164 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
12165 } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
12166 // c'tor and d'tor. Therefore it doesn't
12167 // need to be used otherwise.
12168
12169 // Causes a trace (including the source file path, the current line
12170 // number, and the given message) to be included in every test failure
12171 // message generated by code in the current scope. The effect is
12172 // undone when the control leaves the current scope.
12173 //
12174 // The message argument can be anything streamable to std::ostream.
12175 //
12176 // In the implementation, we include the current line number as part
12177 // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
12178 // to appear in the same block - as long as they are on different
12179 // lines.
12180 //
12181 // Assuming that each thread maintains its own stack of traces.
12182 // Therefore, a SCOPED_TRACE() would (correctly) only affect the
12183 // assertions in its own thread.
12184 #define SCOPED_TRACE(message) \
12185 ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
12186 __FILE__, __LINE__, (message))
12187
12188 // Compile-time assertion for type equality.
12189 // StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
12190 // are the same type. The value it returns is not interesting.
12191 //
12192 // Instead of making StaticAssertTypeEq a class template, we make it a
12193 // function template that invokes a helper class template. This
12194 // prevents a user from misusing StaticAssertTypeEq<T1, T2> by
12195 // defining objects of that type.
12196 //
12197 // CAVEAT:
12198 //
12199 // When used inside a method of a class template,
12200 // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
12201 // instantiated. For example, given:
12202 //
12203 // template <typename T> class Foo {
12204 // public:
12205 // void Bar() { testing::StaticAssertTypeEq<int, T>(); }
12206 // };
12207 //
12208 // the code:
12209 //
12210 // void Test1() { Foo<bool> foo; }
12211 //
12212 // will NOT generate a compiler error, as Foo<bool>::Bar() is never
12213 // actually instantiated. Instead, you need:
12214 //
12215 // void Test2() { Foo<bool> foo; foo.Bar(); }
12216 //
12217 // to cause a compiler error.
12218 template <typename T1, typename T2>
12219 constexpr bool StaticAssertTypeEq() noexcept {
12220 static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type");
12221 return true;
12222 }
12223
12224 // Defines a test.
12225 //
12226 // The first parameter is the name of the test suite, and the second
12227 // parameter is the name of the test within the test suite.
12228 //
12229 // The convention is to end the test suite name with "Test". For
12230 // example, a test suite for the Foo class can be named FooTest.
12231 //
12232 // Test code should appear between braces after an invocation of
12233 // this macro. Example:
12234 //
12235 // TEST(FooTest, InitializesCorrectly) {
12236 // Foo foo;
12237 // EXPECT_TRUE(foo.StatusIsOK());
12238 // }
12239
12240 // Note that we call GetTestTypeId() instead of GetTypeId<
12241 // ::testing::Test>() here to get the type ID of testing::Test. This
12242 // is to work around a suspected linker bug when using Google Test as
12243 // a framework on Mac OS X. The bug causes GetTypeId<
12244 // ::testing::Test>() to return different values depending on whether
12245 // the call is from the Google Test framework itself or from user test
12246 // code. GetTestTypeId() is guaranteed to always return the same
12247 // value, as it always calls GetTypeId<>() from the Google Test
12248 // framework.
12249 #define GTEST_TEST(test_suite_name, test_name) \
12250 GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \
12251 ::testing::internal::GetTestTypeId())
12252
12253 // Define this macro to 1 to omit the definition of TEST(), which
12254 // is a generic name and clashes with some other libraries.
12255 #if !GTEST_DONT_DEFINE_TEST
12256 #define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
12257 #endif
12258
12259 // Defines a test that uses a test fixture.
12260 //
12261 // The first parameter is the name of the test fixture class, which
12262 // also doubles as the test suite name. The second parameter is the
12263 // name of the test within the test suite.
12264 //
12265 // A test fixture class must be declared earlier. The user should put
12266 // the test code between braces after using this macro. Example:
12267 //
12268 // class FooTest : public testing::Test {
12269 // protected:
12270 // void SetUp() override { b_.AddElement(3); }
12271 //
12272 // Foo a_;
12273 // Foo b_;
12274 // };
12275 //
12276 // TEST_F(FooTest, InitializesCorrectly) {
12277 // EXPECT_TRUE(a_.StatusIsOK());
12278 // }
12279 //
12280 // TEST_F(FooTest, ReturnsElementCountCorrectly) {
12281 // EXPECT_EQ(a_.size(), 0);
12282 // EXPECT_EQ(b_.size(), 1);
12283 // }
12284 //
12285 // GOOGLETEST_CM0011 DO NOT DELETE
12286 #if !GTEST_DONT_DEFINE_TEST
12287 #define TEST_F(test_fixture, test_name)\
12288 GTEST_TEST_(test_fixture, test_name, test_fixture, \
12289 ::testing::internal::GetTypeId<test_fixture>())
12290 #endif // !GTEST_DONT_DEFINE_TEST
12291
12292 // Returns a path to temporary directory.
12293 // Tries to determine an appropriate directory for the platform.
12294 GTEST_API_ std::string TempDir();
12295
12296 #ifdef _MSC_VER
12297 # pragma warning(pop)
12298 #endif
12299
12300 // Dynamically registers a test with the framework.
12301 //
12302 // This is an advanced API only to be used when the `TEST` macros are
12303 // insufficient. The macros should be preferred when possible, as they avoid
12304 // most of the complexity of calling this function.
12305 //
12306 // The `factory` argument is a factory callable (move-constructible) object or
12307 // function pointer that creates a new instance of the Test object. It
12308 // handles ownership to the caller. The signature of the callable is
12309 // `Fixture*()`, where `Fixture` is the test fixture class for the test. All
12310 // tests registered with the same `test_suite_name` must return the same
12311 // fixture type. This is checked at runtime.
12312 //
12313 // The framework will infer the fixture class from the factory and will call
12314 // the `SetUpTestSuite` and `TearDownTestSuite` for it.
12315 //
12316 // Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
12317 // undefined.
12318 //
12319 // Use case example:
12320 //
12321 // class MyFixture : public ::testing::Test {
12322 // public:
12323 // // All of these optional, just like in regular macro usage.
12324 // static void SetUpTestSuite() { ... }
12325 // static void TearDownTestSuite() { ... }
12326 // void SetUp() override { ... }
12327 // void TearDown() override { ... }
12328 // };
12329 //
12330 // class MyTest : public MyFixture {
12331 // public:
12332 // explicit MyTest(int data) : data_(data) {}
12333 // void TestBody() override { ... }
12334 //
12335 // private:
12336 // int data_;
12337 // };
12338 //
12339 // void RegisterMyTests(const std::vector<int>& values) {
12340 // for (int v : values) {
12341 // ::testing::RegisterTest(
12342 // "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
12343 // std::to_string(v).c_str(),
12344 // __FILE__, __LINE__,
12345 // // Important to use the fixture type as the return type here.
12346 // [=]() -> MyFixture* { return new MyTest(v); });
12347 // }
12348 // }
12349 // ...
12350 // int main(int argc, char** argv) {
12351 // std::vector<int> values_to_test = LoadValuesFromConfig();
12352 // RegisterMyTests(values_to_test);
12353 // ...
12354 // return RUN_ALL_TESTS();
12355 // }
12356 //
12357 template <int&... ExplicitParameterBarrier, typename Factory>
12358 TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
12359 const char* type_param, const char* value_param,
12360 const char* file, int line, Factory factory) {
12361 using TestT = typename std::remove_pointer<decltype(factory())>::type;
12362
12363 class FactoryImpl : public internal::TestFactoryBase {
12364 public:
12365 explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}
12366 Test* CreateTest() override { return factory_(); }
12367
12368 private:
12369 Factory factory_;
12370 };
12371
12372 return internal::MakeAndRegisterTestInfo(
12373 test_suite_name, test_name, type_param, value_param,
12374 internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),
12375 internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),
12376 internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),
12377 new FactoryImpl{std::move(factory)});
12378 }
12379
12380 } // namespace testing
12381
12382 // Use this function in main() to run all tests. It returns 0 if all
12383 // tests are successful, or 1 otherwise.
12384 //
12385 // RUN_ALL_TESTS() should be invoked after the command line has been
12386 // parsed by InitGoogleTest().
12387 //
12388 // This function was formerly a macro; thus, it is in the global
12389 // namespace and has an all-caps name.
12390 int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
12391
12392 inline int RUN_ALL_TESTS() {
12393 return ::testing::UnitTest::GetInstance()->Run();
12394 }
12395
12396 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
12397
12398 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_