STIR  6.3.0
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), buffer_() {}
6394 
6395  // Constructs a matcher from its implementation.
6396  template <typename U>
6397  explicit MatcherBase(const MatcherInterface<U>* impl)
6398  : vtable_(nullptr), buffer_() {
6399  Init(impl);
6400  }
6401 
6402  template <typename M, typename = typename std::remove_reference<
6403  M>::type::is_gtest_matcher>
6404  MatcherBase(M&& m) : vtable_(nullptr), buffer_() { // NOLINT
6405  Init(std::forward<M>(m));
6406  }
6407 
6408  MatcherBase(const MatcherBase& other)
6409  : vtable_(other.vtable_), buffer_(other.buffer_) {
6410  if (IsShared()) buffer_.shared->Ref();
6411  }
6412 
6413  MatcherBase& operator=(const MatcherBase& other) {
6414  if (this == &other) return *this;
6415  Destroy();
6416  vtable_ = other.vtable_;
6417  buffer_ = other.buffer_;
6418  if (IsShared()) buffer_.shared->Ref();
6419  return *this;
6420  }
6421 
6422  MatcherBase(MatcherBase&& other)
6423  : vtable_(other.vtable_), buffer_(other.buffer_) {
6424  other.vtable_ = nullptr;
6425  }
6426 
6427  MatcherBase& operator=(MatcherBase&& other) {
6428  if (this == &other) return *this;
6429  Destroy();
6430  vtable_ = other.vtable_;
6431  buffer_ = other.buffer_;
6432  other.vtable_ = nullptr;
6433  return *this;
6434  }
6435 
6436  ~MatcherBase() override { Destroy(); }
6437 
6438  private:
6439  struct VTable {
6440  bool (*match_and_explain)(const MatcherBase&, const T&,
6441  MatchResultListener*);
6442  void (*describe)(const MatcherBase&, std::ostream*, bool negation);
6443  // Returns the captured object if it implements the interface, otherwise
6444  // returns the MatcherBase itself.
6445  const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
6446  // Called on shared instances when the reference count reaches 0.
6447  void (*shared_destroy)(SharedPayloadBase*);
6448  };
6449 
6450  bool IsShared() const {
6451  return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
6452  }
6453 
6454  // If the implementation uses a listener, call that.
6455  template <typename P>
6456  static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
6457  MatchResultListener* listener)
6458  -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
6459  return P::Get(m).MatchAndExplain(value, listener->stream());
6460  }
6461 
6462  template <typename P>
6463  static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
6464  MatchResultListener* listener)
6465  -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
6466  return P::Get(m).MatchAndExplain(value, listener);
6467  }
6468 
6469  template <typename P>
6470  static void DescribeImpl(const MatcherBase& m, std::ostream* os,
6471  bool negation) {
6472  if (negation) {
6473  P::Get(m).DescribeNegationTo(os);
6474  } else {
6475  P::Get(m).DescribeTo(os);
6476  }
6477  }
6478 
6479  template <typename P>
6480  static const MatcherDescriberInterface* GetDescriberImpl(
6481  const MatcherBase& m) {
6482  // If the impl is a MatcherDescriberInterface, then return it.
6483  // Otherwise use MatcherBase itself.
6484  // This allows us to implement the GetDescriber() function without support
6485  // from the impl, but some users really want to get their impl back when
6486  // they call GetDescriber().
6487  // We use std::get on a tuple as a workaround of not having `if constexpr`.
6488  return std::get<(
6489  std::is_convertible<decltype(&P::Get(m)),
6490  const MatcherDescriberInterface*>::value
6491  ? 1
6492  : 0)>(std::make_tuple(&m, &P::Get(m)));
6493  }
6494 
6495  template <typename P>
6496  const VTable* GetVTable() {
6497  static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
6498  &DescribeImpl<P>, &GetDescriberImpl<P>,
6499  P::shared_destroy};
6500  return &kVTable;
6501  }
6502 
6503  union Buffer {
6504  // Add some types to give Buffer some common alignment/size use cases.
6505  void* ptr;
6506  double d;
6507  int64_t i;
6508  // And add one for the out-of-line cases.
6509  SharedPayloadBase* shared;
6510  };
6511 
6512  void Destroy() {
6513  if (IsShared() && buffer_.shared->Unref()) {
6514  vtable_->shared_destroy(buffer_.shared);
6515  }
6516  }
6517 
6518  template <typename M>
6519  static constexpr bool IsInlined() {
6520  return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
6521  is_trivially_copy_constructible<M>::value &&
6522  std::is_trivially_destructible<M>::value;
6523  }
6524 
6525  template <typename M, bool = MatcherBase::IsInlined<M>()>
6526  struct ValuePolicy {
6527  static const M& Get(const MatcherBase& m) {
6528  // When inlined along with Init, need to be explicit to avoid violating
6529  // strict aliasing rules.
6530  const M *ptr = static_cast<const M*>(
6531  static_cast<const void*>(&m.buffer_));
6532  return *ptr;
6533  }
6534  static void Init(MatcherBase& m, M impl) {
6535  ::new (static_cast<void*>(&m.buffer_)) M(impl);
6536  }
6537  static constexpr auto shared_destroy = nullptr;
6538  };
6539 
6540  template <typename M>
6541  struct ValuePolicy<M, false> {
6542  using Shared = SharedPayload<M>;
6543  static const M& Get(const MatcherBase& m) {
6544  return static_cast<Shared*>(m.buffer_.shared)->value;
6545  }
6546  template <typename Arg>
6547  static void Init(MatcherBase& m, Arg&& arg) {
6548  m.buffer_.shared = new Shared(std::forward<Arg>(arg));
6549  }
6550  static constexpr auto shared_destroy = &Shared::Destroy;
6551  };
6552 
6553  template <typename U, bool B>
6554  struct ValuePolicy<const MatcherInterface<U>*, B> {
6555  using M = const MatcherInterface<U>;
6556  using Shared = SharedPayload<std::unique_ptr<M>>;
6557  static const M& Get(const MatcherBase& m) {
6558  return *static_cast<Shared*>(m.buffer_.shared)->value;
6559  }
6560  static void Init(MatcherBase& m, M* impl) {
6561  m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
6562  }
6563 
6564  static constexpr auto shared_destroy = &Shared::Destroy;
6565  };
6566 
6567  template <typename M>
6568  void Init(M&& m) {
6569  using MM = typename std::decay<M>::type;
6570  using Policy = ValuePolicy<MM>;
6571  vtable_ = GetVTable<Policy>();
6572  Policy::Init(*this, std::forward<M>(m));
6573  }
6574 
6575  const VTable* vtable_;
6576  Buffer buffer_;
6577 };
6578 
6579 } // namespace internal
6580 
6581 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
6582 // object that can check whether a value of type T matches. The
6583 // implementation of Matcher<T> is just a std::shared_ptr to const
6584 // MatcherInterface<T>. Don't inherit from Matcher!
6585 template <typename T>
6586 class Matcher : public internal::MatcherBase<T> {
6587  public:
6588  // Constructs a null matcher. Needed for storing Matcher objects in STL
6589  // containers. A default-constructed matcher is not yet initialized. You
6590  // cannot use it until a valid value has been assigned to it.
6591  explicit Matcher() {} // NOLINT
6592 
6593  // Constructs a matcher from its implementation.
6594  explicit Matcher(const MatcherInterface<const T&>* impl)
6595  : internal::MatcherBase<T>(impl) {}
6596 
6597  template <typename U>
6598  explicit Matcher(
6599  const MatcherInterface<U>* impl,
6600  typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
6601  nullptr)
6602  : internal::MatcherBase<T>(impl) {}
6603 
6604  template <typename M, typename = typename std::remove_reference<
6605  M>::type::is_gtest_matcher>
6606  Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
6607 
6608  // Implicit constructor here allows people to write
6609  // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
6610  Matcher(T value); // NOLINT
6611 };
6612 
6613 // The following two specializations allow the user to write str
6614 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
6615 // matcher is expected.
6616 template <>
6617 class GTEST_API_ Matcher<const std::string&>
6618  : public internal::MatcherBase<const std::string&> {
6619  public:
6620  Matcher() {}
6621 
6622  explicit Matcher(const MatcherInterface<const std::string&>* impl)
6623  : internal::MatcherBase<const std::string&>(impl) {}
6624 
6625  template <typename M, typename = typename std::remove_reference<
6626  M>::type::is_gtest_matcher>
6627  Matcher(M&& m) // NOLINT
6628  : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
6629 
6630  // Allows the user to write str instead of Eq(str) sometimes, where
6631  // str is a std::string object.
6632  Matcher(const std::string& s); // NOLINT
6633 
6634  // Allows the user to write "foo" instead of Eq("foo") sometimes.
6635  Matcher(const char* s); // NOLINT
6636 };
6637 
6638 template <>
6639 class GTEST_API_ Matcher<std::string>
6640  : public internal::MatcherBase<std::string> {
6641  public:
6642  Matcher() {}
6643 
6644  explicit Matcher(const MatcherInterface<const std::string&>* impl)
6645  : internal::MatcherBase<std::string>(impl) {}
6646  explicit Matcher(const MatcherInterface<std::string>* impl)
6647  : internal::MatcherBase<std::string>(impl) {}
6648 
6649  template <typename M, typename = typename std::remove_reference<
6650  M>::type::is_gtest_matcher>
6651  Matcher(M&& m) // NOLINT
6652  : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
6653 
6654  // Allows the user to write str instead of Eq(str) sometimes, where
6655  // str is a string object.
6656  Matcher(const std::string& s); // NOLINT
6657 
6658  // Allows the user to write "foo" instead of Eq("foo") sometimes.
6659  Matcher(const char* s); // NOLINT
6660 };
6661 
6662 #if GTEST_INTERNAL_HAS_STRING_VIEW
6663 // The following two specializations allow the user to write str
6664 // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
6665 // matcher is expected.
6666 template <>
6667 class GTEST_API_ Matcher<const internal::StringView&>
6668  : public internal::MatcherBase<const internal::StringView&> {
6669  public:
6670  Matcher() {}
6671 
6672  explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
6673  : internal::MatcherBase<const internal::StringView&>(impl) {}
6674 
6675  template <typename M, typename = typename std::remove_reference<
6676  M>::type::is_gtest_matcher>
6677  Matcher(M&& m) // NOLINT
6678  : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
6679  }
6680 
6681  // Allows the user to write str instead of Eq(str) sometimes, where
6682  // str is a std::string object.
6683  Matcher(const std::string& s); // NOLINT
6684 
6685  // Allows the user to write "foo" instead of Eq("foo") sometimes.
6686  Matcher(const char* s); // NOLINT
6687 
6688  // Allows the user to pass absl::string_views or std::string_views directly.
6689  Matcher(internal::StringView s); // NOLINT
6690 };
6691 
6692 template <>
6693 class GTEST_API_ Matcher<internal::StringView>
6694  : public internal::MatcherBase<internal::StringView> {
6695  public:
6696  Matcher() {}
6697 
6698  explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
6699  : internal::MatcherBase<internal::StringView>(impl) {}
6700  explicit Matcher(const MatcherInterface<internal::StringView>* impl)
6701  : internal::MatcherBase<internal::StringView>(impl) {}
6702 
6703  template <typename M, typename = typename std::remove_reference<
6704  M>::type::is_gtest_matcher>
6705  Matcher(M&& m) // NOLINT
6706  : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
6707 
6708  // Allows the user to write str instead of Eq(str) sometimes, where
6709  // str is a std::string object.
6710  Matcher(const std::string& s); // NOLINT
6711 
6712  // Allows the user to write "foo" instead of Eq("foo") sometimes.
6713  Matcher(const char* s); // NOLINT
6714 
6715  // Allows the user to pass absl::string_views or std::string_views directly.
6716  Matcher(internal::StringView s); // NOLINT
6717 };
6718 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
6719 
6720 // Prints a matcher in a human-readable format.
6721 template <typename T>
6722 std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
6723  matcher.DescribeTo(&os);
6724  return os;
6725 }
6726 
6727 // The PolymorphicMatcher class template makes it easy to implement a
6728 // polymorphic matcher (i.e. a matcher that can match values of more
6729 // than one type, e.g. Eq(n) and NotNull()).
6730 //
6731 // To define a polymorphic matcher, a user should provide an Impl
6732 // class that has a DescribeTo() method and a DescribeNegationTo()
6733 // method, and define a member function (or member function template)
6734 //
6735 // bool MatchAndExplain(const Value& value,
6736 // MatchResultListener* listener) const;
6737 //
6738 // See the definition of NotNull() for a complete example.
6739 template <class Impl>
6740 class PolymorphicMatcher {
6741  public:
6742  explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
6743 
6744  // Returns a mutable reference to the underlying matcher
6745  // implementation object.
6746  Impl& mutable_impl() { return impl_; }
6747 
6748  // Returns an immutable reference to the underlying matcher
6749  // implementation object.
6750  const Impl& impl() const { return impl_; }
6751 
6752  template <typename T>
6753  operator Matcher<T>() const {
6754  return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
6755  }
6756 
6757  private:
6758  template <typename T>
6759  class MonomorphicImpl : public MatcherInterface<T> {
6760  public:
6761  explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
6762 
6763  void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
6764 
6765  void DescribeNegationTo(::std::ostream* os) const override {
6766  impl_.DescribeNegationTo(os);
6767  }
6768 
6769  bool MatchAndExplain(T x, MatchResultListener* listener) const override {
6770  return impl_.MatchAndExplain(x, listener);
6771  }
6772 
6773  private:
6774  const Impl impl_;
6775  };
6776 
6777  Impl impl_;
6778 };
6779 
6780 // Creates a matcher from its implementation.
6781 // DEPRECATED: Especially in the generic code, prefer:
6782 // Matcher<T>(new MyMatcherImpl<const T&>(...));
6783 //
6784 // MakeMatcher may create a Matcher that accepts its argument by value, which
6785 // leads to unnecessary copies & lack of support for non-copyable types.
6786 template <typename T>
6787 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
6788  return Matcher<T>(impl);
6789 }
6790 
6791 // Creates a polymorphic matcher from its implementation. This is
6792 // easier to use than the PolymorphicMatcher<Impl> constructor as it
6793 // doesn't require you to explicitly write the template argument, e.g.
6794 //
6795 // MakePolymorphicMatcher(foo);
6796 // vs
6797 // PolymorphicMatcher<TypeOfFoo>(foo);
6798 template <class Impl>
6799 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
6800  return PolymorphicMatcher<Impl>(impl);
6801 }
6802 
6803 namespace internal {
6804 // Implements a matcher that compares a given value with a
6805 // pre-supplied value using one of the ==, <=, <, etc, operators. The
6806 // two values being compared don't have to have the same type.
6807 //
6808 // The matcher defined here is polymorphic (for example, Eq(5) can be
6809 // used to match an int, a short, a double, etc). Therefore we use
6810 // a template type conversion operator in the implementation.
6811 //
6812 // The following template definition assumes that the Rhs parameter is
6813 // a "bare" type (i.e. neither 'const T' nor 'T&').
6814 template <typename D, typename Rhs, typename Op>
6815 class ComparisonBase {
6816  public:
6817  explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
6818 
6819  using is_gtest_matcher = void;
6820 
6821  template <typename Lhs>
6822  bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
6823  return Op()(lhs, Unwrap(rhs_));
6824  }
6825  void DescribeTo(std::ostream* os) const {
6826  *os << D::Desc() << " ";
6827  UniversalPrint(Unwrap(rhs_), os);
6828  }
6829  void DescribeNegationTo(std::ostream* os) const {
6830  *os << D::NegatedDesc() << " ";
6831  UniversalPrint(Unwrap(rhs_), os);
6832  }
6833 
6834  private:
6835  template <typename T>
6836  static const T& Unwrap(const T& v) {
6837  return v;
6838  }
6839  template <typename T>
6840  static const T& Unwrap(std::reference_wrapper<T> v) {
6841  return v;
6842  }
6843 
6844  Rhs rhs_;
6845 };
6846 
6847 template <typename Rhs>
6848 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
6849  public:
6850  explicit EqMatcher(const Rhs& rhs)
6851  : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
6852  static const char* Desc() { return "is equal to"; }
6853  static const char* NegatedDesc() { return "isn't equal to"; }
6854 };
6855 template <typename Rhs>
6856 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
6857  public:
6858  explicit NeMatcher(const Rhs& rhs)
6859  : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
6860  static const char* Desc() { return "isn't equal to"; }
6861  static const char* NegatedDesc() { return "is equal to"; }
6862 };
6863 template <typename Rhs>
6864 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
6865  public:
6866  explicit LtMatcher(const Rhs& rhs)
6867  : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
6868  static const char* Desc() { return "is <"; }
6869  static const char* NegatedDesc() { return "isn't <"; }
6870 };
6871 template <typename Rhs>
6872 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
6873  public:
6874  explicit GtMatcher(const Rhs& rhs)
6875  : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
6876  static const char* Desc() { return "is >"; }
6877  static const char* NegatedDesc() { return "isn't >"; }
6878 };
6879 template <typename Rhs>
6880 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
6881  public:
6882  explicit LeMatcher(const Rhs& rhs)
6883  : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
6884  static const char* Desc() { return "is <="; }
6885  static const char* NegatedDesc() { return "isn't <="; }
6886 };
6887 template <typename Rhs>
6888 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
6889  public:
6890  explicit GeMatcher(const Rhs& rhs)
6891  : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
6892  static const char* Desc() { return "is >="; }
6893  static const char* NegatedDesc() { return "isn't >="; }
6894 };
6895 
6896 template <typename T, typename = typename std::enable_if<
6897  std::is_constructible<std::string, T>::value>::type>
6898 using StringLike = T;
6899 
6900 // Implements polymorphic matchers MatchesRegex(regex) and
6901 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
6902 // T can be converted to a string.
6903 class MatchesRegexMatcher {
6904  public:
6905  MatchesRegexMatcher(const RE* regex, bool full_match)
6906  : regex_(regex), full_match_(full_match) {}
6907 
6908 #if GTEST_INTERNAL_HAS_STRING_VIEW
6909  bool MatchAndExplain(const internal::StringView& s,
6910  MatchResultListener* listener) const {
6911  return MatchAndExplain(std::string(s), listener);
6912  }
6913 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
6914 
6915  // Accepts pointer types, particularly:
6916  // const char*
6917  // char*
6918  // const wchar_t*
6919  // wchar_t*
6920  template <typename CharType>
6921  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
6922  return s != nullptr && MatchAndExplain(std::string(s), listener);
6923  }
6924 
6925  // Matches anything that can convert to std::string.
6926  //
6927  // This is a template, not just a plain function with const std::string&,
6928  // because absl::string_view has some interfering non-explicit constructors.
6929  template <class MatcheeStringType>
6930  bool MatchAndExplain(const MatcheeStringType& s,
6931  MatchResultListener* /* listener */) const {
6932  const std::string& s2(s);
6933  return full_match_ ? RE::FullMatch(s2, *regex_)
6934  : RE::PartialMatch(s2, *regex_);
6935  }
6936 
6937  void DescribeTo(::std::ostream* os) const {
6938  *os << (full_match_ ? "matches" : "contains") << " regular expression ";
6939  UniversalPrinter<std::string>::Print(regex_->pattern(), os);
6940  }
6941 
6942  void DescribeNegationTo(::std::ostream* os) const {
6943  *os << "doesn't " << (full_match_ ? "match" : "contain")
6944  << " regular expression ";
6945  UniversalPrinter<std::string>::Print(regex_->pattern(), os);
6946  }
6947 
6948  private:
6949  const std::shared_ptr<const RE> regex_;
6950  const bool full_match_;
6951 };
6952 } // namespace internal
6953 
6954 // Matches a string that fully matches regular expression 'regex'.
6955 // The matcher takes ownership of 'regex'.
6956 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
6957  const internal::RE* regex) {
6958  return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
6959 }
6960 template <typename T = std::string>
6961 PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
6962  const internal::StringLike<T>& regex) {
6963  return MatchesRegex(new internal::RE(std::string(regex)));
6964 }
6965 
6966 // Matches a string that contains regular expression 'regex'.
6967 // The matcher takes ownership of 'regex'.
6968 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
6969  const internal::RE* regex) {
6970  return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
6971 }
6972 template <typename T = std::string>
6973 PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
6974  const internal::StringLike<T>& regex) {
6975  return ContainsRegex(new internal::RE(std::string(regex)));
6976 }
6977 
6978 // Creates a polymorphic matcher that matches anything equal to x.
6979 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
6980 // wouldn't compile.
6981 template <typename T>
6982 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
6983 
6984 // Constructs a Matcher<T> from a 'value' of type T. The constructed
6985 // matcher matches any value that's equal to 'value'.
6986 template <typename T>
6987 Matcher<T>::Matcher(T value) { *this = Eq(value); }
6988 
6989 // Creates a monomorphic matcher that matches anything with type Lhs
6990 // and equal to rhs. A user may need to use this instead of Eq(...)
6991 // in order to resolve an overloading ambiguity.
6992 //
6993 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
6994 // or Matcher<T>(x), but more readable than the latter.
6995 //
6996 // We could define similar monomorphic matchers for other comparison
6997 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
6998 // it yet as those are used much less than Eq() in practice. A user
6999 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
7000 // for example.
7001 template <typename Lhs, typename Rhs>
7002 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
7003 
7004 // Creates a polymorphic matcher that matches anything >= x.
7005 template <typename Rhs>
7006 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
7007  return internal::GeMatcher<Rhs>(x);
7008 }
7009 
7010 // Creates a polymorphic matcher that matches anything > x.
7011 template <typename Rhs>
7012 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
7013  return internal::GtMatcher<Rhs>(x);
7014 }
7015 
7016 // Creates a polymorphic matcher that matches anything <= x.
7017 template <typename Rhs>
7018 inline internal::LeMatcher<Rhs> Le(Rhs x) {
7019  return internal::LeMatcher<Rhs>(x);
7020 }
7021 
7022 // Creates a polymorphic matcher that matches anything < x.
7023 template <typename Rhs>
7024 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
7025  return internal::LtMatcher<Rhs>(x);
7026 }
7027 
7028 // Creates a polymorphic matcher that matches anything != x.
7029 template <typename Rhs>
7030 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
7031  return internal::NeMatcher<Rhs>(x);
7032 }
7033 } // namespace testing
7034 
7035 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
7036 
7037 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
7038 
7039 #include <stdio.h>
7040 #include <memory>
7041 
7042 namespace testing {
7043 namespace internal {
7044 
7045 GTEST_DECLARE_string_(internal_run_death_test);
7046 
7047 // Names of the flags (needed for parsing Google Test flags).
7048 const char kDeathTestStyleFlag[] = "death_test_style";
7049 const char kDeathTestUseFork[] = "death_test_use_fork";
7050 const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
7051 
7052 #if GTEST_HAS_DEATH_TEST
7053 
7054 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
7055 /* class A needs to have dll-interface to be used by clients of class B */)
7056 
7057 // DeathTest is a class that hides much of the complexity of the
7058 // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
7059 // returns a concrete class that depends on the prevailing death test
7060 // style, as defined by the --gtest_death_test_style and/or
7061 // --gtest_internal_run_death_test flags.
7062 
7063 // In describing the results of death tests, these terms are used with
7064 // the corresponding definitions:
7065 //
7066 // exit status: The integer exit information in the format specified
7067 // by wait(2)
7068 // exit code: The integer code passed to exit(3), _exit(2), or
7069 // returned from main()
7070 class GTEST_API_ DeathTest {
7071  public:
7072  // Create returns false if there was an error determining the
7073  // appropriate action to take for the current death test; for example,
7074  // if the gtest_death_test_style flag is set to an invalid value.
7075  // The LastMessage method will return a more detailed message in that
7076  // case. Otherwise, the DeathTest pointer pointed to by the "test"
7077  // argument is set. If the death test should be skipped, the pointer
7078  // is set to NULL; otherwise, it is set to the address of a new concrete
7079  // DeathTest object that controls the execution of the current test.
7080  static bool Create(const char* statement, Matcher<const std::string&> matcher,
7081  const char* file, int line, DeathTest** test);
7082  DeathTest();
7083  virtual ~DeathTest() { }
7084 
7085  // A helper class that aborts a death test when it's deleted.
7086  class ReturnSentinel {
7087  public:
7088  explicit ReturnSentinel(DeathTest* test) : test_(test) { }
7089  ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
7090  private:
7091  DeathTest* const test_;
7092  GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
7093  } GTEST_ATTRIBUTE_UNUSED_;
7094 
7095  // An enumeration of possible roles that may be taken when a death
7096  // test is encountered. EXECUTE means that the death test logic should
7097  // be executed immediately. OVERSEE means that the program should prepare
7098  // the appropriate environment for a child process to execute the death
7099  // test, then wait for it to complete.
7100  enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
7101 
7102  // An enumeration of the three reasons that a test might be aborted.
7103  enum AbortReason {
7104  TEST_ENCOUNTERED_RETURN_STATEMENT,
7105  TEST_THREW_EXCEPTION,
7106  TEST_DID_NOT_DIE
7107  };
7108 
7109  // Assumes one of the above roles.
7110  virtual TestRole AssumeRole() = 0;
7111 
7112  // Waits for the death test to finish and returns its status.
7113  virtual int Wait() = 0;
7114 
7115  // Returns true if the death test passed; that is, the test process
7116  // exited during the test, its exit status matches a user-supplied
7117  // predicate, and its stderr output matches a user-supplied regular
7118  // expression.
7119  // The user-supplied predicate may be a macro expression rather
7120  // than a function pointer or functor, or else Wait and Passed could
7121  // be combined.
7122  virtual bool Passed(bool exit_status_ok) = 0;
7123 
7124  // Signals that the death test did not die as expected.
7125  virtual void Abort(AbortReason reason) = 0;
7126 
7127  // Returns a human-readable outcome message regarding the outcome of
7128  // the last death test.
7129  static const char* LastMessage();
7130 
7131  static void set_last_death_test_message(const std::string& message);
7132 
7133  private:
7134  // A string containing a description of the outcome of the last death test.
7135  static std::string last_death_test_message_;
7136 
7137  GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
7138 };
7139 
7140 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
7141 
7142 // Factory interface for death tests. May be mocked out for testing.
7143 class DeathTestFactory {
7144  public:
7145  virtual ~DeathTestFactory() { }
7146  virtual bool Create(const char* statement,
7147  Matcher<const std::string&> matcher, const char* file,
7148  int line, DeathTest** test) = 0;
7149 };
7150 
7151 // A concrete DeathTestFactory implementation for normal use.
7152 class DefaultDeathTestFactory : public DeathTestFactory {
7153  public:
7154  bool Create(const char* statement, Matcher<const std::string&> matcher,
7155  const char* file, int line, DeathTest** test) override;
7156 };
7157 
7158 // Returns true if exit_status describes a process that was terminated
7159 // by a signal, or exited normally with a nonzero exit code.
7160 GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
7161 
7162 // A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
7163 // and interpreted as a regex (rather than an Eq matcher) for legacy
7164 // compatibility.
7165 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7166  ::testing::internal::RE regex) {
7167  return ContainsRegex(regex.pattern());
7168 }
7169 inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
7170  return ContainsRegex(regex);
7171 }
7172 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7173  const ::std::string& regex) {
7174  return ContainsRegex(regex);
7175 }
7176 
7177 // If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
7178 // used directly.
7179 inline Matcher<const ::std::string&> MakeDeathTestMatcher(
7180  Matcher<const ::std::string&> matcher) {
7181  return matcher;
7182 }
7183 
7184 // Traps C++ exceptions escaping statement and reports them as test
7185 // failures. Note that trapping SEH exceptions is not implemented here.
7186 # if GTEST_HAS_EXCEPTIONS
7187 # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
7188  try { \
7189  GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7190  } catch (const ::std::exception& gtest_exception) { \
7191  fprintf(\
7192  stderr, \
7193  "\n%s: Caught std::exception-derived exception escaping the " \
7194  "death test statement. Exception message: %s\n", \
7195  ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
7196  gtest_exception.what()); \
7197  fflush(stderr); \
7198  death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
7199  } catch (...) { \
7200  death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
7201  }
7202 
7203 # else
7204 # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
7205  GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
7206 
7207 # endif
7208 
7209 // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
7210 // ASSERT_EXIT*, and EXPECT_EXIT*.
7211 #define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \
7212  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7213  if (::testing::internal::AlwaysTrue()) { \
7214  ::testing::internal::DeathTest* gtest_dt; \
7215  if (!::testing::internal::DeathTest::Create( \
7216  #statement, \
7217  ::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \
7218  __FILE__, __LINE__, &gtest_dt)) { \
7219  goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
7220  } \
7221  if (gtest_dt != nullptr) { \
7222  std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
7223  switch (gtest_dt->AssumeRole()) { \
7224  case ::testing::internal::DeathTest::OVERSEE_TEST: \
7225  if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
7226  goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
7227  } \
7228  break; \
7229  case ::testing::internal::DeathTest::EXECUTE_TEST: { \
7230  ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
7231  gtest_dt); \
7232  GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
7233  gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
7234  break; \
7235  } \
7236  default: \
7237  break; \
7238  } \
7239  } \
7240  } else \
7241  GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
7242  : fail(::testing::internal::DeathTest::LastMessage())
7243 // The symbol "fail" here expands to something into which a message
7244 // can be streamed.
7245 
7246 // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
7247 // NDEBUG mode. In this case we need the statements to be executed and the macro
7248 // must accept a streamed message even though the message is never printed.
7249 // The regex object is not evaluated, but it is used to prevent "unused"
7250 // warnings and to avoid an expression that doesn't compile in debug mode.
7251 #define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
7252  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7253  if (::testing::internal::AlwaysTrue()) { \
7254  GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7255  } else if (!::testing::internal::AlwaysTrue()) { \
7256  ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
7257  } else \
7258  ::testing::Message()
7259 
7260 // A class representing the parsed contents of the
7261 // --gtest_internal_run_death_test flag, as it existed when
7262 // RUN_ALL_TESTS was called.
7263 class InternalRunDeathTestFlag {
7264  public:
7265  InternalRunDeathTestFlag(const std::string& a_file,
7266  int a_line,
7267  int an_index,
7268  int a_write_fd)
7269  : file_(a_file), line_(a_line), index_(an_index),
7270  write_fd_(a_write_fd) {}
7271 
7272  ~InternalRunDeathTestFlag() {
7273  if (write_fd_ >= 0)
7274  posix::Close(write_fd_);
7275  }
7276 
7277  const std::string& file() const { return file_; }
7278  int line() const { return line_; }
7279  int index() const { return index_; }
7280  int write_fd() const { return write_fd_; }
7281 
7282  private:
7283  std::string file_;
7284  int line_;
7285  int index_;
7286  int write_fd_;
7287 
7288  GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
7289 };
7290 
7291 // Returns a newly created InternalRunDeathTestFlag object with fields
7292 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7293 // the flag is specified; otherwise returns NULL.
7294 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
7295 
7296 #endif // GTEST_HAS_DEATH_TEST
7297 
7298 } // namespace internal
7299 } // namespace testing
7300 
7301 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
7302 
7303 namespace testing {
7304 
7305 // This flag controls the style of death tests. Valid values are "threadsafe",
7306 // meaning that the death test child process will re-execute the test binary
7307 // from the start, running only a single death test, or "fast",
7308 // meaning that the child process will execute the test logic immediately
7309 // after forking.
7310 GTEST_DECLARE_string_(death_test_style);
7311 
7312 #if GTEST_HAS_DEATH_TEST
7313 
7314 namespace internal {
7315 
7316 // Returns a Boolean value indicating whether the caller is currently
7317 // executing in the context of the death test child process. Tools such as
7318 // Valgrind heap checkers may need this to modify their behavior in death
7319 // tests. IMPORTANT: This is an internal utility. Using it may break the
7320 // implementation of death tests. User code MUST NOT use it.
7321 GTEST_API_ bool InDeathTestChild();
7322 
7323 } // namespace internal
7324 
7325 // The following macros are useful for writing death tests.
7326 
7327 // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
7328 // executed:
7329 //
7330 // 1. It generates a warning if there is more than one active
7331 // thread. This is because it's safe to fork() or clone() only
7332 // when there is a single thread.
7333 //
7334 // 2. The parent process clone()s a sub-process and runs the death
7335 // test in it; the sub-process exits with code 0 at the end of the
7336 // death test, if it hasn't exited already.
7337 //
7338 // 3. The parent process waits for the sub-process to terminate.
7339 //
7340 // 4. The parent process checks the exit code and error message of
7341 // the sub-process.
7342 //
7343 // Examples:
7344 //
7345 // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
7346 // for (int i = 0; i < 5; i++) {
7347 // EXPECT_DEATH(server.ProcessRequest(i),
7348 // "Invalid request .* in ProcessRequest()")
7349 // << "Failed to die on request " << i;
7350 // }
7351 //
7352 // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
7353 //
7354 // bool KilledBySIGHUP(int exit_code) {
7355 // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
7356 // }
7357 //
7358 // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
7359 //
7360 // On the regular expressions used in death tests:
7361 //
7362 // GOOGLETEST_CM0005 DO NOT DELETE
7363 // On POSIX-compliant systems (*nix), we use the <regex.h> library,
7364 // which uses the POSIX extended regex syntax.
7365 //
7366 // On other platforms (e.g. Windows or Mac), we only support a simple regex
7367 // syntax implemented as part of Google Test. This limited
7368 // implementation should be enough most of the time when writing
7369 // death tests; though it lacks many features you can find in PCRE
7370 // or POSIX extended regex syntax. For example, we don't support
7371 // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
7372 // repetition count ("x{5,7}"), among others.
7373 //
7374 // Below is the syntax that we do support. We chose it to be a
7375 // subset of both PCRE and POSIX extended regex, so it's easy to
7376 // learn wherever you come from. In the following: 'A' denotes a
7377 // literal character, period (.), or a single \\ escape sequence;
7378 // 'x' and 'y' denote regular expressions; 'm' and 'n' are for
7379 // natural numbers.
7380 //
7381 // c matches any literal character c
7382 // \\d matches any decimal digit
7383 // \\D matches any character that's not a decimal digit
7384 // \\f matches \f
7385 // \\n matches \n
7386 // \\r matches \r
7387 // \\s matches any ASCII whitespace, including \n
7388 // \\S matches any character that's not a whitespace
7389 // \\t matches \t
7390 // \\v matches \v
7391 // \\w matches any letter, _, or decimal digit
7392 // \\W matches any character that \\w doesn't match
7393 // \\c matches any literal character c, which must be a punctuation
7394 // . matches any single character except \n
7395 // A? matches 0 or 1 occurrences of A
7396 // A* matches 0 or many occurrences of A
7397 // A+ matches 1 or many occurrences of A
7398 // ^ matches the beginning of a string (not that of each line)
7399 // $ matches the end of a string (not that of each line)
7400 // xy matches x followed by y
7401 //
7402 // If you accidentally use PCRE or POSIX extended regex features
7403 // not implemented by us, you will get a run-time failure. In that
7404 // case, please try to rewrite your regular expression within the
7405 // above syntax.
7406 //
7407 // This implementation is *not* meant to be as highly tuned or robust
7408 // as a compiled regex library, but should perform well enough for a
7409 // death test, which already incurs significant overhead by launching
7410 // a child process.
7411 //
7412 // Known caveats:
7413 //
7414 // A "threadsafe" style death test obtains the path to the test
7415 // program from argv[0] and re-executes it in the sub-process. For
7416 // simplicity, the current implementation doesn't search the PATH
7417 // when launching the sub-process. This means that the user must
7418 // invoke the test program via a path that contains at least one
7419 // path separator (e.g. path/to/foo_test and
7420 // /absolute/path/to/bar_test are fine, but foo_test is not). This
7421 // is rarely a problem as people usually don't put the test binary
7422 // directory in PATH.
7423 //
7424 
7425 // Asserts that a given statement causes the program to exit, with an
7426 // integer exit status that satisfies predicate, and emitting error output
7427 // that matches regex.
7428 # define ASSERT_EXIT(statement, predicate, regex) \
7429  GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
7430 
7431 // Like ASSERT_EXIT, but continues on to successive tests in the
7432 // test suite, if any:
7433 # define EXPECT_EXIT(statement, predicate, regex) \
7434  GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_)
7435 
7436 // Asserts that a given statement causes the program to exit, either by
7437 // explicitly exiting with a nonzero exit code or being killed by a
7438 // signal, and emitting error output that matches regex.
7439 # define ASSERT_DEATH(statement, regex) \
7440  ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
7441 
7442 // Like ASSERT_DEATH, but continues on to successive tests in the
7443 // test suite, if any:
7444 # define EXPECT_DEATH(statement, regex) \
7445  EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
7446 
7447 // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
7448 
7449 // Tests that an exit code describes a normal exit with a given exit code.
7450 class GTEST_API_ ExitedWithCode {
7451  public:
7452  explicit ExitedWithCode(int exit_code);
7453  ExitedWithCode(const ExitedWithCode&) = default;
7454  void operator=(const ExitedWithCode& other) = delete;
7455  bool operator()(int exit_status) const;
7456  private:
7457  const int exit_code_;
7458 };
7459 
7460 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7461 // Tests that an exit code describes an exit due to termination by a
7462 // given signal.
7463 // GOOGLETEST_CM0006 DO NOT DELETE
7464 class GTEST_API_ KilledBySignal {
7465  public:
7466  explicit KilledBySignal(int signum);
7467  bool operator()(int exit_status) const;
7468  private:
7469  const int signum_;
7470 };
7471 # endif // !GTEST_OS_WINDOWS
7472 
7473 // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
7474 // The death testing framework causes this to have interesting semantics,
7475 // since the sideeffects of the call are only visible in opt mode, and not
7476 // in debug mode.
7477 //
7478 // In practice, this can be used to test functions that utilize the
7479 // LOG(DFATAL) macro using the following style:
7480 //
7481 // int DieInDebugOr12(int* sideeffect) {
7482 // if (sideeffect) {
7483 // *sideeffect = 12;
7484 // }
7485 // LOG(DFATAL) << "death";
7486 // return 12;
7487 // }
7488 //
7489 // TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
7490 // int sideeffect = 0;
7491 // // Only asserts in dbg.
7492 // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
7493 //
7494 // #ifdef NDEBUG
7495 // // opt-mode has sideeffect visible.
7496 // EXPECT_EQ(12, sideeffect);
7497 // #else
7498 // // dbg-mode no visible sideeffect.
7499 // EXPECT_EQ(0, sideeffect);
7500 // #endif
7501 // }
7502 //
7503 // This will assert that DieInDebugReturn12InOpt() crashes in debug
7504 // mode, usually due to a DCHECK or LOG(DFATAL), but returns the
7505 // appropriate fallback value (12 in this case) in opt mode. If you
7506 // need to test that a function has appropriate side-effects in opt
7507 // mode, include assertions against the side-effects. A general
7508 // pattern for this is:
7509 //
7510 // EXPECT_DEBUG_DEATH({
7511 // // Side-effects here will have an effect after this statement in
7512 // // opt mode, but none in debug mode.
7513 // EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
7514 // }, "death");
7515 //
7516 # ifdef NDEBUG
7517 
7518 # define EXPECT_DEBUG_DEATH(statement, regex) \
7519  GTEST_EXECUTE_STATEMENT_(statement, regex)
7520 
7521 # define ASSERT_DEBUG_DEATH(statement, regex) \
7522  GTEST_EXECUTE_STATEMENT_(statement, regex)
7523 
7524 # else
7525 
7526 # define EXPECT_DEBUG_DEATH(statement, regex) \
7527  EXPECT_DEATH(statement, regex)
7528 
7529 # define ASSERT_DEBUG_DEATH(statement, regex) \
7530  ASSERT_DEATH(statement, regex)
7531 
7532 # endif // NDEBUG for EXPECT_DEBUG_DEATH
7533 #endif // GTEST_HAS_DEATH_TEST
7534 
7535 // This macro is used for implementing macros such as
7536 // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
7537 // death tests are not supported. Those macros must compile on such systems
7538 // if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
7539 // on systems that support death tests. This allows one to write such a macro on
7540 // a system that does not support death tests and be sure that it will compile
7541 // on a death-test supporting system. It is exposed publicly so that systems
7542 // that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
7543 // can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
7544 // ASSERT_DEATH_IF_SUPPORTED.
7545 //
7546 // Parameters:
7547 // statement - A statement that a macro such as EXPECT_DEATH would test
7548 // for program termination. This macro has to make sure this
7549 // statement is compiled but not executed, to ensure that
7550 // EXPECT_DEATH_IF_SUPPORTED compiles with a certain
7551 // parameter if and only if EXPECT_DEATH compiles with it.
7552 // regex - A regex that a macro such as EXPECT_DEATH would use to test
7553 // the output of statement. This parameter has to be
7554 // compiled but not evaluated by this macro, to ensure that
7555 // this macro only accepts expressions that a macro such as
7556 // EXPECT_DEATH would accept.
7557 // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
7558 // and a return statement for ASSERT_DEATH_IF_SUPPORTED.
7559 // This ensures that ASSERT_DEATH_IF_SUPPORTED will not
7560 // compile inside functions where ASSERT_DEATH doesn't
7561 // compile.
7562 //
7563 // The branch that has an always false condition is used to ensure that
7564 // statement and regex are compiled (and thus syntactically correct) but
7565 // never executed. The unreachable code macro protects the terminator
7566 // statement from generating an 'unreachable code' warning in case
7567 // statement unconditionally returns or throws. The Message constructor at
7568 // the end allows the syntax of streaming additional messages into the
7569 // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
7570 # define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
7571  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
7572  if (::testing::internal::AlwaysTrue()) { \
7573  GTEST_LOG_(WARNING) \
7574  << "Death tests are not supported on this platform.\n" \
7575  << "Statement '" #statement "' cannot be verified."; \
7576  } else if (::testing::internal::AlwaysFalse()) { \
7577  ::testing::internal::RE::PartialMatch(".*", (regex)); \
7578  GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
7579  terminator; \
7580  } else \
7581  ::testing::Message()
7582 
7583 // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
7584 // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
7585 // death tests are supported; otherwise they just issue a warning. This is
7586 // useful when you are combining death test assertions with normal test
7587 // assertions in one test.
7588 #if GTEST_HAS_DEATH_TEST
7589 # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
7590  EXPECT_DEATH(statement, regex)
7591 # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
7592  ASSERT_DEATH(statement, regex)
7593 #else
7594 # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
7595  GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
7596 # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
7597  GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
7598 #endif
7599 
7600 } // namespace testing
7601 
7602 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
7603 // Copyright 2008, Google Inc.
7604 // All rights reserved.
7605 //
7606 // Redistribution and use in source and binary forms, with or without
7607 // modification, are permitted provided that the following conditions are
7608 // met:
7609 //
7610 // * Redistributions of source code must retain the above copyright
7611 // notice, this list of conditions and the following disclaimer.
7612 // * Redistributions in binary form must reproduce the above
7613 // copyright notice, this list of conditions and the following disclaimer
7614 // in the documentation and/or other materials provided with the
7615 // distribution.
7616 // * Neither the name of Google Inc. nor the names of its
7617 // contributors may be used to endorse or promote products derived from
7618 // this software without specific prior written permission.
7619 //
7620 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7621 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7622 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7623 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7624 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7625 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7626 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7627 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7628 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7629 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7630 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7631 //
7632 // Macros and functions for implementing parameterized tests
7633 // in Google C++ Testing and Mocking Framework (Google Test)
7634 //
7635 // GOOGLETEST_CM0001 DO NOT DELETE
7636 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
7637 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
7638 
7639 // Value-parameterized tests allow you to test your code with different
7640 // parameters without writing multiple copies of the same test.
7641 //
7642 // Here is how you use value-parameterized tests:
7643 
7644 #if 0
7645 
7646 // To write value-parameterized tests, first you should define a fixture
7647 // class. It is usually derived from testing::TestWithParam<T> (see below for
7648 // another inheritance scheme that's sometimes useful in more complicated
7649 // class hierarchies), where the type of your parameter values.
7650 // TestWithParam<T> is itself derived from testing::Test. T can be any
7651 // copyable type. If it's a raw pointer, you are responsible for managing the
7652 // lifespan of the pointed values.
7653 
7654 class FooTest : public ::testing::TestWithParam<const char*> {
7655  // You can implement all the usual class fixture members here.
7656 };
7657 
7658 // Then, use the TEST_P macro to define as many parameterized tests
7659 // for this fixture as you want. The _P suffix is for "parameterized"
7660 // or "pattern", whichever you prefer to think.
7661 
7662 TEST_P(FooTest, DoesBlah) {
7663  // Inside a test, access the test parameter with the GetParam() method
7664  // of the TestWithParam<T> class:
7665  EXPECT_TRUE(foo.Blah(GetParam()));
7666  ...
7667 }
7668 
7669 TEST_P(FooTest, HasBlahBlah) {
7670  ...
7671 }
7672 
7673 // Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test
7674 // case with any set of parameters you want. Google Test defines a number
7675 // of functions for generating test parameters. They return what we call
7676 // (surprise!) parameter generators. Here is a summary of them, which
7677 // are all in the testing namespace:
7678 //
7679 //
7680 // Range(begin, end [, step]) - Yields values {begin, begin+step,
7681 // begin+step+step, ...}. The values do not
7682 // include end. step defaults to 1.
7683 // Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}.
7684 // ValuesIn(container) - Yields values from a C-style array, an STL
7685 // ValuesIn(begin,end) container, or an iterator range [begin, end).
7686 // Bool() - Yields sequence {false, true}.
7687 // Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product
7688 // for the math savvy) of the values generated
7689 // by the N generators.
7690 //
7691 // For more details, see comments at the definitions of these functions below
7692 // in this file.
7693 //
7694 // The following statement will instantiate tests from the FooTest test suite
7695 // each with parameter values "meeny", "miny", and "moe".
7696 
7697 INSTANTIATE_TEST_SUITE_P(InstantiationName,
7698  FooTest,
7699  Values("meeny", "miny", "moe"));
7700 
7701 // To distinguish different instances of the pattern, (yes, you
7702 // can instantiate it more than once) the first argument to the
7703 // INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
7704 // actual test suite name. Remember to pick unique prefixes for different
7705 // instantiations. The tests from the instantiation above will have
7706 // these names:
7707 //
7708 // * InstantiationName/FooTest.DoesBlah/0 for "meeny"
7709 // * InstantiationName/FooTest.DoesBlah/1 for "miny"
7710 // * InstantiationName/FooTest.DoesBlah/2 for "moe"
7711 // * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
7712 // * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
7713 // * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
7714 //
7715 // You can use these names in --gtest_filter.
7716 //
7717 // This statement will instantiate all tests from FooTest again, each
7718 // with parameter values "cat" and "dog":
7719 
7720 const char* pets[] = {"cat", "dog"};
7721 INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
7722 
7723 // The tests from the instantiation above will have these names:
7724 //
7725 // * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
7726 // * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
7727 // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
7728 // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
7729 //
7730 // Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests
7731 // in the given test suite, whether their definitions come before or
7732 // AFTER the INSTANTIATE_TEST_SUITE_P statement.
7733 //
7734 // Please also note that generator expressions (including parameters to the
7735 // generators) are evaluated in InitGoogleTest(), after main() has started.
7736 // This allows the user on one hand, to adjust generator parameters in order
7737 // to dynamically determine a set of tests to run and on the other hand,
7738 // give the user a chance to inspect the generated tests with Google Test
7739 // reflection API before RUN_ALL_TESTS() is executed.
7740 //
7741 // You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
7742 // for more examples.
7743 //
7744 // In the future, we plan to publish the API for defining new parameter
7745 // generators. But for now this interface remains part of the internal
7746 // implementation and is subject to change.
7747 //
7748 //
7749 // A parameterized test fixture must be derived from testing::Test and from
7750 // testing::WithParamInterface<T>, where T is the type of the parameter
7751 // values. Inheriting from TestWithParam<T> satisfies that requirement because
7752 // TestWithParam<T> inherits from both Test and WithParamInterface. In more
7753 // complicated hierarchies, however, it is occasionally useful to inherit
7754 // separately from Test and WithParamInterface. For example:
7755 
7756 class BaseTest : public ::testing::Test {
7757  // You can inherit all the usual members for a non-parameterized test
7758  // fixture here.
7759 };
7760 
7761 class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
7762  // The usual test fixture members go here too.
7763 };
7764 
7765 TEST_F(BaseTest, HasFoo) {
7766  // This is an ordinary non-parameterized test.
7767 }
7768 
7769 TEST_P(DerivedTest, DoesBlah) {
7770  // GetParam works just the same here as if you inherit from TestWithParam.
7771  EXPECT_TRUE(foo.Blah(GetParam()));
7772 }
7773 
7774 #endif // 0
7775 
7776 #include <iterator>
7777 #include <utility>
7778 
7779 // Copyright 2008 Google Inc.
7780 // All Rights Reserved.
7781 //
7782 // Redistribution and use in source and binary forms, with or without
7783 // modification, are permitted provided that the following conditions are
7784 // met:
7785 //
7786 // * Redistributions of source code must retain the above copyright
7787 // notice, this list of conditions and the following disclaimer.
7788 // * Redistributions in binary form must reproduce the above
7789 // copyright notice, this list of conditions and the following disclaimer
7790 // in the documentation and/or other materials provided with the
7791 // distribution.
7792 // * Neither the name of Google Inc. nor the names of its
7793 // contributors may be used to endorse or promote products derived from
7794 // this software without specific prior written permission.
7795 //
7796 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7797 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7798 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7799 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7800 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7801 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7802 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7803 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7804 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7805 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7806 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7807 
7808 
7809 // Type and function utilities for implementing parameterized tests.
7810 
7811 // GOOGLETEST_CM0001 DO NOT DELETE
7812 
7813 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
7814 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
7815 
7816 #include <ctype.h>
7817 
7818 #include <cassert>
7819 #include <iterator>
7820 #include <memory>
7821 #include <set>
7822 #include <tuple>
7823 #include <type_traits>
7824 #include <utility>
7825 #include <vector>
7826 
7827 // Copyright 2008, Google Inc.
7828 // All rights reserved.
7829 //
7830 // Redistribution and use in source and binary forms, with or without
7831 // modification, are permitted provided that the following conditions are
7832 // met:
7833 //
7834 // * Redistributions of source code must retain the above copyright
7835 // notice, this list of conditions and the following disclaimer.
7836 // * Redistributions in binary form must reproduce the above
7837 // copyright notice, this list of conditions and the following disclaimer
7838 // in the documentation and/or other materials provided with the
7839 // distribution.
7840 // * Neither the name of Google Inc. nor the names of its
7841 // contributors may be used to endorse or promote products derived from
7842 // this software without specific prior written permission.
7843 //
7844 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7845 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7846 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7847 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7848 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7849 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7850 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7851 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7852 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7853 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7854 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7855 //
7856 // GOOGLETEST_CM0001 DO NOT DELETE
7857 
7858 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7859 #define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7860 
7861 #include <iosfwd>
7862 #include <vector>
7863 
7864 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
7865 /* class A needs to have dll-interface to be used by clients of class B */)
7866 
7867 namespace testing {
7868 
7869 // A copyable object representing the result of a test part (i.e. an
7870 // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
7871 //
7872 // Don't inherit from TestPartResult as its destructor is not virtual.
7873 class GTEST_API_ TestPartResult {
7874  public:
7875  // The possible outcomes of a test part (i.e. an assertion or an
7876  // explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
7877  enum Type {
7878  kSuccess, // Succeeded.
7879  kNonFatalFailure, // Failed but the test can continue.
7880  kFatalFailure, // Failed and the test should be terminated.
7881  kSkip // Skipped.
7882  };
7883 
7884  // C'tor. TestPartResult does NOT have a default constructor.
7885  // Always use this constructor (with parameters) to create a
7886  // TestPartResult object.
7887  TestPartResult(Type a_type, const char* a_file_name, int a_line_number,
7888  const char* a_message)
7889  : type_(a_type),
7890  file_name_(a_file_name == nullptr ? "" : a_file_name),
7891  line_number_(a_line_number),
7892  summary_(ExtractSummary(a_message)),
7893  message_(a_message) {}
7894 
7895  // Gets the outcome of the test part.
7896  Type type() const { return type_; }
7897 
7898  // Gets the name of the source file where the test part took place, or
7899  // NULL if it's unknown.
7900  const char* file_name() const {
7901  return file_name_.empty() ? nullptr : file_name_.c_str();
7902  }
7903 
7904  // Gets the line in the source file where the test part took place,
7905  // or -1 if it's unknown.
7906  int line_number() const { return line_number_; }
7907 
7908  // Gets the summary of the failure message.
7909  const char* summary() const { return summary_.c_str(); }
7910 
7911  // Gets the message associated with the test part.
7912  const char* message() const { return message_.c_str(); }
7913 
7914  // Returns true if and only if the test part was skipped.
7915  bool skipped() const { return type_ == kSkip; }
7916 
7917  // Returns true if and only if the test part passed.
7918  bool passed() const { return type_ == kSuccess; }
7919 
7920  // Returns true if and only if the test part non-fatally failed.
7921  bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
7922 
7923  // Returns true if and only if the test part fatally failed.
7924  bool fatally_failed() const { return type_ == kFatalFailure; }
7925 
7926  // Returns true if and only if the test part failed.
7927  bool failed() const { return fatally_failed() || nonfatally_failed(); }
7928 
7929  private:
7930  Type type_;
7931 
7932  // Gets the summary of the failure message by omitting the stack
7933  // trace in it.
7934  static std::string ExtractSummary(const char* message);
7935 
7936  // The name of the source file where the test part took place, or
7937  // "" if the source file is unknown.
7938  std::string file_name_;
7939  // The line in the source file where the test part took place, or -1
7940  // if the line number is unknown.
7941  int line_number_;
7942  std::string summary_; // The test failure summary.
7943  std::string message_; // The test failure message.
7944 };
7945 
7946 // Prints a TestPartResult object.
7947 std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
7948 
7949 // An array of TestPartResult objects.
7950 //
7951 // Don't inherit from TestPartResultArray as its destructor is not
7952 // virtual.
7953 class GTEST_API_ TestPartResultArray {
7954  public:
7955  TestPartResultArray() {}
7956 
7957  // Appends the given TestPartResult to the array.
7958  void Append(const TestPartResult& result);
7959 
7960  // Returns the TestPartResult at the given index (0-based).
7961  const TestPartResult& GetTestPartResult(int index) const;
7962 
7963  // Returns the number of TestPartResult objects in the array.
7964  int size() const;
7965 
7966  private:
7967  std::vector<TestPartResult> array_;
7968 
7969  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
7970 };
7971 
7972 // This interface knows how to report a test part result.
7973 class GTEST_API_ TestPartResultReporterInterface {
7974  public:
7975  virtual ~TestPartResultReporterInterface() {}
7976 
7977  virtual void ReportTestPartResult(const TestPartResult& result) = 0;
7978 };
7979 
7980 namespace internal {
7981 
7982 // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
7983 // statement generates new fatal failures. To do so it registers itself as the
7984 // current test part result reporter. Besides checking if fatal failures were
7985 // reported, it only delegates the reporting to the former result reporter.
7986 // The original result reporter is restored in the destructor.
7987 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
7988 class GTEST_API_ HasNewFatalFailureHelper
7989  : public TestPartResultReporterInterface {
7990  public:
7991  HasNewFatalFailureHelper();
7992  ~HasNewFatalFailureHelper() override;
7993  void ReportTestPartResult(const TestPartResult& result) override;
7994  bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
7995  private:
7996  bool has_new_fatal_failure_;
7997  TestPartResultReporterInterface* original_reporter_;
7998 
7999  GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
8000 };
8001 
8002 } // namespace internal
8003 
8004 } // namespace testing
8005 
8006 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
8007 
8008 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
8009 
8010 namespace testing {
8011 // Input to a parameterized test name generator, describing a test parameter.
8012 // Consists of the parameter value and the integer parameter index.
8013 template <class ParamType>
8014 struct TestParamInfo {
8015  TestParamInfo(const ParamType& a_param, size_t an_index) :
8016  param(a_param),
8017  index(an_index) {}
8018  ParamType param;
8019  size_t index;
8020 };
8021 
8022 // A builtin parameterized test name generator which returns the result of
8023 // testing::PrintToString.
8024 struct PrintToStringParamName {
8025  template <class ParamType>
8026  std::string operator()(const TestParamInfo<ParamType>& info) const {
8027  return PrintToString(info.param);
8028  }
8029 };
8030 
8031 namespace internal {
8032 
8033 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8034 // Utility Functions
8035 
8036 // Outputs a message explaining invalid registration of different
8037 // fixture class for the same test suite. This may happen when
8038 // TEST_P macro is used to define two tests with the same name
8039 // but in different namespaces.
8040 GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
8041  CodeLocation code_location);
8042 
8043 template <typename> class ParamGeneratorInterface;
8044 template <typename> class ParamGenerator;
8045 
8046 // Interface for iterating over elements provided by an implementation
8047 // of ParamGeneratorInterface<T>.
8048 template <typename T>
8049 class ParamIteratorInterface {
8050  public:
8051  virtual ~ParamIteratorInterface() {}
8052  // A pointer to the base generator instance.
8053  // Used only for the purposes of iterator comparison
8054  // to make sure that two iterators belong to the same generator.
8055  virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
8056  // Advances iterator to point to the next element
8057  // provided by the generator. The caller is responsible
8058  // for not calling Advance() on an iterator equal to
8059  // BaseGenerator()->End().
8060  virtual void Advance() = 0;
8061  // Clones the iterator object. Used for implementing copy semantics
8062  // of ParamIterator<T>.
8063  virtual ParamIteratorInterface* Clone() const = 0;
8064  // Dereferences the current iterator and provides (read-only) access
8065  // to the pointed value. It is the caller's responsibility not to call
8066  // Current() on an iterator equal to BaseGenerator()->End().
8067  // Used for implementing ParamGenerator<T>::operator*().
8068  virtual const T* Current() const = 0;
8069  // Determines whether the given iterator and other point to the same
8070  // element in the sequence generated by the generator.
8071  // Used for implementing ParamGenerator<T>::operator==().
8072  virtual bool Equals(const ParamIteratorInterface& other) const = 0;
8073 };
8074 
8075 // Class iterating over elements provided by an implementation of
8076 // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
8077 // and implements the const forward iterator concept.
8078 template <typename T>
8079 class ParamIterator {
8080  public:
8081  typedef T value_type;
8082  typedef const T& reference;
8083  typedef ptrdiff_t difference_type;
8084 
8085  // ParamIterator assumes ownership of the impl_ pointer.
8086  ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
8087  ParamIterator& operator=(const ParamIterator& other) {
8088  if (this != &other)
8089  impl_.reset(other.impl_->Clone());
8090  return *this;
8091  }
8092 
8093  const T& operator*() const { return *impl_->Current(); }
8094  const T* operator->() const { return impl_->Current(); }
8095  // Prefix version of operator++.
8096  ParamIterator& operator++() {
8097  impl_->Advance();
8098  return *this;
8099  }
8100  // Postfix version of operator++.
8101  ParamIterator operator++(int /*unused*/) {
8102  ParamIteratorInterface<T>* clone = impl_->Clone();
8103  impl_->Advance();
8104  return ParamIterator(clone);
8105  }
8106  bool operator==(const ParamIterator& other) const {
8107  return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
8108  }
8109  bool operator!=(const ParamIterator& other) const {
8110  return !(*this == other);
8111  }
8112 
8113  private:
8114  friend class ParamGenerator<T>;
8115  explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
8116  std::unique_ptr<ParamIteratorInterface<T> > impl_;
8117 };
8118 
8119 // ParamGeneratorInterface<T> is the binary interface to access generators
8120 // defined in other translation units.
8121 template <typename T>
8122 class ParamGeneratorInterface {
8123  public:
8124  typedef T ParamType;
8125 
8126  virtual ~ParamGeneratorInterface() {}
8127 
8128  // Generator interface definition
8129  virtual ParamIteratorInterface<T>* Begin() const = 0;
8130  virtual ParamIteratorInterface<T>* End() const = 0;
8131 };
8132 
8133 // Wraps ParamGeneratorInterface<T> and provides general generator syntax
8134 // compatible with the STL Container concept.
8135 // This class implements copy initialization semantics and the contained
8136 // ParamGeneratorInterface<T> instance is shared among all copies
8137 // of the original object. This is possible because that instance is immutable.
8138 template<typename T>
8139 class ParamGenerator {
8140  public:
8141  typedef ParamIterator<T> iterator;
8142 
8143  explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
8144  ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
8145 
8146  ParamGenerator& operator=(const ParamGenerator& other) {
8147  impl_ = other.impl_;
8148  return *this;
8149  }
8150 
8151  iterator begin() const { return iterator(impl_->Begin()); }
8152  iterator end() const { return iterator(impl_->End()); }
8153 
8154  private:
8155  std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
8156 };
8157 
8158 // Generates values from a range of two comparable values. Can be used to
8159 // generate sequences of user-defined types that implement operator+() and
8160 // operator<().
8161 // This class is used in the Range() function.
8162 template <typename T, typename IncrementT>
8163 class RangeGenerator : public ParamGeneratorInterface<T> {
8164  public:
8165  RangeGenerator(T begin, T end, IncrementT step)
8166  : begin_(begin), end_(end),
8167  step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
8168  ~RangeGenerator() override {}
8169 
8170  ParamIteratorInterface<T>* Begin() const override {
8171  return new Iterator(this, begin_, 0, step_);
8172  }
8173  ParamIteratorInterface<T>* End() const override {
8174  return new Iterator(this, end_, end_index_, step_);
8175  }
8176 
8177  private:
8178  class Iterator : public ParamIteratorInterface<T> {
8179  public:
8180  Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
8181  IncrementT step)
8182  : base_(base), value_(value), index_(index), step_(step) {}
8183  ~Iterator() override {}
8184 
8185  const ParamGeneratorInterface<T>* BaseGenerator() const override {
8186  return base_;
8187  }
8188  void Advance() override {
8189  value_ = static_cast<T>(value_ + step_);
8190  index_++;
8191  }
8192  ParamIteratorInterface<T>* Clone() const override {
8193  return new Iterator(*this);
8194  }
8195  const T* Current() const override { return &value_; }
8196  bool Equals(const ParamIteratorInterface<T>& other) const override {
8197  // Having the same base generator guarantees that the other
8198  // iterator is of the same type and we can downcast.
8199  GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8200  << "The program attempted to compare iterators "
8201  << "from different generators." << std::endl;
8202  const int other_index =
8203  CheckedDowncastToActualType<const Iterator>(&other)->index_;
8204  return index_ == other_index;
8205  }
8206 
8207  private:
8208  Iterator(const Iterator& other)
8209  : ParamIteratorInterface<T>(),
8210  base_(other.base_), value_(other.value_), index_(other.index_),
8211  step_(other.step_) {}
8212 
8213  // No implementation - assignment is unsupported.
8214  void operator=(const Iterator& other);
8215 
8216  const ParamGeneratorInterface<T>* const base_;
8217  T value_;
8218  int index_;
8219  const IncrementT step_;
8220  }; // class RangeGenerator::Iterator
8221 
8222  static int CalculateEndIndex(const T& begin,
8223  const T& end,
8224  const IncrementT& step) {
8225  int end_index = 0;
8226  for (T i = begin; i < end; i = static_cast<T>(i + step))
8227  end_index++;
8228  return end_index;
8229  }
8230 
8231  // No implementation - assignment is unsupported.
8232  void operator=(const RangeGenerator& other);
8233 
8234  const T begin_;
8235  const T end_;
8236  const IncrementT step_;
8237  // The index for the end() iterator. All the elements in the generated
8238  // sequence are indexed (0-based) to aid iterator comparison.
8239  const int end_index_;
8240 }; // class RangeGenerator
8241 
8242 
8243 // Generates values from a pair of STL-style iterators. Used in the
8244 // ValuesIn() function. The elements are copied from the source range
8245 // since the source can be located on the stack, and the generator
8246 // is likely to persist beyond that stack frame.
8247 template <typename T>
8248 class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
8249  public:
8250  template <typename ForwardIterator>
8251  ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
8252  : container_(begin, end) {}
8253  ~ValuesInIteratorRangeGenerator() override {}
8254 
8255  ParamIteratorInterface<T>* Begin() const override {
8256  return new Iterator(this, container_.begin());
8257  }
8258  ParamIteratorInterface<T>* End() const override {
8259  return new Iterator(this, container_.end());
8260  }
8261 
8262  private:
8263  typedef typename ::std::vector<T> ContainerType;
8264 
8265  class Iterator : public ParamIteratorInterface<T> {
8266  public:
8267  Iterator(const ParamGeneratorInterface<T>* base,
8268  typename ContainerType::const_iterator iterator)
8269  : base_(base), iterator_(iterator) {}
8270  ~Iterator() override {}
8271 
8272  const ParamGeneratorInterface<T>* BaseGenerator() const override {
8273  return base_;
8274  }
8275  void Advance() override {
8276  ++iterator_;
8277  value_.reset();
8278  }
8279  ParamIteratorInterface<T>* Clone() const override {
8280  return new Iterator(*this);
8281  }
8282  // We need to use cached value referenced by iterator_ because *iterator_
8283  // can return a temporary object (and of type other then T), so just
8284  // having "return &*iterator_;" doesn't work.
8285  // value_ is updated here and not in Advance() because Advance()
8286  // can advance iterator_ beyond the end of the range, and we cannot
8287  // detect that fact. The client code, on the other hand, is
8288  // responsible for not calling Current() on an out-of-range iterator.
8289  const T* Current() const override {
8290  if (value_.get() == nullptr) value_.reset(new T(*iterator_));
8291  return value_.get();
8292  }
8293  bool Equals(const ParamIteratorInterface<T>& other) const override {
8294  // Having the same base generator guarantees that the other
8295  // iterator is of the same type and we can downcast.
8296  GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8297  << "The program attempted to compare iterators "
8298  << "from different generators." << std::endl;
8299  return iterator_ ==
8300  CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
8301  }
8302 
8303  private:
8304  Iterator(const Iterator& other)
8305  // The explicit constructor call suppresses a false warning
8306  // emitted by gcc when supplied with the -Wextra option.
8307  : ParamIteratorInterface<T>(),
8308  base_(other.base_),
8309  iterator_(other.iterator_) {}
8310 
8311  const ParamGeneratorInterface<T>* const base_;
8312  typename ContainerType::const_iterator iterator_;
8313  // A cached value of *iterator_. We keep it here to allow access by
8314  // pointer in the wrapping iterator's operator->().
8315  // value_ needs to be mutable to be accessed in Current().
8316  // Use of std::unique_ptr helps manage cached value's lifetime,
8317  // which is bound by the lifespan of the iterator itself.
8318  mutable std::unique_ptr<const T> value_;
8319  }; // class ValuesInIteratorRangeGenerator::Iterator
8320 
8321  // No implementation - assignment is unsupported.
8322  void operator=(const ValuesInIteratorRangeGenerator& other);
8323 
8324  const ContainerType container_;
8325 }; // class ValuesInIteratorRangeGenerator
8326 
8327 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8328 //
8329 // Default parameterized test name generator, returns a string containing the
8330 // integer test parameter index.
8331 template <class ParamType>
8332 std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
8333  Message name_stream;
8334  name_stream << info.index;
8335  return name_stream.GetString();
8336 }
8337 
8338 template <typename T = int>
8339 void TestNotEmpty() {
8340  static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");
8341 }
8342 template <typename T = int>
8343 void TestNotEmpty(const T&) {}
8344 
8345 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8346 //
8347 // Stores a parameter value and later creates tests parameterized with that
8348 // value.
8349 template <class TestClass>
8350 class ParameterizedTestFactory : public TestFactoryBase {
8351  public:
8352  typedef typename TestClass::ParamType ParamType;
8353  explicit ParameterizedTestFactory(ParamType parameter) :
8354  parameter_(parameter) {}
8355  Test* CreateTest() override {
8356  TestClass::SetParam(&parameter_);
8357  return new TestClass();
8358  }
8359 
8360  private:
8361  const ParamType parameter_;
8362 
8363  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
8364 };
8365 
8366 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8367 //
8368 // TestMetaFactoryBase is a base class for meta-factories that create
8369 // test factories for passing into MakeAndRegisterTestInfo function.
8370 template <class ParamType>
8371 class TestMetaFactoryBase {
8372  public:
8373  virtual ~TestMetaFactoryBase() {}
8374 
8375  virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
8376 };
8377 
8378 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8379 //
8380 // TestMetaFactory creates test factories for passing into
8381 // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
8382 // ownership of test factory pointer, same factory object cannot be passed
8383 // into that method twice. But ParameterizedTestSuiteInfo is going to call
8384 // it for each Test/Parameter value combination. Thus it needs meta factory
8385 // creator class.
8386 template <class TestSuite>
8387 class TestMetaFactory
8388  : public TestMetaFactoryBase<typename TestSuite::ParamType> {
8389  public:
8390  using ParamType = typename TestSuite::ParamType;
8391 
8392  TestMetaFactory() {}
8393 
8394  TestFactoryBase* CreateTestFactory(ParamType parameter) override {
8395  return new ParameterizedTestFactory<TestSuite>(parameter);
8396  }
8397 
8398  private:
8399  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
8400 };
8401 
8402 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8403 //
8404 // ParameterizedTestSuiteInfoBase is a generic interface
8405 // to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase
8406 // accumulates test information provided by TEST_P macro invocations
8407 // and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations
8408 // and uses that information to register all resulting test instances
8409 // in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
8410 // a collection of pointers to the ParameterizedTestSuiteInfo objects
8411 // and calls RegisterTests() on each of them when asked.
8412 class ParameterizedTestSuiteInfoBase {
8413  public:
8414  virtual ~ParameterizedTestSuiteInfoBase() {}
8415 
8416  // Base part of test suite name for display purposes.
8417  virtual const std::string& GetTestSuiteName() const = 0;
8418  // Test suite id to verify identity.
8419  virtual TypeId GetTestSuiteTypeId() const = 0;
8420  // UnitTest class invokes this method to register tests in this
8421  // test suite right before running them in RUN_ALL_TESTS macro.
8422  // This method should not be called more than once on any single
8423  // instance of a ParameterizedTestSuiteInfoBase derived class.
8424  virtual void RegisterTests() = 0;
8425 
8426  protected:
8427  ParameterizedTestSuiteInfoBase() {}
8428 
8429  private:
8430  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
8431 };
8432 
8433 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8434 //
8435 // Report a the name of a test_suit as safe to ignore
8436 // as the side effect of construction of this type.
8437 struct MarkAsIgnored {
8438  explicit MarkAsIgnored(const char* test_suite);
8439 };
8440 
8441 GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
8442  CodeLocation location, bool has_test_p);
8443 
8444 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8445 //
8446 // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
8447 // macro invocations for a particular test suite and generators
8448 // obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that
8449 // test suite. It registers tests with all values generated by all
8450 // generators when asked.
8451 template <class TestSuite>
8452 class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
8453  public:
8454  // ParamType and GeneratorCreationFunc are private types but are required
8455  // for declarations of public methods AddTestPattern() and
8456  // AddTestSuiteInstantiation().
8457  using ParamType = typename TestSuite::ParamType;
8458  // A function that returns an instance of appropriate generator type.
8459  typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
8460  using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
8461 
8462  explicit ParameterizedTestSuiteInfo(const char* name,
8463  CodeLocation code_location)
8464  : test_suite_name_(name), code_location_(code_location) {}
8465 
8466  // Test suite base name for display purposes.
8467  const std::string& GetTestSuiteName() const override {
8468  return test_suite_name_;
8469  }
8470  // Test suite id to verify identity.
8471  TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
8472  // TEST_P macro uses AddTestPattern() to record information
8473  // about a single test in a LocalTestInfo structure.
8474  // test_suite_name is the base name of the test suite (without invocation
8475  // prefix). test_base_name is the name of an individual test without
8476  // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
8477  // test suite base name and DoBar is test base name.
8478  void AddTestPattern(const char* test_suite_name, const char* test_base_name,
8479  TestMetaFactoryBase<ParamType>* meta_factory,
8480  CodeLocation code_location) {
8481  tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
8482  test_suite_name, test_base_name, meta_factory, code_location)));
8483  }
8484  // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
8485  // about a generator.
8486  int AddTestSuiteInstantiation(const std::string& instantiation_name,
8487  GeneratorCreationFunc* func,
8488  ParamNameGeneratorFunc* name_func,
8489  const char* file, int line) {
8490  instantiations_.push_back(
8491  InstantiationInfo(instantiation_name, func, name_func, file, line));
8492  return 0; // Return value used only to run this method in namespace scope.
8493  }
8494  // UnitTest class invokes this method to register tests in this test suite
8495  // right before running tests in RUN_ALL_TESTS macro.
8496  // This method should not be called more than once on any single
8497  // instance of a ParameterizedTestSuiteInfoBase derived class.
8498  // UnitTest has a guard to prevent from calling this method more than once.
8499  void RegisterTests() override {
8500  bool generated_instantiations = false;
8501 
8502  for (typename TestInfoContainer::iterator test_it = tests_.begin();
8503  test_it != tests_.end(); ++test_it) {
8504  std::shared_ptr<TestInfo> test_info = *test_it;
8505  for (typename InstantiationContainer::iterator gen_it =
8506  instantiations_.begin(); gen_it != instantiations_.end();
8507  ++gen_it) {
8508  const std::string& instantiation_name = gen_it->name;
8509  ParamGenerator<ParamType> generator((*gen_it->generator)());
8510  ParamNameGeneratorFunc* name_func = gen_it->name_func;
8511  const char* file = gen_it->file;
8512  int line = gen_it->line;
8513 
8514  std::string test_suite_name;
8515  if ( !instantiation_name.empty() )
8516  test_suite_name = instantiation_name + "/";
8517  test_suite_name += test_info->test_suite_base_name;
8518 
8519  size_t i = 0;
8520  std::set<std::string> test_param_names;
8521  for (typename ParamGenerator<ParamType>::iterator param_it =
8522  generator.begin();
8523  param_it != generator.end(); ++param_it, ++i) {
8524  generated_instantiations = true;
8525 
8526  Message test_name_stream;
8527 
8528  std::string param_name = name_func(
8529  TestParamInfo<ParamType>(*param_it, i));
8530 
8531  GTEST_CHECK_(IsValidParamName(param_name))
8532  << "Parameterized test name '" << param_name
8533  << "' is invalid, in " << file
8534  << " line " << line << std::endl;
8535 
8536  GTEST_CHECK_(test_param_names.count(param_name) == 0)
8537  << "Duplicate parameterized test name '" << param_name
8538  << "', in " << file << " line " << line << std::endl;
8539 
8540  test_param_names.insert(param_name);
8541 
8542  if (!test_info->test_base_name.empty()) {
8543  test_name_stream << test_info->test_base_name << "/";
8544  }
8545  test_name_stream << param_name;
8546  MakeAndRegisterTestInfo(
8547  test_suite_name.c_str(), test_name_stream.GetString().c_str(),
8548  nullptr, // No type parameter.
8549  PrintToString(*param_it).c_str(), test_info->code_location,
8550  GetTestSuiteTypeId(),
8551  SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
8552  SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
8553  test_info->test_meta_factory->CreateTestFactory(*param_it));
8554  } // for param_it
8555  } // for gen_it
8556  } // for test_it
8557 
8558  if (!generated_instantiations) {
8559  // There are no generaotrs, or they all generate nothing ...
8560  InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
8561  !tests_.empty());
8562  }
8563  } // RegisterTests
8564 
8565  private:
8566  // LocalTestInfo structure keeps information about a single test registered
8567  // with TEST_P macro.
8568  struct TestInfo {
8569  TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
8570  TestMetaFactoryBase<ParamType>* a_test_meta_factory,
8571  CodeLocation a_code_location)
8572  : test_suite_base_name(a_test_suite_base_name),
8573  test_base_name(a_test_base_name),
8574  test_meta_factory(a_test_meta_factory),
8575  code_location(a_code_location) {}
8576 
8577  const std::string test_suite_base_name;
8578  const std::string test_base_name;
8579  const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
8580  const CodeLocation code_location;
8581  };
8582  using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
8583  // Records data received from INSTANTIATE_TEST_SUITE_P macros:
8584  // <Instantiation name, Sequence generator creation function,
8585  // Name generator function, Source file, Source line>
8586  struct InstantiationInfo {
8587  InstantiationInfo(const std::string &name_in,
8588  GeneratorCreationFunc* generator_in,
8589  ParamNameGeneratorFunc* name_func_in,
8590  const char* file_in,
8591  int line_in)
8592  : name(name_in),
8593  generator(generator_in),
8594  name_func(name_func_in),
8595  file(file_in),
8596  line(line_in) {}
8597 
8598  std::string name;
8599  GeneratorCreationFunc* generator;
8600  ParamNameGeneratorFunc* name_func;
8601  const char* file;
8602  int line;
8603  };
8604  typedef ::std::vector<InstantiationInfo> InstantiationContainer;
8605 
8606  static bool IsValidParamName(const std::string& name) {
8607  // Check for empty string
8608  if (name.empty())
8609  return false;
8610 
8611  // Check for invalid characters
8612  for (std::string::size_type index = 0; index < name.size(); ++index) {
8613  if (!isalnum(name[index]) && name[index] != '_')
8614  return false;
8615  }
8616 
8617  return true;
8618  }
8619 
8620  const std::string test_suite_name_;
8621  CodeLocation code_location_;
8622  TestInfoContainer tests_;
8623  InstantiationContainer instantiations_;
8624 
8625  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
8626 }; // class ParameterizedTestSuiteInfo
8627 
8628 // Legacy API is deprecated but still available
8629 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8630 template <class TestCase>
8631 using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
8632 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8633 
8634 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
8635 //
8636 // ParameterizedTestSuiteRegistry contains a map of
8637 // ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
8638 // and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
8639 // ParameterizedTestSuiteInfo descriptors.
8640 class ParameterizedTestSuiteRegistry {
8641  public:
8642  ParameterizedTestSuiteRegistry() {}
8643  ~ParameterizedTestSuiteRegistry() {
8644  for (auto& test_suite_info : test_suite_infos_) {
8645  delete test_suite_info;
8646  }
8647  }
8648 
8649  // Looks up or creates and returns a structure containing information about
8650  // tests and instantiations of a particular test suite.
8651  template <class TestSuite>
8652  ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
8653  const char* test_suite_name, CodeLocation code_location) {
8654  ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
8655  for (auto& test_suite_info : test_suite_infos_) {
8656  if (test_suite_info->GetTestSuiteName() == test_suite_name) {
8657  if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
8658  // Complain about incorrect usage of Google Test facilities
8659  // and terminate the program since we cannot guaranty correct
8660  // test suite setup and tear-down in this case.
8661  ReportInvalidTestSuiteType(test_suite_name, code_location);
8662  posix::Abort();
8663  } else {
8664  // At this point we are sure that the object we found is of the same
8665  // type we are looking for, so we downcast it to that type
8666  // without further checks.
8667  typed_test_info = CheckedDowncastToActualType<
8668  ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
8669  }
8670  break;
8671  }
8672  }
8673  if (typed_test_info == nullptr) {
8674  typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
8675  test_suite_name, code_location);
8676  test_suite_infos_.push_back(typed_test_info);
8677  }
8678  return typed_test_info;
8679  }
8680  void RegisterTests() {
8681  for (auto& test_suite_info : test_suite_infos_) {
8682  test_suite_info->RegisterTests();
8683  }
8684  }
8685 // Legacy API is deprecated but still available
8686 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8687  template <class TestCase>
8688  ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
8689  const char* test_case_name, CodeLocation code_location) {
8690  return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
8691  }
8692 
8693 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
8694 
8695  private:
8696  using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
8697 
8698  TestSuiteInfoContainer test_suite_infos_;
8699 
8700  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
8701 };
8702 
8703 // Keep track of what type-parameterized test suite are defined and
8704 // where as well as which are intatiated. This allows susequently
8705 // identifying suits that are defined but never used.
8706 class TypeParameterizedTestSuiteRegistry {
8707  public:
8708  // Add a suite definition
8709  void RegisterTestSuite(const char* test_suite_name,
8710  CodeLocation code_location);
8711 
8712  // Add an instantiation of a suit.
8713  void RegisterInstantiation(const char* test_suite_name);
8714 
8715  // For each suit repored as defined but not reported as instantiation,
8716  // emit a test that reports that fact (configurably, as an error).
8717  void CheckForInstantiations();
8718 
8719  private:
8720  struct TypeParameterizedTestSuiteInfo {
8721  explicit TypeParameterizedTestSuiteInfo(CodeLocation c)
8722  : code_location(c), instantiated(false) {}
8723 
8724  CodeLocation code_location;
8725  bool instantiated;
8726  };
8727 
8728  std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;
8729 };
8730 
8731 } // namespace internal
8732 
8733 // Forward declarations of ValuesIn(), which is implemented in
8734 // include/gtest/gtest-param-test.h.
8735 template <class Container>
8736 internal::ParamGenerator<typename Container::value_type> ValuesIn(
8737  const Container& container);
8738 
8739 namespace internal {
8740 // Used in the Values() function to provide polymorphic capabilities.
8741 
8742 #ifdef _MSC_VER
8743 #pragma warning(push)
8744 #pragma warning(disable : 4100)
8745 #endif
8746 
8747 template <typename... Ts>
8748 class ValueArray {
8749  public:
8750  explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
8751 
8752  template <typename T>
8753  operator ParamGenerator<T>() const { // NOLINT
8754  return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
8755  }
8756 
8757  private:
8758  template <typename T, size_t... I>
8759  std::vector<T> MakeVector(IndexSequence<I...>) const {
8760  return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
8761  }
8762 
8763  FlatTuple<Ts...> v_;
8764 };
8765 
8766 #ifdef _MSC_VER
8767 #pragma warning(pop)
8768 #endif
8769 
8770 template <typename... T>
8771 class CartesianProductGenerator
8772  : public ParamGeneratorInterface<::std::tuple<T...>> {
8773  public:
8774  typedef ::std::tuple<T...> ParamType;
8775 
8776  CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
8777  : generators_(g) {}
8778  ~CartesianProductGenerator() override {}
8779 
8780  ParamIteratorInterface<ParamType>* Begin() const override {
8781  return new Iterator(this, generators_, false);
8782  }
8783  ParamIteratorInterface<ParamType>* End() const override {
8784  return new Iterator(this, generators_, true);
8785  }
8786 
8787  private:
8788  template <class I>
8789  class IteratorImpl;
8790  template <size_t... I>
8791  class IteratorImpl<IndexSequence<I...>>
8792  : public ParamIteratorInterface<ParamType> {
8793  public:
8794  IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
8795  const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
8796  : base_(base),
8797  begin_(std::get<I>(generators).begin()...),
8798  end_(std::get<I>(generators).end()...),
8799  current_(is_end ? end_ : begin_) {
8800  ComputeCurrentValue();
8801  }
8802  ~IteratorImpl() override {}
8803 
8804  const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
8805  return base_;
8806  }
8807  // Advance should not be called on beyond-of-range iterators
8808  // so no component iterators must be beyond end of range, either.
8809  void Advance() override {
8810  assert(!AtEnd());
8811  // Advance the last iterator.
8812  ++std::get<sizeof...(T) - 1>(current_);
8813  // if that reaches end, propagate that up.
8814  AdvanceIfEnd<sizeof...(T) - 1>();
8815  ComputeCurrentValue();
8816  }
8817  ParamIteratorInterface<ParamType>* Clone() const override {
8818  return new IteratorImpl(*this);
8819  }
8820 
8821  const ParamType* Current() const override { return current_value_.get(); }
8822 
8823  bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
8824  // Having the same base generator guarantees that the other
8825  // iterator is of the same type and we can downcast.
8826  GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
8827  << "The program attempted to compare iterators "
8828  << "from different generators." << std::endl;
8829  const IteratorImpl* typed_other =
8830  CheckedDowncastToActualType<const IteratorImpl>(&other);
8831 
8832  // We must report iterators equal if they both point beyond their
8833  // respective ranges. That can happen in a variety of fashions,
8834  // so we have to consult AtEnd().
8835  if (AtEnd() && typed_other->AtEnd()) return true;
8836 
8837  bool same = true;
8838  bool dummy[] = {
8839  (same = same && std::get<I>(current_) ==
8840  std::get<I>(typed_other->current_))...};
8841  (void)dummy;
8842  return same;
8843  }
8844 
8845  private:
8846  template <size_t ThisI>
8847  void AdvanceIfEnd() {
8848  if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
8849 
8850  bool last = ThisI == 0;
8851  if (last) {
8852  // We are done. Nothing else to propagate.
8853  return;
8854  }
8855 
8856  constexpr size_t NextI = ThisI - (ThisI != 0);
8857  std::get<ThisI>(current_) = std::get<ThisI>(begin_);
8858  ++std::get<NextI>(current_);
8859  AdvanceIfEnd<NextI>();
8860  }
8861 
8862  void ComputeCurrentValue() {
8863  if (!AtEnd())
8864  current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
8865  }
8866  bool AtEnd() const {
8867  bool at_end = false;
8868  bool dummy[] = {
8869  (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
8870  (void)dummy;
8871  return at_end;
8872  }
8873 
8874  const ParamGeneratorInterface<ParamType>* const base_;
8875  std::tuple<typename ParamGenerator<T>::iterator...> begin_;
8876  std::tuple<typename ParamGenerator<T>::iterator...> end_;
8877  std::tuple<typename ParamGenerator<T>::iterator...> current_;
8878  std::shared_ptr<ParamType> current_value_;
8879  };
8880 
8881  using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
8882 
8883  std::tuple<ParamGenerator<T>...> generators_;
8884 };
8885 
8886 template <class... Gen>
8887 class CartesianProductHolder {
8888  public:
8889  CartesianProductHolder(const Gen&... g) : generators_(g...) {}
8890  template <typename... T>
8891  operator ParamGenerator<::std::tuple<T...>>() const {
8892  return ParamGenerator<::std::tuple<T...>>(
8893  new CartesianProductGenerator<T...>(generators_));
8894  }
8895 
8896  private:
8897  std::tuple<Gen...> generators_;
8898 };
8899 
8900 } // namespace internal
8901 } // namespace testing
8902 
8903 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
8904 
8905 namespace testing {
8906 
8907 // Functions producing parameter generators.
8908 //
8909 // Google Test uses these generators to produce parameters for value-
8910 // parameterized tests. When a parameterized test suite is instantiated
8911 // with a particular generator, Google Test creates and runs tests
8912 // for each element in the sequence produced by the generator.
8913 //
8914 // In the following sample, tests from test suite FooTest are instantiated
8915 // each three times with parameter values 3, 5, and 8:
8916 //
8917 // class FooTest : public TestWithParam<int> { ... };
8918 //
8919 // TEST_P(FooTest, TestThis) {
8920 // }
8921 // TEST_P(FooTest, TestThat) {
8922 // }
8923 // INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));
8924 //
8925 
8926 // Range() returns generators providing sequences of values in a range.
8927 //
8928 // Synopsis:
8929 // Range(start, end)
8930 // - returns a generator producing a sequence of values {start, start+1,
8931 // start+2, ..., }.
8932 // Range(start, end, step)
8933 // - returns a generator producing a sequence of values {start, start+step,
8934 // start+step+step, ..., }.
8935 // Notes:
8936 // * The generated sequences never include end. For example, Range(1, 5)
8937 // returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
8938 // returns a generator producing {1, 3, 5, 7}.
8939 // * start and end must have the same type. That type may be any integral or
8940 // floating-point type or a user defined type satisfying these conditions:
8941 // * It must be assignable (have operator=() defined).
8942 // * It must have operator+() (operator+(int-compatible type) for
8943 // two-operand version).
8944 // * It must have operator<() defined.
8945 // Elements in the resulting sequences will also have that type.
8946 // * Condition start < end must be satisfied in order for resulting sequences
8947 // to contain any elements.
8948 //
8949 template <typename T, typename IncrementT>
8950 internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
8951  return internal::ParamGenerator<T>(
8952  new internal::RangeGenerator<T, IncrementT>(start, end, step));
8953 }
8954 
8955 template <typename T>
8956 internal::ParamGenerator<T> Range(T start, T end) {
8957  return Range(start, end, 1);
8958 }
8959 
8960 // ValuesIn() function allows generation of tests with parameters coming from
8961 // a container.
8962 //
8963 // Synopsis:
8964 // ValuesIn(const T (&array)[N])
8965 // - returns a generator producing sequences with elements from
8966 // a C-style array.
8967 // ValuesIn(const Container& container)
8968 // - returns a generator producing sequences with elements from
8969 // an STL-style container.
8970 // ValuesIn(Iterator begin, Iterator end)
8971 // - returns a generator producing sequences with elements from
8972 // a range [begin, end) defined by a pair of STL-style iterators. These
8973 // iterators can also be plain C pointers.
8974 //
8975 // Please note that ValuesIn copies the values from the containers
8976 // passed in and keeps them to generate tests in RUN_ALL_TESTS().
8977 //
8978 // Examples:
8979 //
8980 // This instantiates tests from test suite StringTest
8981 // each with C-string values of "foo", "bar", and "baz":
8982 //
8983 // const char* strings[] = {"foo", "bar", "baz"};
8984 // INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));
8985 //
8986 // This instantiates tests from test suite StlStringTest
8987 // each with STL strings with values "a" and "b":
8988 //
8989 // ::std::vector< ::std::string> GetParameterStrings() {
8990 // ::std::vector< ::std::string> v;
8991 // v.push_back("a");
8992 // v.push_back("b");
8993 // return v;
8994 // }
8995 //
8996 // INSTANTIATE_TEST_SUITE_P(CharSequence,
8997 // StlStringTest,
8998 // ValuesIn(GetParameterStrings()));
8999 //
9000 //
9001 // This will also instantiate tests from CharTest
9002 // each with parameter values 'a' and 'b':
9003 //
9004 // ::std::list<char> GetParameterChars() {
9005 // ::std::list<char> list;
9006 // list.push_back('a');
9007 // list.push_back('b');
9008 // return list;
9009 // }
9010 // ::std::list<char> l = GetParameterChars();
9011 // INSTANTIATE_TEST_SUITE_P(CharSequence2,
9012 // CharTest,
9013 // ValuesIn(l.begin(), l.end()));
9014 //
9015 template <typename ForwardIterator>
9016 internal::ParamGenerator<
9017  typename std::iterator_traits<ForwardIterator>::value_type>
9018 ValuesIn(ForwardIterator begin, ForwardIterator end) {
9019  typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;
9020  return internal::ParamGenerator<ParamType>(
9021  new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
9022 }
9023 
9024 template <typename T, size_t N>
9025 internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
9026  return ValuesIn(array, array + N);
9027 }
9028 
9029 template <class Container>
9030 internal::ParamGenerator<typename Container::value_type> ValuesIn(
9031  const Container& container) {
9032  return ValuesIn(container.begin(), container.end());
9033 }
9034 
9035 // Values() allows generating tests from explicitly specified list of
9036 // parameters.
9037 //
9038 // Synopsis:
9039 // Values(T v1, T v2, ..., T vN)
9040 // - returns a generator producing sequences with elements v1, v2, ..., vN.
9041 //
9042 // For example, this instantiates tests from test suite BarTest each
9043 // with values "one", "two", and "three":
9044 //
9045 // INSTANTIATE_TEST_SUITE_P(NumSequence,
9046 // BarTest,
9047 // Values("one", "two", "three"));
9048 //
9049 // This instantiates tests from test suite BazTest each with values 1, 2, 3.5.
9050 // The exact type of values will depend on the type of parameter in BazTest.
9051 //
9052 // INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
9053 //
9054 //
9055 template <typename... T>
9056 internal::ValueArray<T...> Values(T... v) {
9057  return internal::ValueArray<T...>(std::move(v)...);
9058 }
9059 
9060 // Bool() allows generating tests with parameters in a set of (false, true).
9061 //
9062 // Synopsis:
9063 // Bool()
9064 // - returns a generator producing sequences with elements {false, true}.
9065 //
9066 // It is useful when testing code that depends on Boolean flags. Combinations
9067 // of multiple flags can be tested when several Bool()'s are combined using
9068 // Combine() function.
9069 //
9070 // In the following example all tests in the test suite FlagDependentTest
9071 // will be instantiated twice with parameters false and true.
9072 //
9073 // class FlagDependentTest : public testing::TestWithParam<bool> {
9074 // virtual void SetUp() {
9075 // external_flag = GetParam();
9076 // }
9077 // }
9078 // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
9079 //
9080 inline internal::ParamGenerator<bool> Bool() {
9081  return Values(false, true);
9082 }
9083 
9084 // Combine() allows the user to combine two or more sequences to produce
9085 // values of a Cartesian product of those sequences' elements.
9086 //
9087 // Synopsis:
9088 // Combine(gen1, gen2, ..., genN)
9089 // - returns a generator producing sequences with elements coming from
9090 // the Cartesian product of elements from the sequences generated by
9091 // gen1, gen2, ..., genN. The sequence elements will have a type of
9092 // std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
9093 // of elements from sequences produces by gen1, gen2, ..., genN.
9094 //
9095 // Example:
9096 //
9097 // This will instantiate tests in test suite AnimalTest each one with
9098 // the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
9099 // tuple("dog", BLACK), and tuple("dog", WHITE):
9100 //
9101 // enum Color { BLACK, GRAY, WHITE };
9102 // class AnimalTest
9103 // : public testing::TestWithParam<std::tuple<const char*, Color> > {...};
9104 //
9105 // TEST_P(AnimalTest, AnimalLooksNice) {...}
9106 //
9107 // INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
9108 // Combine(Values("cat", "dog"),
9109 // Values(BLACK, WHITE)));
9110 //
9111 // This will instantiate tests in FlagDependentTest with all variations of two
9112 // Boolean flags:
9113 //
9114 // class FlagDependentTest
9115 // : public testing::TestWithParam<std::tuple<bool, bool> > {
9116 // virtual void SetUp() {
9117 // // Assigns external_flag_1 and external_flag_2 values from the tuple.
9118 // std::tie(external_flag_1, external_flag_2) = GetParam();
9119 // }
9120 // };
9121 //
9122 // TEST_P(FlagDependentTest, TestFeature1) {
9123 // // Test your code using external_flag_1 and external_flag_2 here.
9124 // }
9125 // INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,
9126 // Combine(Bool(), Bool()));
9127 //
9128 template <typename... Generator>
9129 internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
9130  return internal::CartesianProductHolder<Generator...>(g...);
9131 }
9132 
9133 #define TEST_P(test_suite_name, test_name) \
9134  class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
9135  : public test_suite_name { \
9136  public: \
9137  GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
9138  void TestBody() override; \
9139  \
9140  private: \
9141  static int AddToRegistry() { \
9142  ::testing::UnitTest::GetInstance() \
9143  ->parameterized_test_registry() \
9144  .GetTestSuitePatternHolder<test_suite_name>( \
9145  GTEST_STRINGIFY_(test_suite_name), \
9146  ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
9147  ->AddTestPattern( \
9148  GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
9149  new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
9150  test_suite_name, test_name)>(), \
9151  ::testing::internal::CodeLocation(__FILE__, __LINE__)); \
9152  return 0; \
9153  } \
9154  static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
9155  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
9156  test_name)); \
9157  }; \
9158  int GTEST_TEST_CLASS_NAME_(test_suite_name, \
9159  test_name)::gtest_registering_dummy_ = \
9160  GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \
9161  void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
9162 
9163 // The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify
9164 // generator and an optional function or functor that generates custom test name
9165 // suffixes based on the test parameters. Such a function or functor should
9166 // accept one argument of type testing::TestParamInfo<class ParamType>, and
9167 // return std::string.
9168 //
9169 // testing::PrintToStringParamName is a builtin test suffix generator that
9170 // returns the value of testing::PrintToString(GetParam()).
9171 //
9172 // Note: test names must be non-empty, unique, and may only contain ASCII
9173 // alphanumeric characters or underscore. Because PrintToString adds quotes
9174 // to std::string and C strings, it won't work for these types.
9175 
9176 #define GTEST_EXPAND_(arg) arg
9177 #define GTEST_GET_FIRST_(first, ...) first
9178 #define GTEST_GET_SECOND_(first, second, ...) second
9179 
9180 #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
9181  static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
9182  gtest_##prefix##test_suite_name##_EvalGenerator_() { \
9183  return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
9184  } \
9185  static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
9186  const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
9187  if (::testing::internal::AlwaysFalse()) { \
9188  ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
9189  __VA_ARGS__, \
9190  ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
9191  DUMMY_PARAM_))); \
9192  auto t = std::make_tuple(__VA_ARGS__); \
9193  static_assert(std::tuple_size<decltype(t)>::value <= 2, \
9194  "Too Many Args!"); \
9195  } \
9196  return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
9197  __VA_ARGS__, \
9198  ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
9199  DUMMY_PARAM_))))(info); \
9200  } \
9201  static int gtest_##prefix##test_suite_name##_dummy_ \
9202  GTEST_ATTRIBUTE_UNUSED_ = \
9203  ::testing::UnitTest::GetInstance() \
9204  ->parameterized_test_registry() \
9205  .GetTestSuitePatternHolder<test_suite_name>( \
9206  GTEST_STRINGIFY_(test_suite_name), \
9207  ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
9208  ->AddTestSuiteInstantiation( \
9209  GTEST_STRINGIFY_(prefix), \
9210  &gtest_##prefix##test_suite_name##_EvalGenerator_, \
9211  &gtest_##prefix##test_suite_name##_EvalGenerateName_, \
9212  __FILE__, __LINE__)
9213 
9214 
9215 // Allow Marking a Parameterized test class as not needing to be instantiated.
9216 #define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
9217  namespace gtest_do_not_use_outside_namespace_scope {} \
9218  static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
9219  GTEST_STRINGIFY_(T))
9220 
9221 // Legacy API is deprecated but still available
9222 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9223 #define INSTANTIATE_TEST_CASE_P \
9224  static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \
9225  ""); \
9226  INSTANTIATE_TEST_SUITE_P
9227 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9228 
9229 } // namespace testing
9230 
9231 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
9232 // Copyright 2006, Google Inc.
9233 // All rights reserved.
9234 //
9235 // Redistribution and use in source and binary forms, with or without
9236 // modification, are permitted provided that the following conditions are
9237 // met:
9238 //
9239 // * Redistributions of source code must retain the above copyright
9240 // notice, this list of conditions and the following disclaimer.
9241 // * Redistributions in binary form must reproduce the above
9242 // copyright notice, this list of conditions and the following disclaimer
9243 // in the documentation and/or other materials provided with the
9244 // distribution.
9245 // * Neither the name of Google Inc. nor the names of its
9246 // contributors may be used to endorse or promote products derived from
9247 // this software without specific prior written permission.
9248 //
9249 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9250 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9251 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9252 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9253 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9254 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9255 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9256 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9257 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9258 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9259 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9260 
9261 //
9262 // Google C++ Testing and Mocking Framework definitions useful in production code.
9263 // GOOGLETEST_CM0003 DO NOT DELETE
9264 
9265 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9266 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9267 
9268 // When you need to test the private or protected members of a class,
9269 // use the FRIEND_TEST macro to declare your tests as friends of the
9270 // class. For example:
9271 //
9272 // class MyClass {
9273 // private:
9274 // void PrivateMethod();
9275 // FRIEND_TEST(MyClassTest, PrivateMethodWorks);
9276 // };
9277 //
9278 // class MyClassTest : public testing::Test {
9279 // // ...
9280 // };
9281 //
9282 // TEST_F(MyClassTest, PrivateMethodWorks) {
9283 // // Can call MyClass::PrivateMethod() here.
9284 // }
9285 //
9286 // Note: The test class must be in the same namespace as the class being tested.
9287 // For example, putting MyClassTest in an anonymous namespace will not work.
9288 
9289 #define FRIEND_TEST(test_case_name, test_name)\
9290 friend class test_case_name##_##test_name##_Test
9291 
9292 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
9293 // Copyright 2008 Google Inc.
9294 // All Rights Reserved.
9295 //
9296 // Redistribution and use in source and binary forms, with or without
9297 // modification, are permitted provided that the following conditions are
9298 // met:
9299 //
9300 // * Redistributions of source code must retain the above copyright
9301 // notice, this list of conditions and the following disclaimer.
9302 // * Redistributions in binary form must reproduce the above
9303 // copyright notice, this list of conditions and the following disclaimer
9304 // in the documentation and/or other materials provided with the
9305 // distribution.
9306 // * Neither the name of Google Inc. nor the names of its
9307 // contributors may be used to endorse or promote products derived from
9308 // this software without specific prior written permission.
9309 //
9310 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9311 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9312 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9313 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9314 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9315 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9316 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9317 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9318 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9319 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9320 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9321 
9322 // GOOGLETEST_CM0001 DO NOT DELETE
9323 
9324 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9325 #define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9326 
9327 // This header implements typed tests and type-parameterized tests.
9328 
9329 // Typed (aka type-driven) tests repeat the same test for types in a
9330 // list. You must know which types you want to test with when writing
9331 // typed tests. Here's how you do it:
9332 
9333 #if 0
9334 
9335 // First, define a fixture class template. It should be parameterized
9336 // by a type. Remember to derive it from testing::Test.
9337 template <typename T>
9338 class FooTest : public testing::Test {
9339  public:
9340  ...
9341  typedef std::list<T> List;
9342  static T shared_;
9343  T value_;
9344 };
9345 
9346 // Next, associate a list of types with the test suite, which will be
9347 // repeated for each type in the list. The typedef is necessary for
9348 // the macro to parse correctly.
9349 typedef testing::Types<char, int, unsigned int> MyTypes;
9350 TYPED_TEST_SUITE(FooTest, MyTypes);
9351 
9352 // If the type list contains only one type, you can write that type
9353 // directly without Types<...>:
9354 // TYPED_TEST_SUITE(FooTest, int);
9355 
9356 // Then, use TYPED_TEST() instead of TEST_F() to define as many typed
9357 // tests for this test suite as you want.
9358 TYPED_TEST(FooTest, DoesBlah) {
9359  // Inside a test, refer to the special name TypeParam to get the type
9360  // parameter. Since we are inside a derived class template, C++ requires
9361  // us to visit the members of FooTest via 'this'.
9362  TypeParam n = this->value_;
9363 
9364  // To visit static members of the fixture, add the TestFixture::
9365  // prefix.
9366  n += TestFixture::shared_;
9367 
9368  // To refer to typedefs in the fixture, add the "typename
9369  // TestFixture::" prefix.
9370  typename TestFixture::List values;
9371  values.push_back(n);
9372  ...
9373 }
9374 
9375 TYPED_TEST(FooTest, HasPropertyA) { ... }
9376 
9377 // TYPED_TEST_SUITE takes an optional third argument which allows to specify a
9378 // class that generates custom test name suffixes based on the type. This should
9379 // be a class which has a static template function GetName(int index) returning
9380 // a string for each type. The provided integer index equals the index of the
9381 // type in the provided type list. In many cases the index can be ignored.
9382 //
9383 // For example:
9384 // class MyTypeNames {
9385 // public:
9386 // template <typename T>
9387 // static std::string GetName(int) {
9388 // if (std::is_same<T, char>()) return "char";
9389 // if (std::is_same<T, int>()) return "int";
9390 // if (std::is_same<T, unsigned int>()) return "unsignedInt";
9391 // }
9392 // };
9393 // TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);
9394 
9395 #endif // 0
9396 
9397 // Type-parameterized tests are abstract test patterns parameterized
9398 // by a type. Compared with typed tests, type-parameterized tests
9399 // allow you to define the test pattern without knowing what the type
9400 // parameters are. The defined pattern can be instantiated with
9401 // different types any number of times, in any number of translation
9402 // units.
9403 //
9404 // If you are designing an interface or concept, you can define a
9405 // suite of type-parameterized tests to verify properties that any
9406 // valid implementation of the interface/concept should have. Then,
9407 // each implementation can easily instantiate the test suite to verify
9408 // that it conforms to the requirements, without having to write
9409 // similar tests repeatedly. Here's an example:
9410 
9411 #if 0
9412 
9413 // First, define a fixture class template. It should be parameterized
9414 // by a type. Remember to derive it from testing::Test.
9415 template <typename T>
9416 class FooTest : public testing::Test {
9417  ...
9418 };
9419 
9420 // Next, declare that you will define a type-parameterized test suite
9421 // (the _P suffix is for "parameterized" or "pattern", whichever you
9422 // prefer):
9423 TYPED_TEST_SUITE_P(FooTest);
9424 
9425 // Then, use TYPED_TEST_P() to define as many type-parameterized tests
9426 // for this type-parameterized test suite as you want.
9427 TYPED_TEST_P(FooTest, DoesBlah) {
9428  // Inside a test, refer to TypeParam to get the type parameter.
9429  TypeParam n = 0;
9430  ...
9431 }
9432 
9433 TYPED_TEST_P(FooTest, HasPropertyA) { ... }
9434 
9435 // Now the tricky part: you need to register all test patterns before
9436 // you can instantiate them. The first argument of the macro is the
9437 // test suite name; the rest are the names of the tests in this test
9438 // case.
9439 REGISTER_TYPED_TEST_SUITE_P(FooTest,
9440  DoesBlah, HasPropertyA);
9441 
9442 // Finally, you are free to instantiate the pattern with the types you
9443 // want. If you put the above code in a header file, you can #include
9444 // it in multiple C++ source files and instantiate it multiple times.
9445 //
9446 // To distinguish different instances of the pattern, the first
9447 // argument to the INSTANTIATE_* macro is a prefix that will be added
9448 // to the actual test suite name. Remember to pick unique prefixes for
9449 // different instances.
9450 typedef testing::Types<char, int, unsigned int> MyTypes;
9451 INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
9452 
9453 // If the type list contains only one type, you can write that type
9454 // directly without Types<...>:
9455 // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
9456 //
9457 // Similar to the optional argument of TYPED_TEST_SUITE above,
9458 // INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to
9459 // generate custom names.
9460 // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);
9461 
9462 #endif // 0
9463 
9464 
9465 // Implements typed tests.
9466 
9467 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9468 //
9469 // Expands to the name of the typedef for the type parameters of the
9470 // given test suite.
9471 #define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_
9472 
9473 // Expands to the name of the typedef for the NameGenerator, responsible for
9474 // creating the suffixes of the name.
9475 #define GTEST_NAME_GENERATOR_(TestSuiteName) \
9476  gtest_type_params_##TestSuiteName##_NameGenerator
9477 
9478 #define TYPED_TEST_SUITE(CaseName, Types, ...) \
9479  typedef ::testing::internal::GenerateTypeList<Types>::type \
9480  GTEST_TYPE_PARAMS_(CaseName); \
9481  typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
9482  GTEST_NAME_GENERATOR_(CaseName)
9483 
9484 #define TYPED_TEST(CaseName, TestName) \
9485  static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \
9486  "test-name must not be empty"); \
9487  template <typename gtest_TypeParam_> \
9488  class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
9489  : public CaseName<gtest_TypeParam_> { \
9490  private: \
9491  typedef CaseName<gtest_TypeParam_> TestFixture; \
9492  typedef gtest_TypeParam_ TypeParam; \
9493  void TestBody() override; \
9494  }; \
9495  static bool gtest_##CaseName##_##TestName##_registered_ \
9496  GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \
9497  CaseName, \
9498  ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
9499  TestName)>, \
9500  GTEST_TYPE_PARAMS_( \
9501  CaseName)>::Register("", \
9502  ::testing::internal::CodeLocation( \
9503  __FILE__, __LINE__), \
9504  GTEST_STRINGIFY_(CaseName), \
9505  GTEST_STRINGIFY_(TestName), 0, \
9506  ::testing::internal::GenerateNames< \
9507  GTEST_NAME_GENERATOR_(CaseName), \
9508  GTEST_TYPE_PARAMS_(CaseName)>()); \
9509  template <typename gtest_TypeParam_> \
9510  void GTEST_TEST_CLASS_NAME_(CaseName, \
9511  TestName)<gtest_TypeParam_>::TestBody()
9512 
9513 // Legacy API is deprecated but still available
9514 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9515 #define TYPED_TEST_CASE \
9516  static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \
9517  TYPED_TEST_SUITE
9518 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9519 
9520 // Implements type-parameterized tests.
9521 
9522 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9523 //
9524 // Expands to the namespace name that the type-parameterized tests for
9525 // the given type-parameterized test suite are defined in. The exact
9526 // name of the namespace is subject to change without notice.
9527 #define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_
9528 
9529 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
9530 //
9531 // Expands to the name of the variable used to remember the names of
9532 // the defined tests in the given test suite.
9533 #define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \
9534  gtest_typed_test_suite_p_state_##TestSuiteName##_
9535 
9536 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
9537 //
9538 // Expands to the name of the variable used to remember the names of
9539 // the registered tests in the given test suite.
9540 #define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \
9541  gtest_registered_test_names_##TestSuiteName##_
9542 
9543 // The variables defined in the type-parameterized test macros are
9544 // static as typically these macros are used in a .h file that can be
9545 // #included in multiple translation units linked together.
9546 #define TYPED_TEST_SUITE_P(SuiteName) \
9547  static ::testing::internal::TypedTestSuitePState \
9548  GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
9549 
9550 // Legacy API is deprecated but still available
9551 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9552 #define TYPED_TEST_CASE_P \
9553  static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \
9554  TYPED_TEST_SUITE_P
9555 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9556 
9557 #define TYPED_TEST_P(SuiteName, TestName) \
9558  namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
9559  template <typename gtest_TypeParam_> \
9560  class TestName : public SuiteName<gtest_TypeParam_> { \
9561  private: \
9562  typedef SuiteName<gtest_TypeParam_> TestFixture; \
9563  typedef gtest_TypeParam_ TypeParam; \
9564  void TestBody() override; \
9565  }; \
9566  static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
9567  GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
9568  __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
9569  GTEST_STRINGIFY_(TestName)); \
9570  } \
9571  template <typename gtest_TypeParam_> \
9572  void GTEST_SUITE_NAMESPACE_( \
9573  SuiteName)::TestName<gtest_TypeParam_>::TestBody()
9574 
9575 // Note: this won't work correctly if the trailing arguments are macros.
9576 #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
9577  namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
9578  typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
9579  } \
9580  static const char* const GTEST_REGISTERED_TEST_NAMES_( \
9581  SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
9582  GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
9583  GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
9584 
9585 // Legacy API is deprecated but still available
9586 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9587 #define REGISTER_TYPED_TEST_CASE_P \
9588  static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \
9589  ""); \
9590  REGISTER_TYPED_TEST_SUITE_P
9591 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9592 
9593 #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
9594  static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \
9595  "test-suit-prefix must not be empty"); \
9596  static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
9597  ::testing::internal::TypeParameterizedTestSuite< \
9598  SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
9599  ::testing::internal::GenerateTypeList<Types>::type>:: \
9600  Register(GTEST_STRINGIFY_(Prefix), \
9601  ::testing::internal::CodeLocation(__FILE__, __LINE__), \
9602  &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \
9603  GTEST_STRINGIFY_(SuiteName), \
9604  GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
9605  ::testing::internal::GenerateNames< \
9606  ::testing::internal::NameGeneratorSelector< \
9607  __VA_ARGS__>::type, \
9608  ::testing::internal::GenerateTypeList<Types>::type>())
9609 
9610 // Legacy API is deprecated but still available
9611 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9612 #define INSTANTIATE_TYPED_TEST_CASE_P \
9613  static_assert( \
9614  ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \
9615  INSTANTIATE_TYPED_TEST_SUITE_P
9616 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9617 
9618 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
9619 
9620 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
9621 /* class A needs to have dll-interface to be used by clients of class B */)
9622 
9623 namespace testing {
9624 
9625 // Silence C4100 (unreferenced formal parameter) and 4805
9626 // unsafe mix of type 'const int' and type 'const bool'
9627 #ifdef _MSC_VER
9628 # pragma warning(push)
9629 # pragma warning(disable:4805)
9630 # pragma warning(disable:4100)
9631 #endif
9632 
9633 
9634 // Declares the flags.
9635 
9636 // This flag temporary enables the disabled tests.
9637 GTEST_DECLARE_bool_(also_run_disabled_tests);
9638 
9639 // This flag brings the debugger on an assertion failure.
9640 GTEST_DECLARE_bool_(break_on_failure);
9641 
9642 // This flag controls whether Google Test catches all test-thrown exceptions
9643 // and logs them as failures.
9644 GTEST_DECLARE_bool_(catch_exceptions);
9645 
9646 // This flag enables using colors in terminal output. Available values are
9647 // "yes" to enable colors, "no" (disable colors), or "auto" (the default)
9648 // to let Google Test decide.
9649 GTEST_DECLARE_string_(color);
9650 
9651 // This flag controls whether the test runner should continue execution past
9652 // first failure.
9653 GTEST_DECLARE_bool_(fail_fast);
9654 
9655 // This flag sets up the filter to select by name using a glob pattern
9656 // the tests to run. If the filter is not given all tests are executed.
9657 GTEST_DECLARE_string_(filter);
9658 
9659 // This flag controls whether Google Test installs a signal handler that dumps
9660 // debugging information when fatal signals are raised.
9661 GTEST_DECLARE_bool_(install_failure_signal_handler);
9662 
9663 // This flag causes the Google Test to list tests. None of the tests listed
9664 // are actually run if the flag is provided.
9665 GTEST_DECLARE_bool_(list_tests);
9666 
9667 // This flag controls whether Google Test emits a detailed XML report to a file
9668 // in addition to its normal textual output.
9669 GTEST_DECLARE_string_(output);
9670 
9671 // This flags control whether Google Test prints only test failures.
9672 GTEST_DECLARE_bool_(brief);
9673 
9674 // This flags control whether Google Test prints the elapsed time for each
9675 // test.
9676 GTEST_DECLARE_bool_(print_time);
9677 
9678 // This flags control whether Google Test prints UTF8 characters as text.
9679 GTEST_DECLARE_bool_(print_utf8);
9680 
9681 // This flag specifies the random number seed.
9682 GTEST_DECLARE_int32_(random_seed);
9683 
9684 // This flag sets how many times the tests are repeated. The default value
9685 // is 1. If the value is -1 the tests are repeating forever.
9686 GTEST_DECLARE_int32_(repeat);
9687 
9688 // This flag controls whether Google Test includes Google Test internal
9689 // stack frames in failure stack traces.
9690 GTEST_DECLARE_bool_(show_internal_stack_frames);
9691 
9692 // When this flag is specified, tests' order is randomized on every iteration.
9693 GTEST_DECLARE_bool_(shuffle);
9694 
9695 // This flag specifies the maximum number of stack frames to be
9696 // printed in a failure message.
9697 GTEST_DECLARE_int32_(stack_trace_depth);
9698 
9699 // When this flag is specified, a failed assertion will throw an
9700 // exception if exceptions are enabled, or exit the program with a
9701 // non-zero code otherwise. For use with an external test framework.
9702 GTEST_DECLARE_bool_(throw_on_failure);
9703 
9704 // When this flag is set with a "host:port" string, on supported
9705 // platforms test results are streamed to the specified port on
9706 // the specified host machine.
9707 GTEST_DECLARE_string_(stream_result_to);
9708 
9709 #if GTEST_USE_OWN_FLAGFILE_FLAG_
9710 GTEST_DECLARE_string_(flagfile);
9711 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
9712 
9713 // The upper limit for valid stack trace depths.
9714 const int kMaxStackTraceDepth = 100;
9715 
9716 namespace internal {
9717 
9718 class AssertHelper;
9719 class DefaultGlobalTestPartResultReporter;
9720 class ExecDeathTest;
9721 class NoExecDeathTest;
9722 class FinalSuccessChecker;
9723 class GTestFlagSaver;
9724 class StreamingListenerTest;
9725 class TestResultAccessor;
9726 class TestEventListenersAccessor;
9727 class TestEventRepeater;
9728 class UnitTestRecordPropertyTestHelper;
9729 class WindowsDeathTest;
9730 class FuchsiaDeathTest;
9731 class UnitTestImpl* GetUnitTestImpl();
9732 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
9733  const std::string& message);
9734 std::set<std::string>* GetIgnoredParameterizedTestSuites();
9735 
9736 } // namespace internal
9737 
9738 // The friend relationship of some of these classes is cyclic.
9739 // If we don't forward declare them the compiler might confuse the classes
9740 // in friendship clauses with same named classes on the scope.
9741 class Test;
9742 class TestSuite;
9743 
9744 // Old API is still available but deprecated
9745 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
9746 using TestCase = TestSuite;
9747 #endif
9748 class TestInfo;
9749 class UnitTest;
9750 
9751 // A class for indicating whether an assertion was successful. When
9752 // the assertion wasn't successful, the AssertionResult object
9753 // remembers a non-empty message that describes how it failed.
9754 //
9755 // To create an instance of this class, use one of the factory functions
9756 // (AssertionSuccess() and AssertionFailure()).
9757 //
9758 // This class is useful for two purposes:
9759 // 1. Defining predicate functions to be used with Boolean test assertions
9760 // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
9761 // 2. Defining predicate-format functions to be
9762 // used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
9763 //
9764 // For example, if you define IsEven predicate:
9765 //
9766 // testing::AssertionResult IsEven(int n) {
9767 // if ((n % 2) == 0)
9768 // return testing::AssertionSuccess();
9769 // else
9770 // return testing::AssertionFailure() << n << " is odd";
9771 // }
9772 //
9773 // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
9774 // will print the message
9775 //
9776 // Value of: IsEven(Fib(5))
9777 // Actual: false (5 is odd)
9778 // Expected: true
9779 //
9780 // instead of a more opaque
9781 //
9782 // Value of: IsEven(Fib(5))
9783 // Actual: false
9784 // Expected: true
9785 //
9786 // in case IsEven is a simple Boolean predicate.
9787 //
9788 // If you expect your predicate to be reused and want to support informative
9789 // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
9790 // about half as often as positive ones in our tests), supply messages for
9791 // both success and failure cases:
9792 //
9793 // testing::AssertionResult IsEven(int n) {
9794 // if ((n % 2) == 0)
9795 // return testing::AssertionSuccess() << n << " is even";
9796 // else
9797 // return testing::AssertionFailure() << n << " is odd";
9798 // }
9799 //
9800 // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
9801 //
9802 // Value of: IsEven(Fib(6))
9803 // Actual: true (8 is even)
9804 // Expected: false
9805 //
9806 // NB: Predicates that support negative Boolean assertions have reduced
9807 // performance in positive ones so be careful not to use them in tests
9808 // that have lots (tens of thousands) of positive Boolean assertions.
9809 //
9810 // To use this class with EXPECT_PRED_FORMAT assertions such as:
9811 //
9812 // // Verifies that Foo() returns an even number.
9813 // EXPECT_PRED_FORMAT1(IsEven, Foo());
9814 //
9815 // you need to define:
9816 //
9817 // testing::AssertionResult IsEven(const char* expr, int n) {
9818 // if ((n % 2) == 0)
9819 // return testing::AssertionSuccess();
9820 // else
9821 // return testing::AssertionFailure()
9822 // << "Expected: " << expr << " is even\n Actual: it's " << n;
9823 // }
9824 //
9825 // If Foo() returns 5, you will see the following message:
9826 //
9827 // Expected: Foo() is even
9828 // Actual: it's 5
9829 //
9830 class GTEST_API_ AssertionResult {
9831  public:
9832  // Copy constructor.
9833  // Used in EXPECT_TRUE/FALSE(assertion_result).
9834  AssertionResult(const AssertionResult& other);
9835 
9836 // C4800 is a level 3 warning in Visual Studio 2015 and earlier.
9837 // This warning is not emitted in Visual Studio 2017.
9838 // This warning is off by default starting in Visual Studio 2019 but can be
9839 // enabled with command-line options.
9840 #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
9841  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
9842 #endif
9843 
9844  // Used in the EXPECT_TRUE/FALSE(bool_expression).
9845  //
9846  // T must be contextually convertible to bool.
9847  //
9848  // The second parameter prevents this overload from being considered if
9849  // the argument is implicitly convertible to AssertionResult. In that case
9850  // we want AssertionResult's copy constructor to be used.
9851  template <typename T>
9852  explicit AssertionResult(
9853  const T& success,
9854  typename std::enable_if<
9855  !std::is_convertible<T, AssertionResult>::value>::type*
9856  /*enabler*/
9857  = nullptr)
9858  : success_(success) {}
9859 
9860 #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
9861  GTEST_DISABLE_MSC_WARNINGS_POP_()
9862 #endif
9863 
9864  // Assignment operator.
9865  AssertionResult& operator=(AssertionResult other) {
9866  swap(other);
9867  return *this;
9868  }
9869 
9870  // Returns true if and only if the assertion succeeded.
9871  operator bool() const { return success_; } // NOLINT
9872 
9873  // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
9874  AssertionResult operator!() const;
9875 
9876  // Returns the text streamed into this AssertionResult. Test assertions
9877  // use it when they fail (i.e., the predicate's outcome doesn't match the
9878  // assertion's expectation). When nothing has been streamed into the
9879  // object, returns an empty string.
9880  const char* message() const {
9881  return message_.get() != nullptr ? message_->c_str() : "";
9882  }
9883  // Deprecated; please use message() instead.
9884  const char* failure_message() const { return message(); }
9885 
9886  // Streams a custom failure message into this object.
9887  template <typename T> AssertionResult& operator<<(const T& value) {
9888  AppendMessage(Message() << value);
9889  return *this;
9890  }
9891 
9892  // Allows streaming basic output manipulators such as endl or flush into
9893  // this object.
9894  AssertionResult& operator<<(
9895  ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
9896  AppendMessage(Message() << basic_manipulator);
9897  return *this;
9898  }
9899 
9900  private:
9901  // Appends the contents of message to message_.
9902  void AppendMessage(const Message& a_message) {
9903  if (message_.get() == nullptr) message_.reset(new ::std::string);
9904  message_->append(a_message.GetString().c_str());
9905  }
9906 
9907  // Swap the contents of this AssertionResult with other.
9908  void swap(AssertionResult& other);
9909 
9910  // Stores result of the assertion predicate.
9911  bool success_;
9912  // Stores the message describing the condition in case the expectation
9913  // construct is not satisfied with the predicate's outcome.
9914  // Referenced via a pointer to avoid taking too much stack frame space
9915  // with test assertions.
9916  std::unique_ptr< ::std::string> message_;
9917 };
9918 
9919 // Makes a successful assertion result.
9920 GTEST_API_ AssertionResult AssertionSuccess();
9921 
9922 // Makes a failed assertion result.
9923 GTEST_API_ AssertionResult AssertionFailure();
9924 
9925 // Makes a failed assertion result with the given failure message.
9926 // Deprecated; use AssertionFailure() << msg.
9927 GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
9928 
9929 } // namespace testing
9930 
9931 // Includes the auto-generated header that implements a family of generic
9932 // predicate assertion macros. This include comes late because it relies on
9933 // APIs declared above.
9934 // Copyright 2006, Google Inc.
9935 // All rights reserved.
9936 //
9937 // Redistribution and use in source and binary forms, with or without
9938 // modification, are permitted provided that the following conditions are
9939 // met:
9940 //
9941 // * Redistributions of source code must retain the above copyright
9942 // notice, this list of conditions and the following disclaimer.
9943 // * Redistributions in binary form must reproduce the above
9944 // copyright notice, this list of conditions and the following disclaimer
9945 // in the documentation and/or other materials provided with the
9946 // distribution.
9947 // * Neither the name of Google Inc. nor the names of its
9948 // contributors may be used to endorse or promote products derived from
9949 // this software without specific prior written permission.
9950 //
9951 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9952 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9953 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9954 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9955 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9956 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9957 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9958 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9959 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9960 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9961 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9962 
9963 // This file is AUTOMATICALLY GENERATED on 01/02/2019 by command
9964 // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
9965 //
9966 // Implements a family of generic predicate assertion macros.
9967 // GOOGLETEST_CM0001 DO NOT DELETE
9968 
9969 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
9970 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
9971 
9972 
9973 namespace testing {
9974 
9975 // This header implements a family of generic predicate assertion
9976 // macros:
9977 //
9978 // ASSERT_PRED_FORMAT1(pred_format, v1)
9979 // ASSERT_PRED_FORMAT2(pred_format, v1, v2)
9980 // ...
9981 //
9982 // where pred_format is a function or functor that takes n (in the
9983 // case of ASSERT_PRED_FORMATn) values and their source expression
9984 // text, and returns a testing::AssertionResult. See the definition
9985 // of ASSERT_EQ in gtest.h for an example.
9986 //
9987 // If you don't care about formatting, you can use the more
9988 // restrictive version:
9989 //
9990 // ASSERT_PRED1(pred, v1)
9991 // ASSERT_PRED2(pred, v1, v2)
9992 // ...
9993 //
9994 // where pred is an n-ary function or functor that returns bool,
9995 // and the values v1, v2, ..., must support the << operator for
9996 // streaming to std::ostream.
9997 //
9998 // We also define the EXPECT_* variations.
9999 //
10000 // For now we only support predicates whose arity is at most 5.
10001 // Please email googletestframework@googlegroups.com if you need
10002 // support for higher arities.
10003 
10004 // GTEST_ASSERT_ is the basic statement to which all of the assertions
10005 // in this file reduce. Don't use this in your code.
10006 
10007 #define GTEST_ASSERT_(expression, on_failure) \
10008  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
10009  if (const ::testing::AssertionResult gtest_ar = (expression)) \
10010  ; \
10011  else \
10012  on_failure(gtest_ar.failure_message())
10013 
10014 
10015 // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
10016 // this in your code.
10017 template <typename Pred,
10018  typename T1>
10019 AssertionResult AssertPred1Helper(const char* pred_text,
10020  const char* e1,
10021  Pred pred,
10022  const T1& v1) {
10023  if (pred(v1)) return AssertionSuccess();
10024 
10025  return AssertionFailure()
10026  << pred_text << "(" << e1 << ") evaluates to false, where"
10027  << "\n"
10028  << e1 << " evaluates to " << ::testing::PrintToString(v1);
10029 }
10030 
10031 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
10032 // Don't use this in your code.
10033 #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
10034  GTEST_ASSERT_(pred_format(#v1, v1), \
10035  on_failure)
10036 
10037 // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
10038 // this in your code.
10039 #define GTEST_PRED1_(pred, v1, on_failure)\
10040  GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
10041  #v1, \
10042  pred, \
10043  v1), on_failure)
10044 
10045 // Unary predicate assertion macros.
10046 #define EXPECT_PRED_FORMAT1(pred_format, v1) \
10047  GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
10048 #define EXPECT_PRED1(pred, v1) \
10049  GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
10050 #define ASSERT_PRED_FORMAT1(pred_format, v1) \
10051  GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
10052 #define ASSERT_PRED1(pred, v1) \
10053  GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
10054 
10055 
10056 
10057 // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
10058 // this in your code.
10059 template <typename Pred,
10060  typename T1,
10061  typename T2>
10062 AssertionResult AssertPred2Helper(const char* pred_text,
10063  const char* e1,
10064  const char* e2,
10065  Pred pred,
10066  const T1& v1,
10067  const T2& v2) {
10068  if (pred(v1, v2)) return AssertionSuccess();
10069 
10070  return AssertionFailure()
10071  << pred_text << "(" << e1 << ", " << e2
10072  << ") evaluates to false, where"
10073  << "\n"
10074  << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10075  << e2 << " evaluates to " << ::testing::PrintToString(v2);
10076 }
10077 
10078 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
10079 // Don't use this in your code.
10080 #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
10081  GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
10082  on_failure)
10083 
10084 // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
10085 // this in your code.
10086 #define GTEST_PRED2_(pred, v1, v2, on_failure)\
10087  GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
10088  #v1, \
10089  #v2, \
10090  pred, \
10091  v1, \
10092  v2), on_failure)
10093 
10094 // Binary predicate assertion macros.
10095 #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
10096  GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
10097 #define EXPECT_PRED2(pred, v1, v2) \
10098  GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
10099 #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
10100  GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
10101 #define ASSERT_PRED2(pred, v1, v2) \
10102  GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
10103 
10104 
10105 
10106 // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
10107 // this in your code.
10108 template <typename Pred,
10109  typename T1,
10110  typename T2,
10111  typename T3>
10112 AssertionResult AssertPred3Helper(const char* pred_text,
10113  const char* e1,
10114  const char* e2,
10115  const char* e3,
10116  Pred pred,
10117  const T1& v1,
10118  const T2& v2,
10119  const T3& v3) {
10120  if (pred(v1, v2, v3)) return AssertionSuccess();
10121 
10122  return AssertionFailure()
10123  << pred_text << "(" << e1 << ", " << e2 << ", " << e3
10124  << ") evaluates to false, where"
10125  << "\n"
10126  << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10127  << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10128  << e3 << " evaluates to " << ::testing::PrintToString(v3);
10129 }
10130 
10131 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
10132 // Don't use this in your code.
10133 #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
10134  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
10135  on_failure)
10136 
10137 // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
10138 // this in your code.
10139 #define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
10140  GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
10141  #v1, \
10142  #v2, \
10143  #v3, \
10144  pred, \
10145  v1, \
10146  v2, \
10147  v3), on_failure)
10148 
10149 // Ternary predicate assertion macros.
10150 #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
10151  GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
10152 #define EXPECT_PRED3(pred, v1, v2, v3) \
10153  GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
10154 #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
10155  GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
10156 #define ASSERT_PRED3(pred, v1, v2, v3) \
10157  GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
10158 
10159 
10160 
10161 // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
10162 // this in your code.
10163 template <typename Pred,
10164  typename T1,
10165  typename T2,
10166  typename T3,
10167  typename T4>
10168 AssertionResult AssertPred4Helper(const char* pred_text,
10169  const char* e1,
10170  const char* e2,
10171  const char* e3,
10172  const char* e4,
10173  Pred pred,
10174  const T1& v1,
10175  const T2& v2,
10176  const T3& v3,
10177  const T4& v4) {
10178  if (pred(v1, v2, v3, v4)) return AssertionSuccess();
10179 
10180  return AssertionFailure()
10181  << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
10182  << ") evaluates to false, where"
10183  << "\n"
10184  << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10185  << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10186  << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
10187  << e4 << " evaluates to " << ::testing::PrintToString(v4);
10188 }
10189 
10190 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
10191 // Don't use this in your code.
10192 #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
10193  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
10194  on_failure)
10195 
10196 // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
10197 // this in your code.
10198 #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
10199  GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
10200  #v1, \
10201  #v2, \
10202  #v3, \
10203  #v4, \
10204  pred, \
10205  v1, \
10206  v2, \
10207  v3, \
10208  v4), on_failure)
10209 
10210 // 4-ary predicate assertion macros.
10211 #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
10212  GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
10213 #define EXPECT_PRED4(pred, v1, v2, v3, v4) \
10214  GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
10215 #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
10216  GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
10217 #define ASSERT_PRED4(pred, v1, v2, v3, v4) \
10218  GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
10219 
10220 
10221 
10222 // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
10223 // this in your code.
10224 template <typename Pred,
10225  typename T1,
10226  typename T2,
10227  typename T3,
10228  typename T4,
10229  typename T5>
10230 AssertionResult AssertPred5Helper(const char* pred_text,
10231  const char* e1,
10232  const char* e2,
10233  const char* e3,
10234  const char* e4,
10235  const char* e5,
10236  Pred pred,
10237  const T1& v1,
10238  const T2& v2,
10239  const T3& v3,
10240  const T4& v4,
10241  const T5& v5) {
10242  if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
10243 
10244  return AssertionFailure()
10245  << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
10246  << ", " << e5 << ") evaluates to false, where"
10247  << "\n"
10248  << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
10249  << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
10250  << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
10251  << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n"
10252  << e5 << " evaluates to " << ::testing::PrintToString(v5);
10253 }
10254 
10255 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
10256 // Don't use this in your code.
10257 #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
10258  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
10259  on_failure)
10260 
10261 // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
10262 // this in your code.
10263 #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
10264  GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
10265  #v1, \
10266  #v2, \
10267  #v3, \
10268  #v4, \
10269  #v5, \
10270  pred, \
10271  v1, \
10272  v2, \
10273  v3, \
10274  v4, \
10275  v5), on_failure)
10276 
10277 // 5-ary predicate assertion macros.
10278 #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
10279  GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
10280 #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
10281  GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
10282 #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
10283  GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
10284 #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
10285  GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
10286 
10287 
10288 
10289 } // namespace testing
10290 
10291 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
10292 
10293 namespace testing {
10294 
10295 // The abstract class that all tests inherit from.
10296 //
10297 // In Google Test, a unit test program contains one or many TestSuites, and
10298 // each TestSuite contains one or many Tests.
10299 //
10300 // When you define a test using the TEST macro, you don't need to
10301 // explicitly derive from Test - the TEST macro automatically does
10302 // this for you.
10303 //
10304 // The only time you derive from Test is when defining a test fixture
10305 // to be used in a TEST_F. For example:
10306 //
10307 // class FooTest : public testing::Test {
10308 // protected:
10309 // void SetUp() override { ... }
10310 // void TearDown() override { ... }
10311 // ...
10312 // };
10313 //
10314 // TEST_F(FooTest, Bar) { ... }
10315 // TEST_F(FooTest, Baz) { ... }
10316 //
10317 // Test is not copyable.
10318 class GTEST_API_ Test {
10319  public:
10320  friend class TestInfo;
10321 
10322  // The d'tor is virtual as we intend to inherit from Test.
10323  virtual ~Test();
10324 
10325  // Sets up the stuff shared by all tests in this test suite.
10326  //
10327  // Google Test will call Foo::SetUpTestSuite() before running the first
10328  // test in test suite Foo. Hence a sub-class can define its own
10329  // SetUpTestSuite() method to shadow the one defined in the super
10330  // class.
10331  static void SetUpTestSuite() {}
10332 
10333  // Tears down the stuff shared by all tests in this test suite.
10334  //
10335  // Google Test will call Foo::TearDownTestSuite() after running the last
10336  // test in test suite Foo. Hence a sub-class can define its own
10337  // TearDownTestSuite() method to shadow the one defined in the super
10338  // class.
10339  static void TearDownTestSuite() {}
10340 
10341  // Legacy API is deprecated but still available. Use SetUpTestSuite and
10342  // TearDownTestSuite instead.
10343 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10344  static void TearDownTestCase() {}
10345  static void SetUpTestCase() {}
10346 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10347 
10348  // Returns true if and only if the current test has a fatal failure.
10349  static bool HasFatalFailure();
10350 
10351  // Returns true if and only if the current test has a non-fatal failure.
10352  static bool HasNonfatalFailure();
10353 
10354  // Returns true if and only if the current test was skipped.
10355  static bool IsSkipped();
10356 
10357  // Returns true if and only if the current test has a (either fatal or
10358  // non-fatal) failure.
10359  static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
10360 
10361  // Logs a property for the current test, test suite, or for the entire
10362  // invocation of the test program when used outside of the context of a
10363  // test suite. Only the last value for a given key is remembered. These
10364  // are public static so they can be called from utility functions that are
10365  // not members of the test fixture. Calls to RecordProperty made during
10366  // lifespan of the test (from the moment its constructor starts to the
10367  // moment its destructor finishes) will be output in XML as attributes of
10368  // the <testcase> element. Properties recorded from fixture's
10369  // SetUpTestSuite or TearDownTestSuite are logged as attributes of the
10370  // corresponding <testsuite> element. Calls to RecordProperty made in the
10371  // global context (before or after invocation of RUN_ALL_TESTS and from
10372  // SetUp/TearDown method of Environment objects registered with Google
10373  // Test) will be output as attributes of the <testsuites> element.
10374  static void RecordProperty(const std::string& key, const std::string& value);
10375  static void RecordProperty(const std::string& key, int value);
10376 
10377  protected:
10378  // Creates a Test object.
10379  Test();
10380 
10381  // Sets up the test fixture.
10382  virtual void SetUp();
10383 
10384  // Tears down the test fixture.
10385  virtual void TearDown();
10386 
10387  private:
10388  // Returns true if and only if the current test has the same fixture class
10389  // as the first test in the current test suite.
10390  static bool HasSameFixtureClass();
10391 
10392  // Runs the test after the test fixture has been set up.
10393  //
10394  // A sub-class must implement this to define the test logic.
10395  //
10396  // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
10397  // Instead, use the TEST or TEST_F macro.
10398  virtual void TestBody() = 0;
10399 
10400  // Sets up, executes, and tears down the test.
10401  void Run();
10402 
10403  // Deletes self. We deliberately pick an unusual name for this
10404  // internal method to avoid clashing with names used in user TESTs.
10405  void DeleteSelf_() { delete this; }
10406 
10407  const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;
10408 
10409  // Often a user misspells SetUp() as Setup() and spends a long time
10410  // wondering why it is never called by Google Test. The declaration of
10411  // the following method is solely for catching such an error at
10412  // compile time:
10413  //
10414  // - The return type is deliberately chosen to be not void, so it
10415  // will be a conflict if void Setup() is declared in the user's
10416  // test fixture.
10417  //
10418  // - This method is private, so it will be another compiler error
10419  // if the method is called from the user's test fixture.
10420  //
10421  // DO NOT OVERRIDE THIS FUNCTION.
10422  //
10423  // If you see an error about overriding the following function or
10424  // about it being private, you have mis-spelled SetUp() as Setup().
10425  struct Setup_should_be_spelled_SetUp {};
10426  virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
10427 
10428  // We disallow copying Tests.
10429  GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
10430 };
10431 
10432 typedef internal::TimeInMillis TimeInMillis;
10433 
10434 // A copyable object representing a user specified test property which can be
10435 // output as a key/value string pair.
10436 //
10437 // Don't inherit from TestProperty as its destructor is not virtual.
10438 class TestProperty {
10439  public:
10440  // C'tor. TestProperty does NOT have a default constructor.
10441  // Always use this constructor (with parameters) to create a
10442  // TestProperty object.
10443  TestProperty(const std::string& a_key, const std::string& a_value) :
10444  key_(a_key), value_(a_value) {
10445  }
10446 
10447  // Gets the user supplied key.
10448  const char* key() const {
10449  return key_.c_str();
10450  }
10451 
10452  // Gets the user supplied value.
10453  const char* value() const {
10454  return value_.c_str();
10455  }
10456 
10457  // Sets a new value, overriding the one supplied in the constructor.
10458  void SetValue(const std::string& new_value) {
10459  value_ = new_value;
10460  }
10461 
10462  private:
10463  // The key supplied by the user.
10464  std::string key_;
10465  // The value supplied by the user.
10466  std::string value_;
10467 };
10468 
10469 // The result of a single Test. This includes a list of
10470 // TestPartResults, a list of TestProperties, a count of how many
10471 // death tests there are in the Test, and how much time it took to run
10472 // the Test.
10473 //
10474 // TestResult is not copyable.
10475 class GTEST_API_ TestResult {
10476  public:
10477  // Creates an empty TestResult.
10478  TestResult();
10479 
10480  // D'tor. Do not inherit from TestResult.
10481  ~TestResult();
10482 
10483  // Gets the number of all test parts. This is the sum of the number
10484  // of successful test parts and the number of failed test parts.
10485  int total_part_count() const;
10486 
10487  // Returns the number of the test properties.
10488  int test_property_count() const;
10489 
10490  // Returns true if and only if the test passed (i.e. no test part failed).
10491  bool Passed() const { return !Skipped() && !Failed(); }
10492 
10493  // Returns true if and only if the test was skipped.
10494  bool Skipped() const;
10495 
10496  // Returns true if and only if the test failed.
10497  bool Failed() const;
10498 
10499  // Returns true if and only if the test fatally failed.
10500  bool HasFatalFailure() const;
10501 
10502  // Returns true if and only if the test has a non-fatal failure.
10503  bool HasNonfatalFailure() const;
10504 
10505  // Returns the elapsed time, in milliseconds.
10506  TimeInMillis elapsed_time() const { return elapsed_time_; }
10507 
10508  // Gets the time of the test case start, in ms from the start of the
10509  // UNIX epoch.
10510  TimeInMillis start_timestamp() const { return start_timestamp_; }
10511 
10512  // Returns the i-th test part result among all the results. i can range from 0
10513  // to total_part_count() - 1. If i is not in that range, aborts the program.
10514  const TestPartResult& GetTestPartResult(int i) const;
10515 
10516  // Returns the i-th test property. i can range from 0 to
10517  // test_property_count() - 1. If i is not in that range, aborts the
10518  // program.
10519  const TestProperty& GetTestProperty(int i) const;
10520 
10521  private:
10522  friend class TestInfo;
10523  friend class TestSuite;
10524  friend class UnitTest;
10525  friend class internal::DefaultGlobalTestPartResultReporter;
10526  friend class internal::ExecDeathTest;
10527  friend class internal::TestResultAccessor;
10528  friend class internal::UnitTestImpl;
10529  friend class internal::WindowsDeathTest;
10530  friend class internal::FuchsiaDeathTest;
10531 
10532  // Gets the vector of TestPartResults.
10533  const std::vector<TestPartResult>& test_part_results() const {
10534  return test_part_results_;
10535  }
10536 
10537  // Gets the vector of TestProperties.
10538  const std::vector<TestProperty>& test_properties() const {
10539  return test_properties_;
10540  }
10541 
10542  // Sets the start time.
10543  void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }
10544 
10545  // Sets the elapsed time.
10546  void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
10547 
10548  // Adds a test property to the list. The property is validated and may add
10549  // a non-fatal failure if invalid (e.g., if it conflicts with reserved
10550  // key names). If a property is already recorded for the same key, the
10551  // value will be updated, rather than storing multiple values for the same
10552  // key. xml_element specifies the element for which the property is being
10553  // recorded and is used for validation.
10554  void RecordProperty(const std::string& xml_element,
10555  const TestProperty& test_property);
10556 
10557  // Adds a failure if the key is a reserved attribute of Google Test
10558  // testsuite tags. Returns true if the property is valid.
10559  // FIXME: Validate attribute names are legal and human readable.
10560  static bool ValidateTestProperty(const std::string& xml_element,
10561  const TestProperty& test_property);
10562 
10563  // Adds a test part result to the list.
10564  void AddTestPartResult(const TestPartResult& test_part_result);
10565 
10566  // Returns the death test count.
10567  int death_test_count() const { return death_test_count_; }
10568 
10569  // Increments the death test count, returning the new count.
10570  int increment_death_test_count() { return ++death_test_count_; }
10571 
10572  // Clears the test part results.
10573  void ClearTestPartResults();
10574 
10575  // Clears the object.
10576  void Clear();
10577 
10578  // Protects mutable state of the property vector and of owned
10579  // properties, whose values may be updated.
10580  internal::Mutex test_properties_mutex_;
10581 
10582  // The vector of TestPartResults
10583  std::vector<TestPartResult> test_part_results_;
10584  // The vector of TestProperties
10585  std::vector<TestProperty> test_properties_;
10586  // Running count of death tests.
10587  int death_test_count_;
10588  // The start time, in milliseconds since UNIX Epoch.
10589  TimeInMillis start_timestamp_;
10590  // The elapsed time, in milliseconds.
10591  TimeInMillis elapsed_time_;
10592 
10593  // We disallow copying TestResult.
10594  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
10595 }; // class TestResult
10596 
10597 // A TestInfo object stores the following information about a test:
10598 //
10599 // Test suite name
10600 // Test name
10601 // Whether the test should be run
10602 // A function pointer that creates the test object when invoked
10603 // Test result
10604 //
10605 // The constructor of TestInfo registers itself with the UnitTest
10606 // singleton such that the RUN_ALL_TESTS() macro knows which tests to
10607 // run.
10608 class GTEST_API_ TestInfo {
10609  public:
10610  // Destructs a TestInfo object. This function is not virtual, so
10611  // don't inherit from TestInfo.
10612  ~TestInfo();
10613 
10614  // Returns the test suite name.
10615  const char* test_suite_name() const { return test_suite_name_.c_str(); }
10616 
10617 // Legacy API is deprecated but still available
10618 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10619  const char* test_case_name() const { return test_suite_name(); }
10620 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
10621 
10622  // Returns the test name.
10623  const char* name() const { return name_.c_str(); }
10624 
10625  // Returns the name of the parameter type, or NULL if this is not a typed
10626  // or a type-parameterized test.
10627  const char* type_param() const {
10628  if (type_param_.get() != nullptr) return type_param_->c_str();
10629  return nullptr;
10630  }
10631 
10632  // Returns the text representation of the value parameter, or NULL if this
10633  // is not a value-parameterized test.
10634  const char* value_param() const {
10635  if (value_param_.get() != nullptr) return value_param_->c_str();
10636  return nullptr;
10637  }
10638 
10639  // Returns the file name where this test is defined.
10640  const char* file() const { return location_.file.c_str(); }
10641 
10642  // Returns the line where this test is defined.
10643  int line() const { return location_.line; }
10644 
10645  // Return true if this test should not be run because it's in another shard.
10646  bool is_in_another_shard() const { return is_in_another_shard_; }
10647 
10648  // Returns true if this test should run, that is if the test is not
10649  // disabled (or it is disabled but the also_run_disabled_tests flag has
10650  // been specified) and its full name matches the user-specified filter.
10651  //
10652  // Google Test allows the user to filter the tests by their full names.
10653  // The full name of a test Bar in test suite Foo is defined as
10654  // "Foo.Bar". Only the tests that match the filter will run.
10655  //
10656  // A filter is a colon-separated list of glob (not regex) patterns,
10657  // optionally followed by a '-' and a colon-separated list of
10658  // negative patterns (tests to exclude). A test is run if it
10659  // matches one of the positive patterns and does not match any of
10660  // the negative patterns.
10661  //
10662  // For example, *A*:Foo.* is a filter that matches any string that
10663  // contains the character 'A' or starts with "Foo.".
10664  bool should_run() const { return should_run_; }
10665 
10666  // Returns true if and only if this test will appear in the XML report.
10667  bool is_reportable() const {
10668  // The XML report includes tests matching the filter, excluding those
10669  // run in other shards.
10670  return matches_filter_ && !is_in_another_shard_;
10671  }
10672 
10673  // Returns the result of the test.
10674  const TestResult* result() const { return &result_; }
10675 
10676  private:
10677 #if GTEST_HAS_DEATH_TEST
10678  friend class internal::DefaultDeathTestFactory;
10679 #endif // GTEST_HAS_DEATH_TEST
10680  friend class Test;
10681  friend class TestSuite;
10682  friend class internal::UnitTestImpl;
10683  friend class internal::StreamingListenerTest;
10684  friend TestInfo* internal::MakeAndRegisterTestInfo(
10685  const char* test_suite_name, const char* name, const char* type_param,
10686  const char* value_param, internal::CodeLocation code_location,
10687  internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
10688  internal::TearDownTestSuiteFunc tear_down_tc,
10689  internal::TestFactoryBase* factory);
10690 
10691  // Constructs a TestInfo object. The newly constructed instance assumes
10692  // ownership of the factory object.
10693  TestInfo(const std::string& test_suite_name, const std::string& name,
10694  const char* a_type_param, // NULL if not a type-parameterized test
10695  const char* a_value_param, // NULL if not a value-parameterized test
10696  internal::CodeLocation a_code_location,
10697  internal::TypeId fixture_class_id,
10698  internal::TestFactoryBase* factory);
10699 
10700  // Increments the number of death tests encountered in this test so
10701  // far.
10702  int increment_death_test_count() {
10703  return result_.increment_death_test_count();
10704  }
10705 
10706  // Creates the test object, runs it, records its result, and then
10707  // deletes it.
10708  void Run();
10709 
10710  // Skip and records the test result for this object.
10711  void Skip();
10712 
10713  static void ClearTestResult(TestInfo* test_info) {
10714  test_info->result_.Clear();
10715  }
10716 
10717  // These fields are immutable properties of the test.
10718  const std::string test_suite_name_; // test suite name
10719  const std::string name_; // Test name
10720  // Name of the parameter type, or NULL if this is not a typed or a
10721  // type-parameterized test.
10722  const std::unique_ptr<const ::std::string> type_param_;
10723  // Text representation of the value parameter, or NULL if this is not a
10724  // value-parameterized test.
10725  const std::unique_ptr<const ::std::string> value_param_;
10726  internal::CodeLocation location_;
10727  const internal::TypeId fixture_class_id_; // ID of the test fixture class
10728  bool should_run_; // True if and only if this test should run
10729  bool is_disabled_; // True if and only if this test is disabled
10730  bool matches_filter_; // True if this test matches the
10731  // user-specified filter.
10732  bool is_in_another_shard_; // Will be run in another shard.
10733  internal::TestFactoryBase* const factory_; // The factory that creates
10734  // the test object
10735 
10736  // This field is mutable and needs to be reset before running the
10737  // test for the second time.
10738  TestResult result_;
10739 
10740  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
10741 };
10742 
10743 // A test suite, which consists of a vector of TestInfos.
10744 //
10745 // TestSuite is not copyable.
10746 class GTEST_API_ TestSuite {
10747  public:
10748  // Creates a TestSuite with the given name.
10749  //
10750  // TestSuite does NOT have a default constructor. Always use this
10751  // constructor to create a TestSuite object.
10752  //
10753  // Arguments:
10754  //
10755  // name: name of the test suite
10756  // a_type_param: the name of the test's type parameter, or NULL if
10757  // this is not a type-parameterized test.
10758  // set_up_tc: pointer to the function that sets up the test suite
10759  // tear_down_tc: pointer to the function that tears down the test suite
10760  TestSuite(const char* name, const char* a_type_param,
10761  internal::SetUpTestSuiteFunc set_up_tc,
10762  internal::TearDownTestSuiteFunc tear_down_tc);
10763 
10764  // Destructor of TestSuite.
10765  virtual ~TestSuite();
10766 
10767  // Gets the name of the TestSuite.
10768  const char* name() const { return name_.c_str(); }
10769 
10770  // Returns the name of the parameter type, or NULL if this is not a
10771  // type-parameterized test suite.
10772  const char* type_param() const {
10773  if (type_param_.get() != nullptr) return type_param_->c_str();
10774  return nullptr;
10775  }
10776 
10777  // Returns true if any test in this test suite should run.
10778  bool should_run() const { return should_run_; }
10779 
10780  // Gets the number of successful tests in this test suite.
10781  int successful_test_count() const;
10782 
10783  // Gets the number of skipped tests in this test suite.
10784  int skipped_test_count() const;
10785 
10786  // Gets the number of failed tests in this test suite.
10787  int failed_test_count() const;
10788 
10789  // Gets the number of disabled tests that will be reported in the XML report.
10790  int reportable_disabled_test_count() const;
10791 
10792  // Gets the number of disabled tests in this test suite.
10793  int disabled_test_count() const;
10794 
10795  // Gets the number of tests to be printed in the XML report.
10796  int reportable_test_count() const;
10797 
10798  // Get the number of tests in this test suite that should run.
10799  int test_to_run_count() const;
10800 
10801  // Gets the number of all tests in this test suite.
10802  int total_test_count() const;
10803 
10804  // Returns true if and only if the test suite passed.
10805  bool Passed() const { return !Failed(); }
10806 
10807  // Returns true if and only if the test suite failed.
10808  bool Failed() const {
10809  return failed_test_count() > 0 || ad_hoc_test_result().Failed();
10810  }
10811 
10812  // Returns the elapsed time, in milliseconds.
10813  TimeInMillis elapsed_time() const { return elapsed_time_; }
10814 
10815  // Gets the time of the test suite start, in ms from the start of the
10816  // UNIX epoch.
10817  TimeInMillis start_timestamp() const { return start_timestamp_; }
10818 
10819  // Returns the i-th test among all the tests. i can range from 0 to
10820  // total_test_count() - 1. If i is not in that range, returns NULL.
10821  const TestInfo* GetTestInfo(int i) const;
10822 
10823  // Returns the TestResult that holds test properties recorded during
10824  // execution of SetUpTestSuite and TearDownTestSuite.
10825  const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
10826 
10827  private:
10828  friend class Test;
10829  friend class internal::UnitTestImpl;
10830 
10831  // Gets the (mutable) vector of TestInfos in this TestSuite.
10832  std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
10833 
10834  // Gets the (immutable) vector of TestInfos in this TestSuite.
10835  const std::vector<TestInfo*>& test_info_list() const {
10836  return test_info_list_;
10837  }
10838 
10839  // Returns the i-th test among all the tests. i can range from 0 to
10840  // total_test_count() - 1. If i is not in that range, returns NULL.
10841  TestInfo* GetMutableTestInfo(int i);
10842 
10843  // Sets the should_run member.
10844  void set_should_run(bool should) { should_run_ = should; }
10845 
10846  // Adds a TestInfo to this test suite. Will delete the TestInfo upon
10847  // destruction of the TestSuite object.
10848  void AddTestInfo(TestInfo * test_info);
10849 
10850  // Clears the results of all tests in this test suite.
10851  void ClearResult();
10852 
10853  // Clears the results of all tests in the given test suite.
10854  static void ClearTestSuiteResult(TestSuite* test_suite) {
10855  test_suite->ClearResult();
10856  }
10857 
10858  // Runs every test in this TestSuite.
10859  void Run();
10860 
10861  // Skips the execution of tests under this TestSuite
10862  void Skip();
10863 
10864  // Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
10865  // for catching exceptions thrown from SetUpTestSuite().
10866  void RunSetUpTestSuite() {
10867  if (set_up_tc_ != nullptr) {
10868  (*set_up_tc_)();
10869  }
10870  }
10871 
10872  // Runs TearDownTestSuite() for this TestSuite. This wrapper is
10873  // needed for catching exceptions thrown from TearDownTestSuite().
10874  void RunTearDownTestSuite() {
10875  if (tear_down_tc_ != nullptr) {
10876  (*tear_down_tc_)();
10877  }
10878  }
10879 
10880  // Returns true if and only if test passed.
10881  static bool TestPassed(const TestInfo* test_info) {
10882  return test_info->should_run() && test_info->result()->Passed();
10883  }
10884 
10885  // Returns true if and only if test skipped.
10886  static bool TestSkipped(const TestInfo* test_info) {
10887  return test_info->should_run() && test_info->result()->Skipped();
10888  }
10889 
10890  // Returns true if and only if test failed.
10891  static bool TestFailed(const TestInfo* test_info) {
10892  return test_info->should_run() && test_info->result()->Failed();
10893  }
10894 
10895  // Returns true if and only if the test is disabled and will be reported in
10896  // the XML report.
10897  static bool TestReportableDisabled(const TestInfo* test_info) {
10898  return test_info->is_reportable() && test_info->is_disabled_;
10899  }
10900 
10901  // Returns true if and only if test is disabled.
10902  static bool TestDisabled(const TestInfo* test_info) {
10903  return test_info->is_disabled_;
10904  }
10905 
10906  // Returns true if and only if this test will appear in the XML report.
10907  static bool TestReportable(const TestInfo* test_info) {
10908  return test_info->is_reportable();
10909  }
10910 
10911  // Returns true if the given test should run.
10912  static bool ShouldRunTest(const TestInfo* test_info) {
10913  return test_info->should_run();
10914  }
10915 
10916  // Shuffles the tests in this test suite.
10917  void ShuffleTests(internal::Random* random);
10918 
10919  // Restores the test order to before the first shuffle.
10920  void UnshuffleTests();
10921 
10922  // Name of the test suite.
10923  std::string name_;
10924  // Name of the parameter type, or NULL if this is not a typed or a
10925  // type-parameterized test.
10926  const std::unique_ptr<const ::std::string> type_param_;
10927  // The vector of TestInfos in their original order. It owns the
10928  // elements in the vector.
10929  std::vector<TestInfo*> test_info_list_;
10930  // Provides a level of indirection for the test list to allow easy
10931  // shuffling and restoring the test order. The i-th element in this
10932  // vector is the index of the i-th test in the shuffled test list.
10933  std::vector<int> test_indices_;
10934  // Pointer to the function that sets up the test suite.
10935  internal::SetUpTestSuiteFunc set_up_tc_;
10936  // Pointer to the function that tears down the test suite.
10937  internal::TearDownTestSuiteFunc tear_down_tc_;
10938  // True if and only if any test in this test suite should run.
10939  bool should_run_;
10940  // The start time, in milliseconds since UNIX Epoch.
10941  TimeInMillis start_timestamp_;
10942  // Elapsed time, in milliseconds.
10943  TimeInMillis elapsed_time_;
10944  // Holds test properties recorded during execution of SetUpTestSuite and
10945  // TearDownTestSuite.
10946  TestResult ad_hoc_test_result_;
10947 
10948  // We disallow copying TestSuites.
10949  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite);
10950 };
10951 
10952 // An Environment object is capable of setting up and tearing down an
10953 // environment. You should subclass this to define your own
10954 // environment(s).
10955 //
10956 // An Environment object does the set-up and tear-down in virtual
10957 // methods SetUp() and TearDown() instead of the constructor and the
10958 // destructor, as:
10959 //
10960 // 1. You cannot safely throw from a destructor. This is a problem
10961 // as in some cases Google Test is used where exceptions are enabled, and
10962 // we may want to implement ASSERT_* using exceptions where they are
10963 // available.
10964 // 2. You cannot use ASSERT_* directly in a constructor or
10965 // destructor.
10966 class Environment {
10967  public:
10968  // The d'tor is virtual as we need to subclass Environment.
10969  virtual ~Environment() {}
10970 
10971  // Override this to define how to set up the environment.
10972  virtual void SetUp() {}
10973 
10974  // Override this to define how to tear down the environment.
10975  virtual void TearDown() {}
10976  private:
10977  // If you see an error about overriding the following function or
10978  // about it being private, you have mis-spelled SetUp() as Setup().
10979  struct Setup_should_be_spelled_SetUp {};
10980  virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
10981 };
10982 
10983 #if GTEST_HAS_EXCEPTIONS
10984 
10985 // Exception which can be thrown from TestEventListener::OnTestPartResult.
10986 class GTEST_API_ AssertionException
10987  : public internal::GoogleTestFailureException {
10988  public:
10989  explicit AssertionException(const TestPartResult& result)
10990  : GoogleTestFailureException(result) {}
10991 };
10992 
10993 #endif // GTEST_HAS_EXCEPTIONS
10994 
10995 // The interface for tracing execution of tests. The methods are organized in
10996 // the order the corresponding events are fired.
10997 class TestEventListener {
10998  public:
10999  virtual ~TestEventListener() {}
11000 
11001  // Fired before any test activity starts.
11002  virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
11003 
11004  // Fired before each iteration of tests starts. There may be more than
11005  // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
11006  // index, starting from 0.
11007  virtual void OnTestIterationStart(const UnitTest& unit_test,
11008  int iteration) = 0;
11009 
11010  // Fired before environment set-up for each iteration of tests starts.
11011  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
11012 
11013  // Fired after environment set-up for each iteration of tests ends.
11014  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
11015 
11016  // Fired before the test suite starts.
11017  virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}
11018 
11019  // Legacy API is deprecated but still available
11020 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11021  virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
11022 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11023 
11024  // Fired before the test starts.
11025  virtual void OnTestStart(const TestInfo& test_info) = 0;
11026 
11027  // Fired after a failed assertion or a SUCCEED() invocation.
11028  // If you want to throw an exception from this function to skip to the next
11029  // TEST, it must be AssertionException defined above, or inherited from it.
11030  virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
11031 
11032  // Fired after the test ends.
11033  virtual void OnTestEnd(const TestInfo& test_info) = 0;
11034 
11035  // Fired after the test suite ends.
11036  virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}
11037 
11038 // Legacy API is deprecated but still available
11039 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11040  virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
11041 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11042 
11043  // Fired before environment tear-down for each iteration of tests starts.
11044  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
11045 
11046  // Fired after environment tear-down for each iteration of tests ends.
11047  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
11048 
11049  // Fired after each iteration of tests finishes.
11050  virtual void OnTestIterationEnd(const UnitTest& unit_test,
11051  int iteration) = 0;
11052 
11053  // Fired after all test activities have ended.
11054  virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
11055 };
11056 
11057 // The convenience class for users who need to override just one or two
11058 // methods and are not concerned that a possible change to a signature of
11059 // the methods they override will not be caught during the build. For
11060 // comments about each method please see the definition of TestEventListener
11061 // above.
11062 class EmptyTestEventListener : public TestEventListener {
11063  public:
11064  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
11065  void OnTestIterationStart(const UnitTest& /*unit_test*/,
11066  int /*iteration*/) override {}
11067  void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
11068  void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
11069  void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
11070 // Legacy API is deprecated but still available
11071 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11072  void OnTestCaseStart(const TestCase& /*test_case*/) override {}
11073 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11074 
11075  void OnTestStart(const TestInfo& /*test_info*/) override {}
11076  void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
11077  void OnTestEnd(const TestInfo& /*test_info*/) override {}
11078  void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
11079 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11080  void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
11081 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11082 
11083  void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
11084  void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
11085  void OnTestIterationEnd(const UnitTest& /*unit_test*/,
11086  int /*iteration*/) override {}
11087  void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
11088 };
11089 
11090 // TestEventListeners lets users add listeners to track events in Google Test.
11091 class GTEST_API_ TestEventListeners {
11092  public:
11093  TestEventListeners();
11094  ~TestEventListeners();
11095 
11096  // Appends an event listener to the end of the list. Google Test assumes
11097  // the ownership of the listener (i.e. it will delete the listener when
11098  // the test program finishes).
11099  void Append(TestEventListener* listener);
11100 
11101  // Removes the given event listener from the list and returns it. It then
11102  // becomes the caller's responsibility to delete the listener. Returns
11103  // NULL if the listener is not found in the list.
11104  TestEventListener* Release(TestEventListener* listener);
11105 
11106  // Returns the standard listener responsible for the default console
11107  // output. Can be removed from the listeners list to shut down default
11108  // console output. Note that removing this object from the listener list
11109  // with Release transfers its ownership to the caller and makes this
11110  // function return NULL the next time.
11111  TestEventListener* default_result_printer() const {
11112  return default_result_printer_;
11113  }
11114 
11115  // Returns the standard listener responsible for the default XML output
11116  // controlled by the --gtest_output=xml flag. Can be removed from the
11117  // listeners list by users who want to shut down the default XML output
11118  // controlled by this flag and substitute it with custom one. Note that
11119  // removing this object from the listener list with Release transfers its
11120  // ownership to the caller and makes this function return NULL the next
11121  // time.
11122  TestEventListener* default_xml_generator() const {
11123  return default_xml_generator_;
11124  }
11125 
11126  private:
11127  friend class TestSuite;
11128  friend class TestInfo;
11129  friend class internal::DefaultGlobalTestPartResultReporter;
11130  friend class internal::NoExecDeathTest;
11131  friend class internal::TestEventListenersAccessor;
11132  friend class internal::UnitTestImpl;
11133 
11134  // Returns repeater that broadcasts the TestEventListener events to all
11135  // subscribers.
11136  TestEventListener* repeater();
11137 
11138  // Sets the default_result_printer attribute to the provided listener.
11139  // The listener is also added to the listener list and previous
11140  // default_result_printer is removed from it and deleted. The listener can
11141  // also be NULL in which case it will not be added to the list. Does
11142  // nothing if the previous and the current listener objects are the same.
11143  void SetDefaultResultPrinter(TestEventListener* listener);
11144 
11145  // Sets the default_xml_generator attribute to the provided listener. The
11146  // listener is also added to the listener list and previous
11147  // default_xml_generator is removed from it and deleted. The listener can
11148  // also be NULL in which case it will not be added to the list. Does
11149  // nothing if the previous and the current listener objects are the same.
11150  void SetDefaultXmlGenerator(TestEventListener* listener);
11151 
11152  // Controls whether events will be forwarded by the repeater to the
11153  // listeners in the list.
11154  bool EventForwardingEnabled() const;
11155  void SuppressEventForwarding();
11156 
11157  // The actual list of listeners.
11158  internal::TestEventRepeater* repeater_;
11159  // Listener responsible for the standard result output.
11160  TestEventListener* default_result_printer_;
11161  // Listener responsible for the creation of the XML output file.
11162  TestEventListener* default_xml_generator_;
11163 
11164  // We disallow copying TestEventListeners.
11165  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
11166 };
11167 
11168 // A UnitTest consists of a vector of TestSuites.
11169 //
11170 // This is a singleton class. The only instance of UnitTest is
11171 // created when UnitTest::GetInstance() is first called. This
11172 // instance is never deleted.
11173 //
11174 // UnitTest is not copyable.
11175 //
11176 // This class is thread-safe as long as the methods are called
11177 // according to their specification.
11178 class GTEST_API_ UnitTest {
11179  public:
11180  // Gets the singleton UnitTest object. The first time this method
11181  // is called, a UnitTest object is constructed and returned.
11182  // Consecutive calls will return the same object.
11183  static UnitTest* GetInstance();
11184 
11185  // Runs all tests in this UnitTest object and prints the result.
11186  // Returns 0 if successful, or 1 otherwise.
11187  //
11188  // This method can only be called from the main thread.
11189  //
11190  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11191  int Run() GTEST_MUST_USE_RESULT_;
11192 
11193  // Returns the working directory when the first TEST() or TEST_F()
11194  // was executed. The UnitTest object owns the string.
11195  const char* original_working_dir() const;
11196 
11197  // Returns the TestSuite object for the test that's currently running,
11198  // or NULL if no test is running.
11199  const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);
11200 
11201 // Legacy API is still available but deprecated
11202 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11203  const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);
11204 #endif
11205 
11206  // Returns the TestInfo object for the test that's currently running,
11207  // or NULL if no test is running.
11208  const TestInfo* current_test_info() const
11209  GTEST_LOCK_EXCLUDED_(mutex_);
11210 
11211  // Returns the random seed used at the start of the current test run.
11212  int random_seed() const;
11213 
11214  // Returns the ParameterizedTestSuiteRegistry object used to keep track of
11215  // value-parameterized tests and instantiate and register them.
11216  //
11217  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11218  internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()
11219  GTEST_LOCK_EXCLUDED_(mutex_);
11220 
11221  // Gets the number of successful test suites.
11222  int successful_test_suite_count() const;
11223 
11224  // Gets the number of failed test suites.
11225  int failed_test_suite_count() const;
11226 
11227  // Gets the number of all test suites.
11228  int total_test_suite_count() const;
11229 
11230  // Gets the number of all test suites that contain at least one test
11231  // that should run.
11232  int test_suite_to_run_count() const;
11233 
11234  // Legacy API is deprecated but still available
11235 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11236  int successful_test_case_count() const;
11237  int failed_test_case_count() const;
11238  int total_test_case_count() const;
11239  int test_case_to_run_count() const;
11240 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11241 
11242  // Gets the number of successful tests.
11243  int successful_test_count() const;
11244 
11245  // Gets the number of skipped tests.
11246  int skipped_test_count() const;
11247 
11248  // Gets the number of failed tests.
11249  int failed_test_count() const;
11250 
11251  // Gets the number of disabled tests that will be reported in the XML report.
11252  int reportable_disabled_test_count() const;
11253 
11254  // Gets the number of disabled tests.
11255  int disabled_test_count() const;
11256 
11257  // Gets the number of tests to be printed in the XML report.
11258  int reportable_test_count() const;
11259 
11260  // Gets the number of all tests.
11261  int total_test_count() const;
11262 
11263  // Gets the number of tests that should run.
11264  int test_to_run_count() const;
11265 
11266  // Gets the time of the test program start, in ms from the start of the
11267  // UNIX epoch.
11268  TimeInMillis start_timestamp() const;
11269 
11270  // Gets the elapsed time, in milliseconds.
11271  TimeInMillis elapsed_time() const;
11272 
11273  // Returns true if and only if the unit test passed (i.e. all test suites
11274  // passed).
11275  bool Passed() const;
11276 
11277  // Returns true if and only if the unit test failed (i.e. some test suite
11278  // failed or something outside of all tests failed).
11279  bool Failed() const;
11280 
11281  // Gets the i-th test suite among all the test suites. i can range from 0 to
11282  // total_test_suite_count() - 1. If i is not in that range, returns NULL.
11283  const TestSuite* GetTestSuite(int i) const;
11284 
11285 // Legacy API is deprecated but still available
11286 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11287  const TestCase* GetTestCase(int i) const;
11288 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
11289 
11290  // Returns the TestResult containing information on test failures and
11291  // properties logged outside of individual test suites.
11292  const TestResult& ad_hoc_test_result() const;
11293 
11294  // Returns the list of event listeners that can be used to track events
11295  // inside Google Test.
11296  TestEventListeners& listeners();
11297 
11298  private:
11299  // Registers and returns a global test environment. When a test
11300  // program is run, all global test environments will be set-up in
11301  // the order they were registered. After all tests in the program
11302  // have finished, all global test environments will be torn-down in
11303  // the *reverse* order they were registered.
11304  //
11305  // The UnitTest object takes ownership of the given environment.
11306  //
11307  // This method can only be called from the main thread.
11308  Environment* AddEnvironment(Environment* env);
11309 
11310  // Adds a TestPartResult to the current TestResult object. All
11311  // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
11312  // eventually call this to report their results. The user code
11313  // should use the assertion macros instead of calling this directly.
11314  void AddTestPartResult(TestPartResult::Type result_type,
11315  const char* file_name,
11316  int line_number,
11317  const std::string& message,
11318  const std::string& os_stack_trace)
11319  GTEST_LOCK_EXCLUDED_(mutex_);
11320 
11321  // Adds a TestProperty to the current TestResult object when invoked from
11322  // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
11323  // from SetUpTestSuite or TearDownTestSuite, or to the global property set
11324  // when invoked elsewhere. If the result already contains a property with
11325  // the same key, the value will be updated.
11326  void RecordProperty(const std::string& key, const std::string& value);
11327 
11328  // Gets the i-th test suite among all the test suites. i can range from 0 to
11329  // total_test_suite_count() - 1. If i is not in that range, returns NULL.
11330  TestSuite* GetMutableTestSuite(int i);
11331 
11332  // Accessors for the implementation object.
11333  internal::UnitTestImpl* impl() { return impl_; }
11334  const internal::UnitTestImpl* impl() const { return impl_; }
11335 
11336  // These classes and functions are friends as they need to access private
11337  // members of UnitTest.
11338  friend class ScopedTrace;
11339  friend class Test;
11340  friend class internal::AssertHelper;
11341  friend class internal::StreamingListenerTest;
11342  friend class internal::UnitTestRecordPropertyTestHelper;
11343  friend Environment* AddGlobalTestEnvironment(Environment* env);
11344  friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
11345  friend internal::UnitTestImpl* internal::GetUnitTestImpl();
11346  friend void internal::ReportFailureInUnknownLocation(
11347  TestPartResult::Type result_type,
11348  const std::string& message);
11349 
11350  // Creates an empty UnitTest.
11351  UnitTest();
11352 
11353  // D'tor
11354  virtual ~UnitTest();
11355 
11356  // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
11357  // Google Test trace stack.
11358  void PushGTestTrace(const internal::TraceInfo& trace)
11359  GTEST_LOCK_EXCLUDED_(mutex_);
11360 
11361  // Pops a trace from the per-thread Google Test trace stack.
11362  void PopGTestTrace()
11363  GTEST_LOCK_EXCLUDED_(mutex_);
11364 
11365  // Protects mutable state in *impl_. This is mutable as some const
11366  // methods need to lock it too.
11367  mutable internal::Mutex mutex_;
11368 
11369  // Opaque implementation object. This field is never changed once
11370  // the object is constructed. We don't mark it as const here, as
11371  // doing so will cause a warning in the constructor of UnitTest.
11372  // Mutable state in *impl_ is protected by mutex_.
11373  internal::UnitTestImpl* impl_;
11374 
11375  // We disallow copying UnitTest.
11376  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
11377 };
11378 
11379 // A convenient wrapper for adding an environment for the test
11380 // program.
11381 //
11382 // You should call this before RUN_ALL_TESTS() is called, probably in
11383 // main(). If you use gtest_main, you need to call this before main()
11384 // starts for it to take effect. For example, you can define a global
11385 // variable like this:
11386 //
11387 // testing::Environment* const foo_env =
11388 // testing::AddGlobalTestEnvironment(new FooEnvironment);
11389 //
11390 // However, we strongly recommend you to write your own main() and
11391 // call AddGlobalTestEnvironment() there, as relying on initialization
11392 // of global variables makes the code harder to read and may cause
11393 // problems when you register multiple environments from different
11394 // translation units and the environments have dependencies among them
11395 // (remember that the compiler doesn't guarantee the order in which
11396 // global variables from different translation units are initialized).
11397 inline Environment* AddGlobalTestEnvironment(Environment* env) {
11398  return UnitTest::GetInstance()->AddEnvironment(env);
11399 }
11400 
11401 // Initializes Google Test. This must be called before calling
11402 // RUN_ALL_TESTS(). In particular, it parses a command line for the
11403 // flags that Google Test recognizes. Whenever a Google Test flag is
11404 // seen, it is removed from argv, and *argc is decremented.
11405 //
11406 // No value is returned. Instead, the Google Test flag variables are
11407 // updated.
11408 //
11409 // Calling the function for the second time has no user-visible effect.
11410 GTEST_API_ void InitGoogleTest(int* argc, char** argv);
11411 
11412 // This overloaded version can be used in Windows programs compiled in
11413 // UNICODE mode.
11414 GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
11415 
11416 // This overloaded version can be used on Arduino/embedded platforms where
11417 // there is no argc/argv.
11418 GTEST_API_ void InitGoogleTest();
11419 
11420 namespace internal {
11421 
11422 // Separate the error generating code from the code path to reduce the stack
11423 // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
11424 // when calling EXPECT_* in a tight loop.
11425 template <typename T1, typename T2>
11426 AssertionResult CmpHelperEQFailure(const char* lhs_expression,
11427  const char* rhs_expression,
11428  const T1& lhs, const T2& rhs) {
11429  return EqFailure(lhs_expression,
11430  rhs_expression,
11431  FormatForComparisonFailureMessage(lhs, rhs),
11432  FormatForComparisonFailureMessage(rhs, lhs),
11433  false);
11434 }
11435 
11436 // This block of code defines operator==/!=
11437 // to block lexical scope lookup.
11438 // It prevents using invalid operator==/!= defined at namespace scope.
11439 struct faketype {};
11440 inline bool operator==(faketype, faketype) { return true; }
11441 inline bool operator!=(faketype, faketype) { return false; }
11442 
11443 // The helper function for {ASSERT|EXPECT}_EQ.
11444 template <typename T1, typename T2>
11445 AssertionResult CmpHelperEQ(const char* lhs_expression,
11446  const char* rhs_expression,
11447  const T1& lhs,
11448  const T2& rhs) {
11449  if (lhs == rhs) {
11450  return AssertionSuccess();
11451  }
11452 
11453  return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
11454 }
11455 
11456 class EqHelper {
11457  public:
11458  // This templatized version is for the general case.
11459  template <
11460  typename T1, typename T2,
11461  // Disable this overload for cases where one argument is a pointer
11462  // and the other is the null pointer constant.
11463  typename std::enable_if<!std::is_integral<T1>::value ||
11464  !std::is_pointer<T2>::value>::type* = nullptr>
11465  static AssertionResult Compare(const char* lhs_expression,
11466  const char* rhs_expression, const T1& lhs,
11467  const T2& rhs) {
11468  return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
11469  }
11470 
11471  // With this overloaded version, we allow anonymous enums to be used
11472  // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
11473  // enums can be implicitly cast to BiggestInt.
11474  //
11475  // Even though its body looks the same as the above version, we
11476  // cannot merge the two, as it will make anonymous enums unhappy.
11477  static AssertionResult Compare(const char* lhs_expression,
11478  const char* rhs_expression,
11479  BiggestInt lhs,
11480  BiggestInt rhs) {
11481  return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
11482  }
11483 
11484  template <typename T>
11485  static AssertionResult Compare(
11486  const char* lhs_expression, const char* rhs_expression,
11487  // Handle cases where '0' is used as a null pointer literal.
11488  std::nullptr_t /* lhs */, T* rhs) {
11489  // We already know that 'lhs' is a null pointer.
11490  return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),
11491  rhs);
11492  }
11493 };
11494 
11495 // Separate the error generating code from the code path to reduce the stack
11496 // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
11497 // when calling EXPECT_OP in a tight loop.
11498 template <typename T1, typename T2>
11499 AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
11500  const T1& val1, const T2& val2,
11501  const char* op) {
11502  return AssertionFailure()
11503  << "Expected: (" << expr1 << ") " << op << " (" << expr2
11504  << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
11505  << " vs " << FormatForComparisonFailureMessage(val2, val1);
11506 }
11507 
11508 // A macro for implementing the helper functions needed to implement
11509 // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
11510 // of similar code.
11511 //
11512 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11513 
11514 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
11515 template <typename T1, typename T2>\
11516 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
11517  const T1& val1, const T2& val2) {\
11518  if (val1 op val2) {\
11519  return AssertionSuccess();\
11520  } else {\
11521  return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
11522  }\
11523 }
11524 
11525 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11526 
11527 // Implements the helper function for {ASSERT|EXPECT}_NE
11528 GTEST_IMPL_CMP_HELPER_(NE, !=)
11529 // Implements the helper function for {ASSERT|EXPECT}_LE
11530 GTEST_IMPL_CMP_HELPER_(LE, <=)
11531 // Implements the helper function for {ASSERT|EXPECT}_LT
11532 GTEST_IMPL_CMP_HELPER_(LT, <)
11533 // Implements the helper function for {ASSERT|EXPECT}_GE
11534 GTEST_IMPL_CMP_HELPER_(GE, >=)
11535 // Implements the helper function for {ASSERT|EXPECT}_GT
11536 GTEST_IMPL_CMP_HELPER_(GT, >)
11537 
11538 #undef GTEST_IMPL_CMP_HELPER_
11539 
11540 // The helper function for {ASSERT|EXPECT}_STREQ.
11541 //
11542 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11543 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
11544  const char* s2_expression,
11545  const char* s1,
11546  const char* s2);
11547 
11548 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
11549 //
11550 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11551 GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
11552  const char* s2_expression,
11553  const char* s1,
11554  const char* s2);
11555 
11556 // The helper function for {ASSERT|EXPECT}_STRNE.
11557 //
11558 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11559 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
11560  const char* s2_expression,
11561  const char* s1,
11562  const char* s2);
11563 
11564 // The helper function for {ASSERT|EXPECT}_STRCASENE.
11565 //
11566 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11567 GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
11568  const char* s2_expression,
11569  const char* s1,
11570  const char* s2);
11571 
11572 
11573 // Helper function for *_STREQ on wide strings.
11574 //
11575 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11576 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
11577  const char* s2_expression,
11578  const wchar_t* s1,
11579  const wchar_t* s2);
11580 
11581 // Helper function for *_STRNE on wide strings.
11582 //
11583 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11584 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
11585  const char* s2_expression,
11586  const wchar_t* s1,
11587  const wchar_t* s2);
11588 
11589 } // namespace internal
11590 
11591 // IsSubstring() and IsNotSubstring() are intended to be used as the
11592 // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
11593 // themselves. They check whether needle is a substring of haystack
11594 // (NULL is considered a substring of itself only), and return an
11595 // appropriate error message when they fail.
11596 //
11597 // The {needle,haystack}_expr arguments are the stringified
11598 // expressions that generated the two real arguments.
11599 GTEST_API_ AssertionResult IsSubstring(
11600  const char* needle_expr, const char* haystack_expr,
11601  const char* needle, const char* haystack);
11602 GTEST_API_ AssertionResult IsSubstring(
11603  const char* needle_expr, const char* haystack_expr,
11604  const wchar_t* needle, const wchar_t* haystack);
11605 GTEST_API_ AssertionResult IsNotSubstring(
11606  const char* needle_expr, const char* haystack_expr,
11607  const char* needle, const char* haystack);
11608 GTEST_API_ AssertionResult IsNotSubstring(
11609  const char* needle_expr, const char* haystack_expr,
11610  const wchar_t* needle, const wchar_t* haystack);
11611 GTEST_API_ AssertionResult IsSubstring(
11612  const char* needle_expr, const char* haystack_expr,
11613  const ::std::string& needle, const ::std::string& haystack);
11614 GTEST_API_ AssertionResult IsNotSubstring(
11615  const char* needle_expr, const char* haystack_expr,
11616  const ::std::string& needle, const ::std::string& haystack);
11617 
11618 #if GTEST_HAS_STD_WSTRING
11619 GTEST_API_ AssertionResult IsSubstring(
11620  const char* needle_expr, const char* haystack_expr,
11621  const ::std::wstring& needle, const ::std::wstring& haystack);
11622 GTEST_API_ AssertionResult IsNotSubstring(
11623  const char* needle_expr, const char* haystack_expr,
11624  const ::std::wstring& needle, const ::std::wstring& haystack);
11625 #endif // GTEST_HAS_STD_WSTRING
11626 
11627 namespace internal {
11628 
11629 // Helper template function for comparing floating-points.
11630 //
11631 // Template parameter:
11632 //
11633 // RawType: the raw floating-point type (either float or double)
11634 //
11635 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11636 template <typename RawType>
11637 AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
11638  const char* rhs_expression,
11639  RawType lhs_value,
11640  RawType rhs_value) {
11641  const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
11642 
11643  if (lhs.AlmostEquals(rhs)) {
11644  return AssertionSuccess();
11645  }
11646 
11647  ::std::stringstream lhs_ss;
11648  lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
11649  << lhs_value;
11650 
11651  ::std::stringstream rhs_ss;
11652  rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
11653  << rhs_value;
11654 
11655  return EqFailure(lhs_expression,
11656  rhs_expression,
11657  StringStreamToString(&lhs_ss),
11658  StringStreamToString(&rhs_ss),
11659  false);
11660 }
11661 
11662 // Helper function for implementing ASSERT_NEAR.
11663 //
11664 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
11665 GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
11666  const char* expr2,
11667  const char* abs_error_expr,
11668  double val1,
11669  double val2,
11670  double abs_error);
11671 
11672 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
11673 // A class that enables one to stream messages to assertion macros
11674 class GTEST_API_ AssertHelper {
11675  public:
11676  // Constructor.
11677  AssertHelper(TestPartResult::Type type,
11678  const char* file,
11679  int line,
11680  const char* message);
11681  ~AssertHelper();
11682 
11683  // Message assignment is a semantic trick to enable assertion
11684  // streaming; see the GTEST_MESSAGE_ macro below.
11685  void operator=(const Message& message) const;
11686 
11687  private:
11688  // We put our data in a struct so that the size of the AssertHelper class can
11689  // be as small as possible. This is important because gcc is incapable of
11690  // re-using stack space even for temporary variables, so every EXPECT_EQ
11691  // reserves stack space for another AssertHelper.
11692  struct AssertHelperData {
11693  AssertHelperData(TestPartResult::Type t,
11694  const char* srcfile,
11695  int line_num,
11696  const char* msg)
11697  : type(t), file(srcfile), line(line_num), message(msg) { }
11698 
11699  TestPartResult::Type const type;
11700  const char* const file;
11701  int const line;
11702  std::string const message;
11703 
11704  private:
11705  GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
11706  };
11707 
11708  AssertHelperData* const data_;
11709 
11710  GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
11711 };
11712 
11713 } // namespace internal
11714 
11715 // The pure interface class that all value-parameterized tests inherit from.
11716 // A value-parameterized class must inherit from both ::testing::Test and
11717 // ::testing::WithParamInterface. In most cases that just means inheriting
11718 // from ::testing::TestWithParam, but more complicated test hierarchies
11719 // may need to inherit from Test and WithParamInterface at different levels.
11720 //
11721 // This interface has support for accessing the test parameter value via
11722 // the GetParam() method.
11723 //
11724 // Use it with one of the parameter generator defining functions, like Range(),
11725 // Values(), ValuesIn(), Bool(), and Combine().
11726 //
11727 // class FooTest : public ::testing::TestWithParam<int> {
11728 // protected:
11729 // FooTest() {
11730 // // Can use GetParam() here.
11731 // }
11732 // ~FooTest() override {
11733 // // Can use GetParam() here.
11734 // }
11735 // void SetUp() override {
11736 // // Can use GetParam() here.
11737 // }
11738 // void TearDown override {
11739 // // Can use GetParam() here.
11740 // }
11741 // };
11742 // TEST_P(FooTest, DoesBar) {
11743 // // Can use GetParam() method here.
11744 // Foo foo;
11745 // ASSERT_TRUE(foo.DoesBar(GetParam()));
11746 // }
11747 // INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
11748 
11749 template <typename T>
11750 class WithParamInterface {
11751  public:
11752  typedef T ParamType;
11753  virtual ~WithParamInterface() {}
11754 
11755  // The current parameter value. Is also available in the test fixture's
11756  // constructor.
11757  static const ParamType& GetParam() {
11758  GTEST_CHECK_(parameter_ != nullptr)
11759  << "GetParam() can only be called inside a value-parameterized test "
11760  << "-- did you intend to write TEST_P instead of TEST_F?";
11761  return *parameter_;
11762  }
11763 
11764  private:
11765  // Sets parameter value. The caller is responsible for making sure the value
11766  // remains alive and unchanged throughout the current test.
11767  static void SetParam(const ParamType* parameter) {
11768  parameter_ = parameter;
11769  }
11770 
11771  // Static value used for accessing parameter during a test lifetime.
11772  static const ParamType* parameter_;
11773 
11774  // TestClass must be a subclass of WithParamInterface<T> and Test.
11775  template <class TestClass> friend class internal::ParameterizedTestFactory;
11776 };
11777 
11778 template <typename T>
11779 const T* WithParamInterface<T>::parameter_ = nullptr;
11780 
11781 // Most value-parameterized classes can ignore the existence of
11782 // WithParamInterface, and can just inherit from ::testing::TestWithParam.
11783 
11784 template <typename T>
11785 class TestWithParam : public Test, public WithParamInterface<T> {
11786 };
11787 
11788 // Macros for indicating success/failure in test code.
11789 
11790 // Skips test in runtime.
11791 // Skipping test aborts current function.
11792 // Skipped tests are neither successful nor failed.
11793 #define GTEST_SKIP() GTEST_SKIP_("")
11794 
11795 // ADD_FAILURE unconditionally adds a failure to the current test.
11796 // SUCCEED generates a success - it doesn't automatically make the
11797 // current test successful, as a test is only successful when it has
11798 // no failure.
11799 //
11800 // EXPECT_* verifies that a certain condition is satisfied. If not,
11801 // it behaves like ADD_FAILURE. In particular:
11802 //
11803 // EXPECT_TRUE verifies that a Boolean condition is true.
11804 // EXPECT_FALSE verifies that a Boolean condition is false.
11805 //
11806 // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
11807 // that they will also abort the current function on failure. People
11808 // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
11809 // writing data-driven tests often find themselves using ADD_FAILURE
11810 // and EXPECT_* more.
11811 
11812 // Generates a nonfatal failure with a generic message.
11813 #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
11814 
11815 // Generates a nonfatal failure at the given source file location with
11816 // a generic message.
11817 #define ADD_FAILURE_AT(file, line) \
11818  GTEST_MESSAGE_AT_(file, line, "Failed", \
11819  ::testing::TestPartResult::kNonFatalFailure)
11820 
11821 // Generates a fatal failure with a generic message.
11822 #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
11823 
11824 // Like GTEST_FAIL(), but at the given source file location.
11825 #define GTEST_FAIL_AT(file, line) \
11826  GTEST_MESSAGE_AT_(file, line, "Failed", \
11827  ::testing::TestPartResult::kFatalFailure)
11828 
11829 // Define this macro to 1 to omit the definition of FAIL(), which is a
11830 // generic name and clashes with some other libraries.
11831 #if !GTEST_DONT_DEFINE_FAIL
11832 # define FAIL() GTEST_FAIL()
11833 #endif
11834 
11835 // Generates a success with a generic message.
11836 #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
11837 
11838 // Define this macro to 1 to omit the definition of SUCCEED(), which
11839 // is a generic name and clashes with some other libraries.
11840 #if !GTEST_DONT_DEFINE_SUCCEED
11841 # define SUCCEED() GTEST_SUCCEED()
11842 #endif
11843 
11844 // Macros for testing exceptions.
11845 //
11846 // * {ASSERT|EXPECT}_THROW(statement, expected_exception):
11847 // Tests that the statement throws the expected exception.
11848 // * {ASSERT|EXPECT}_NO_THROW(statement):
11849 // Tests that the statement doesn't throw any exception.
11850 // * {ASSERT|EXPECT}_ANY_THROW(statement):
11851 // Tests that the statement throws an exception.
11852 
11853 #define EXPECT_THROW(statement, expected_exception) \
11854  GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
11855 #define EXPECT_NO_THROW(statement) \
11856  GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
11857 #define EXPECT_ANY_THROW(statement) \
11858  GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
11859 #define ASSERT_THROW(statement, expected_exception) \
11860  GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
11861 #define ASSERT_NO_THROW(statement) \
11862  GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
11863 #define ASSERT_ANY_THROW(statement) \
11864  GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
11865 
11866 // Boolean assertions. Condition can be either a Boolean expression or an
11867 // AssertionResult. For more information on how to use AssertionResult with
11868 // these macros see comments on that class.
11869 #define GTEST_EXPECT_TRUE(condition) \
11870  GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
11871  GTEST_NONFATAL_FAILURE_)
11872 #define GTEST_EXPECT_FALSE(condition) \
11873  GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
11874  GTEST_NONFATAL_FAILURE_)
11875 #define GTEST_ASSERT_TRUE(condition) \
11876  GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
11877  GTEST_FATAL_FAILURE_)
11878 #define GTEST_ASSERT_FALSE(condition) \
11879  GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
11880  GTEST_FATAL_FAILURE_)
11881 
11882 // Define these macros to 1 to omit the definition of the corresponding
11883 // EXPECT or ASSERT, which clashes with some users' own code.
11884 
11885 #if !GTEST_DONT_DEFINE_EXPECT_TRUE
11886 #define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
11887 #endif
11888 
11889 #if !GTEST_DONT_DEFINE_EXPECT_FALSE
11890 #define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
11891 #endif
11892 
11893 #if !GTEST_DONT_DEFINE_ASSERT_TRUE
11894 #define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
11895 #endif
11896 
11897 #if !GTEST_DONT_DEFINE_ASSERT_FALSE
11898 #define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
11899 #endif
11900 
11901 // Macros for testing equalities and inequalities.
11902 //
11903 // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
11904 // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
11905 // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
11906 // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
11907 // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
11908 // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
11909 //
11910 // When they are not, Google Test prints both the tested expressions and
11911 // their actual values. The values must be compatible built-in types,
11912 // or you will get a compiler error. By "compatible" we mean that the
11913 // values can be compared by the respective operator.
11914 //
11915 // Note:
11916 //
11917 // 1. It is possible to make a user-defined type work with
11918 // {ASSERT|EXPECT}_??(), but that requires overloading the
11919 // comparison operators and is thus discouraged by the Google C++
11920 // Usage Guide. Therefore, you are advised to use the
11921 // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
11922 // equal.
11923 //
11924 // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
11925 // pointers (in particular, C strings). Therefore, if you use it
11926 // with two C strings, you are testing how their locations in memory
11927 // are related, not how their content is related. To compare two C
11928 // strings by content, use {ASSERT|EXPECT}_STR*().
11929 //
11930 // 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
11931 // {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
11932 // what the actual value is when it fails, and similarly for the
11933 // other comparisons.
11934 //
11935 // 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
11936 // evaluate their arguments, which is undefined.
11937 //
11938 // 5. These macros evaluate their arguments exactly once.
11939 //
11940 // Examples:
11941 //
11942 // EXPECT_NE(Foo(), 5);
11943 // EXPECT_EQ(a_pointer, NULL);
11944 // ASSERT_LT(i, array_size);
11945 // ASSERT_GT(records.size(), 0) << "There is no record left.";
11946 
11947 #define EXPECT_EQ(val1, val2) \
11948  EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
11949 #define EXPECT_NE(val1, val2) \
11950  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
11951 #define EXPECT_LE(val1, val2) \
11952  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
11953 #define EXPECT_LT(val1, val2) \
11954  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
11955 #define EXPECT_GE(val1, val2) \
11956  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
11957 #define EXPECT_GT(val1, val2) \
11958  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
11959 
11960 #define GTEST_ASSERT_EQ(val1, val2) \
11961  ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
11962 #define GTEST_ASSERT_NE(val1, val2) \
11963  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
11964 #define GTEST_ASSERT_LE(val1, val2) \
11965  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
11966 #define GTEST_ASSERT_LT(val1, val2) \
11967  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
11968 #define GTEST_ASSERT_GE(val1, val2) \
11969  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
11970 #define GTEST_ASSERT_GT(val1, val2) \
11971  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
11972 
11973 // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
11974 // ASSERT_XY(), which clashes with some users' own code.
11975 
11976 #if !GTEST_DONT_DEFINE_ASSERT_EQ
11977 # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
11978 #endif
11979 
11980 #if !GTEST_DONT_DEFINE_ASSERT_NE
11981 # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
11982 #endif
11983 
11984 #if !GTEST_DONT_DEFINE_ASSERT_LE
11985 # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
11986 #endif
11987 
11988 #if !GTEST_DONT_DEFINE_ASSERT_LT
11989 # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
11990 #endif
11991 
11992 #if !GTEST_DONT_DEFINE_ASSERT_GE
11993 # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
11994 #endif
11995 
11996 #if !GTEST_DONT_DEFINE_ASSERT_GT
11997 # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
11998 #endif
11999 
12000 // C-string Comparisons. All tests treat NULL and any non-NULL string
12001 // as different. Two NULLs are equal.
12002 //
12003 // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
12004 // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
12005 // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
12006 // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
12007 //
12008 // For wide or narrow string objects, you can use the
12009 // {ASSERT|EXPECT}_??() macros.
12010 //
12011 // Don't depend on the order in which the arguments are evaluated,
12012 // which is undefined.
12013 //
12014 // These macros evaluate their arguments exactly once.
12015 
12016 #define EXPECT_STREQ(s1, s2) \
12017  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
12018 #define EXPECT_STRNE(s1, s2) \
12019  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
12020 #define EXPECT_STRCASEEQ(s1, s2) \
12021  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
12022 #define EXPECT_STRCASENE(s1, s2)\
12023  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
12024 
12025 #define ASSERT_STREQ(s1, s2) \
12026  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
12027 #define ASSERT_STRNE(s1, s2) \
12028  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
12029 #define ASSERT_STRCASEEQ(s1, s2) \
12030  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
12031 #define ASSERT_STRCASENE(s1, s2)\
12032  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
12033 
12034 // Macros for comparing floating-point numbers.
12035 //
12036 // * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
12037 // Tests that two float values are almost equal.
12038 // * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
12039 // Tests that two double values are almost equal.
12040 // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
12041 // Tests that v1 and v2 are within the given distance to each other.
12042 //
12043 // Google Test uses ULP-based comparison to automatically pick a default
12044 // error bound that is appropriate for the operands. See the
12045 // FloatingPoint template class in gtest-internal.h if you are
12046 // interested in the implementation details.
12047 
12048 #define EXPECT_FLOAT_EQ(val1, val2)\
12049  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
12050  val1, val2)
12051 
12052 #define EXPECT_DOUBLE_EQ(val1, val2)\
12053  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
12054  val1, val2)
12055 
12056 #define ASSERT_FLOAT_EQ(val1, val2)\
12057  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
12058  val1, val2)
12059 
12060 #define ASSERT_DOUBLE_EQ(val1, val2)\
12061  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
12062  val1, val2)
12063 
12064 #define EXPECT_NEAR(val1, val2, abs_error)\
12065  EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
12066  val1, val2, abs_error)
12067 
12068 #define ASSERT_NEAR(val1, val2, abs_error)\
12069  ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
12070  val1, val2, abs_error)
12071 
12072 // These predicate format functions work on floating-point values, and
12073 // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
12074 //
12075 // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
12076 
12077 // Asserts that val1 is less than, or almost equal to, val2. Fails
12078 // otherwise. In particular, it fails if either val1 or val2 is NaN.
12079 GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
12080  float val1, float val2);
12081 GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
12082  double val1, double val2);
12083 
12084 
12085 #if GTEST_OS_WINDOWS
12086 
12087 // Macros that test for HRESULT failure and success, these are only useful
12088 // on Windows, and rely on Windows SDK macros and APIs to compile.
12089 //
12090 // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
12091 //
12092 // When expr unexpectedly fails or succeeds, Google Test prints the
12093 // expected result and the actual result with both a human-readable
12094 // string representation of the error, if available, as well as the
12095 // hex result code.
12096 # define EXPECT_HRESULT_SUCCEEDED(expr) \
12097  EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
12098 
12099 # define ASSERT_HRESULT_SUCCEEDED(expr) \
12100  ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
12101 
12102 # define EXPECT_HRESULT_FAILED(expr) \
12103  EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
12104 
12105 # define ASSERT_HRESULT_FAILED(expr) \
12106  ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
12107 
12108 #endif // GTEST_OS_WINDOWS
12109 
12110 // Macros that execute statement and check that it doesn't generate new fatal
12111 // failures in the current thread.
12112 //
12113 // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
12114 //
12115 // Examples:
12116 //
12117 // EXPECT_NO_FATAL_FAILURE(Process());
12118 // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
12119 //
12120 #define ASSERT_NO_FATAL_FAILURE(statement) \
12121  GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
12122 #define EXPECT_NO_FATAL_FAILURE(statement) \
12123  GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
12124 
12125 // Causes a trace (including the given source file path and line number,
12126 // and the given message) to be included in every test failure message generated
12127 // by code in the scope of the lifetime of an instance of this class. The effect
12128 // is undone with the destruction of the instance.
12129 //
12130 // The message argument can be anything streamable to std::ostream.
12131 //
12132 // Example:
12133 // testing::ScopedTrace trace("file.cc", 123, "message");
12134 //
12135 class GTEST_API_ ScopedTrace {
12136  public:
12137  // The c'tor pushes the given source file location and message onto
12138  // a trace stack maintained by Google Test.
12139 
12140  // Template version. Uses Message() to convert the values into strings.
12141  // Slow, but flexible.
12142  template <typename T>
12143  ScopedTrace(const char* file, int line, const T& message) {
12144  PushTrace(file, line, (Message() << message).GetString());
12145  }
12146 
12147  // Optimize for some known types.
12148  ScopedTrace(const char* file, int line, const char* message) {
12149  PushTrace(file, line, message ? message : "(null)");
12150  }
12151 
12152  ScopedTrace(const char* file, int line, const std::string& message) {
12153  PushTrace(file, line, message);
12154  }
12155 
12156  // The d'tor pops the info pushed by the c'tor.
12157  //
12158  // Note that the d'tor is not virtual in order to be efficient.
12159  // Don't inherit from ScopedTrace!
12160  ~ScopedTrace();
12161 
12162  private:
12163  void PushTrace(const char* file, int line, std::string message);
12164 
12165  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
12166 } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
12167  // c'tor and d'tor. Therefore it doesn't
12168  // need to be used otherwise.
12169 
12170 // Causes a trace (including the source file path, the current line
12171 // number, and the given message) to be included in every test failure
12172 // message generated by code in the current scope. The effect is
12173 // undone when the control leaves the current scope.
12174 //
12175 // The message argument can be anything streamable to std::ostream.
12176 //
12177 // In the implementation, we include the current line number as part
12178 // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
12179 // to appear in the same block - as long as they are on different
12180 // lines.
12181 //
12182 // Assuming that each thread maintains its own stack of traces.
12183 // Therefore, a SCOPED_TRACE() would (correctly) only affect the
12184 // assertions in its own thread.
12185 #define SCOPED_TRACE(message) \
12186  ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
12187  __FILE__, __LINE__, (message))
12188 
12189 // Compile-time assertion for type equality.
12190 // StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
12191 // are the same type. The value it returns is not interesting.
12192 //
12193 // Instead of making StaticAssertTypeEq a class template, we make it a
12194 // function template that invokes a helper class template. This
12195 // prevents a user from misusing StaticAssertTypeEq<T1, T2> by
12196 // defining objects of that type.
12197 //
12198 // CAVEAT:
12199 //
12200 // When used inside a method of a class template,
12201 // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
12202 // instantiated. For example, given:
12203 //
12204 // template <typename T> class Foo {
12205 // public:
12206 // void Bar() { testing::StaticAssertTypeEq<int, T>(); }
12207 // };
12208 //
12209 // the code:
12210 //
12211 // void Test1() { Foo<bool> foo; }
12212 //
12213 // will NOT generate a compiler error, as Foo<bool>::Bar() is never
12214 // actually instantiated. Instead, you need:
12215 //
12216 // void Test2() { Foo<bool> foo; foo.Bar(); }
12217 //
12218 // to cause a compiler error.
12219 template <typename T1, typename T2>
12220 constexpr bool StaticAssertTypeEq() noexcept {
12221  static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type");
12222  return true;
12223 }
12224 
12225 // Defines a test.
12226 //
12227 // The first parameter is the name of the test suite, and the second
12228 // parameter is the name of the test within the test suite.
12229 //
12230 // The convention is to end the test suite name with "Test". For
12231 // example, a test suite for the Foo class can be named FooTest.
12232 //
12233 // Test code should appear between braces after an invocation of
12234 // this macro. Example:
12235 //
12236 // TEST(FooTest, InitializesCorrectly) {
12237 // Foo foo;
12238 // EXPECT_TRUE(foo.StatusIsOK());
12239 // }
12240 
12241 // Note that we call GetTestTypeId() instead of GetTypeId<
12242 // ::testing::Test>() here to get the type ID of testing::Test. This
12243 // is to work around a suspected linker bug when using Google Test as
12244 // a framework on Mac OS X. The bug causes GetTypeId<
12245 // ::testing::Test>() to return different values depending on whether
12246 // the call is from the Google Test framework itself or from user test
12247 // code. GetTestTypeId() is guaranteed to always return the same
12248 // value, as it always calls GetTypeId<>() from the Google Test
12249 // framework.
12250 #define GTEST_TEST(test_suite_name, test_name) \
12251  GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \
12252  ::testing::internal::GetTestTypeId())
12253 
12254 // Define this macro to 1 to omit the definition of TEST(), which
12255 // is a generic name and clashes with some other libraries.
12256 #if !GTEST_DONT_DEFINE_TEST
12257 #define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
12258 #endif
12259 
12260 // Defines a test that uses a test fixture.
12261 //
12262 // The first parameter is the name of the test fixture class, which
12263 // also doubles as the test suite name. The second parameter is the
12264 // name of the test within the test suite.
12265 //
12266 // A test fixture class must be declared earlier. The user should put
12267 // the test code between braces after using this macro. Example:
12268 //
12269 // class FooTest : public testing::Test {
12270 // protected:
12271 // void SetUp() override { b_.AddElement(3); }
12272 //
12273 // Foo a_;
12274 // Foo b_;
12275 // };
12276 //
12277 // TEST_F(FooTest, InitializesCorrectly) {
12278 // EXPECT_TRUE(a_.StatusIsOK());
12279 // }
12280 //
12281 // TEST_F(FooTest, ReturnsElementCountCorrectly) {
12282 // EXPECT_EQ(a_.size(), 0);
12283 // EXPECT_EQ(b_.size(), 1);
12284 // }
12285 //
12286 // GOOGLETEST_CM0011 DO NOT DELETE
12287 #if !GTEST_DONT_DEFINE_TEST
12288 #define TEST_F(test_fixture, test_name)\
12289  GTEST_TEST_(test_fixture, test_name, test_fixture, \
12290  ::testing::internal::GetTypeId<test_fixture>())
12291 #endif // !GTEST_DONT_DEFINE_TEST
12292 
12293 // Returns a path to temporary directory.
12294 // Tries to determine an appropriate directory for the platform.
12295 GTEST_API_ std::string TempDir();
12296 
12297 #ifdef _MSC_VER
12298 # pragma warning(pop)
12299 #endif
12300 
12301 // Dynamically registers a test with the framework.
12302 //
12303 // This is an advanced API only to be used when the `TEST` macros are
12304 // insufficient. The macros should be preferred when possible, as they avoid
12305 // most of the complexity of calling this function.
12306 //
12307 // The `factory` argument is a factory callable (move-constructible) object or
12308 // function pointer that creates a new instance of the Test object. It
12309 // handles ownership to the caller. The signature of the callable is
12310 // `Fixture*()`, where `Fixture` is the test fixture class for the test. All
12311 // tests registered with the same `test_suite_name` must return the same
12312 // fixture type. This is checked at runtime.
12313 //
12314 // The framework will infer the fixture class from the factory and will call
12315 // the `SetUpTestSuite` and `TearDownTestSuite` for it.
12316 //
12317 // Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
12318 // undefined.
12319 //
12320 // Use case example:
12321 //
12322 // class MyFixture : public ::testing::Test {
12323 // public:
12324 // // All of these optional, just like in regular macro usage.
12325 // static void SetUpTestSuite() { ... }
12326 // static void TearDownTestSuite() { ... }
12327 // void SetUp() override { ... }
12328 // void TearDown() override { ... }
12329 // };
12330 //
12331 // class MyTest : public MyFixture {
12332 // public:
12333 // explicit MyTest(int data) : data_(data) {}
12334 // void TestBody() override { ... }
12335 //
12336 // private:
12337 // int data_;
12338 // };
12339 //
12340 // void RegisterMyTests(const std::vector<int>& values) {
12341 // for (int v : values) {
12342 // ::testing::RegisterTest(
12343 // "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
12344 // std::to_string(v).c_str(),
12345 // __FILE__, __LINE__,
12346 // // Important to use the fixture type as the return type here.
12347 // [=]() -> MyFixture* { return new MyTest(v); });
12348 // }
12349 // }
12350 // ...
12351 // int main(int argc, char** argv) {
12352 // std::vector<int> values_to_test = LoadValuesFromConfig();
12353 // RegisterMyTests(values_to_test);
12354 // ...
12355 // return RUN_ALL_TESTS();
12356 // }
12357 //
12358 template <int&... ExplicitParameterBarrier, typename Factory>
12359 TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
12360  const char* type_param, const char* value_param,
12361  const char* file, int line, Factory factory) {
12362  using TestT = typename std::remove_pointer<decltype(factory())>::type;
12363 
12364  class FactoryImpl : public internal::TestFactoryBase {
12365  public:
12366  explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}
12367  Test* CreateTest() override { return factory_(); }
12368 
12369  private:
12370  Factory factory_;
12371  };
12372 
12373  return internal::MakeAndRegisterTestInfo(
12374  test_suite_name, test_name, type_param, value_param,
12375  internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),
12376  internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),
12377  internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),
12378  new FactoryImpl{std::move(factory)});
12379 }
12380 
12381 } // namespace testing
12382 
12383 // Use this function in main() to run all tests. It returns 0 if all
12384 // tests are successful, or 1 otherwise.
12385 //
12386 // RUN_ALL_TESTS() should be invoked after the command line has been
12387 // parsed by InitGoogleTest().
12388 //
12389 // This function was formerly a macro; thus, it is in the global
12390 // namespace and has an all-caps name.
12391 int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
12392 
12393 inline int RUN_ALL_TESTS() {
12394  return ::testing::UnitTest::GetInstance()->Run();
12395 }
12396 
12397 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
12398 
12399 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_
bool test
enable/disable tests
Definition: distributed_functions.cxx:47
Definition: gmock.h:374
Definition: posix-mock.h:29
void info(const STRING &string, const int verbosity_level=1)
Use this function for writing informational messages.
Definition: info.h:51
STL namespace.
Definition: gtest.h:3471
const Array< num_dimensions - num_dimensions2, elemT > & get(const Array< num_dimensions, elemT > &a, const BasicCoordinate< num_dimensions2, int > &c)
an alternative for array indexing using BasicCoordinate objects
Definition: array_index_functions.inl:114