googletest-printers-test.cc 63.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
29

Gennadiy Civil's avatar
Gennadiy Civil committed
30
// Google Test - The Google C++ Testing and Mocking Framework
31
32
33
34
//
// This file tests the universal value printer.

#include <algorithm>
Abseil Team's avatar
Abseil Team committed
35
#include <cctype>
Abseil Team's avatar
Abseil Team committed
36
#include <cstdint>
Abseil Team's avatar
Abseil Team committed
37
#include <cstring>
38
#include <deque>
Abseil Team's avatar
Abseil Team committed
39
#include <forward_list>
40
#include <functional>
Abseil Team's avatar
Abseil Team committed
41
#include <limits>
42
43
#include <list>
#include <map>
Abseil Team's avatar
Abseil Team committed
44
#include <memory>
45
46
47
#include <set>
#include <sstream>
#include <string>
Abseil Team's avatar
Abseil Team committed
48
49
#include <unordered_map>
#include <unordered_set>
50
51
52
#include <utility>
#include <vector>

53
#include "gtest/gtest-printers.h"
54
#include "gtest/gtest.h"
55
56
57

// Some user-defined types for testing the universal value printer.

58
// An anonymous enum type.
59
enum AnonymousEnum { kAE1 = -1, kAE2 = 1 };
60
61

// An enum without a user-defined printer.
62
enum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 };
63
64

// An enum with a << operator.
65
enum EnumWithStreaming { kEWS1 = 10 };
66
67
68
69
70
71

std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
  return os << (e == kEWS1 ? "kEWS1" : "invalid");
}

// An enum with a PrintTo() function.
72
enum EnumWithPrintTo { kEWPT1 = 1 };
73
74
75
76
77

void PrintTo(EnumWithPrintTo e, std::ostream* os) {
  *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
}

78
79
// A class implicitly convertible to BiggestInt.
class BiggestIntConvertible {
80
 public:
81
  operator ::testing::internal::BiggestInt() const { return 42; }
82
83
};

Abseil Team's avatar
Abseil Team committed
84
85
86
87
88
89
90
91
92
93
94
95
// A parent class with two child classes. The parent and one of the kids have
// stream operators.
class ParentClass {};
class ChildClassWithStreamOperator : public ParentClass {};
class ChildClassWithoutStreamOperator : public ParentClass {};
static void operator<<(std::ostream& os, const ParentClass&) {
  os << "ParentClass";
}
static void operator<<(std::ostream& os, const ChildClassWithStreamOperator&) {
  os << "ChildClassWithStreamOperator";
}

96
97
98
99
100
// A user-defined unprintable class template in the global namespace.
template <typename T>
class UnprintableTemplateInGlobal {
 public:
  UnprintableTemplateInGlobal() : value_() {}
101

102
103
104
105
106
107
108
109
110
111
112
113
114
115
 private:
  T value_;
};

// A user-defined streamable type in the global namespace.
class StreamableInGlobal {
 public:
  virtual ~StreamableInGlobal() {}
};

inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
  os << "StreamableInGlobal";
}

116
117
118
119
void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
  os << "StreamableInGlobal*";
}

120
121
122
123
124
namespace foo {

// A user-defined unprintable type in a user namespace.
class UnprintableInFoo {
 public:
vladlosev's avatar
vladlosev committed
125
  UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
126
  double z() const { return z_; }
127

128
 private:
vladlosev's avatar
vladlosev committed
129
  char xy_[8];
130
131
132
133
134
135
136
137
138
139
140
141
142
  double z_;
};

// A user-defined printable type in a user-chosen namespace.
struct PrintableViaPrintTo {
  PrintableViaPrintTo() : value() {}
  int value;
};

void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
  *os << "PrintableViaPrintTo: " << x.value;
}

143
// A type with a user-defined << for printing its pointer.
144
struct PointerPrintable {};
145
146
147
148
149
150

::std::ostream& operator<<(::std::ostream& os,
                           const PointerPrintable* /* x */) {
  return os << "PointerPrintable*";
}

151
152
153
154
155
156
157
// A user-defined printable class template in a user-chosen namespace.
template <typename T>
class PrintableViaPrintToTemplate {
 public:
  explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}

  const T& value() const { return value_; }
158

159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
 private:
  T value_;
};

template <typename T>
void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {
  *os << "PrintableViaPrintToTemplate: " << x.value();
}

// A user-defined streamable class template in a user namespace.
template <typename T>
class StreamableTemplateInFoo {
 public:
  StreamableTemplateInFoo() : value_() {}

  const T& value() const { return value_; }
175

176
177
178
179
180
181
182
183
184
185
 private:
  T value_;
};

template <typename T>
inline ::std::ostream& operator<<(::std::ostream& os,
                                  const StreamableTemplateInFoo<T>& x) {
  return os << "StreamableTemplateInFoo: " << x.value();
}

Abseil Team's avatar
Abseil Team committed
186
187
188
189
190
191
192
193
194
195
196
// A user-defined streamable type in a user namespace whose operator<< is
// templated on the type of the output stream.
struct TemplatedStreamableInFoo {};

template <typename OutputStream>
OutputStream& operator<<(OutputStream& os,
                         const TemplatedStreamableInFoo& /*ts*/) {
  os << "TemplatedStreamableInFoo";
  return os;
}

197
198
199
200
201
struct StreamableInLocal {};
void operator<<(::std::ostream& os, const StreamableInLocal& /* x */) {
  os << "StreamableInLocal";
}

John Bampton's avatar
John Bampton committed
202
// A user-defined streamable but recursively-defined container type in
203
204
205
206
// a user namespace, it mimics therefore std::filesystem::path or
// boost::filesystem::path.
class PathLike {
 public:
Gennadiy Civil's avatar
 
Gennadiy Civil committed
207
  struct iterator {
208
    typedef PathLike value_type;
Ryohei Machida's avatar
Ryohei Machida committed
209
210
211

    iterator& operator++();
    PathLike& operator*();
212
213
  };

Ryohei Machida's avatar
Ryohei Machida committed
214
215
216
  using value_type = char;
  using const_iterator = iterator;

217
218
  PathLike() {}

219
220
221
  iterator begin() const { return iterator(); }
  iterator end() const { return iterator(); }

Gennadiy Civil's avatar
 
Gennadiy Civil committed
222
  friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) {
223
224
225
226
    return os << "Streamable-PathLike";
  }
};

227
228
229
}  // namespace foo

namespace testing {
Abseil Team's avatar
Abseil Team committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
namespace {
template <typename T>
class Wrapper {
 public:
  explicit Wrapper(T&& value) : value_(std::forward<T>(value)) {}

  const T& value() const { return value_; }

 private:
  T value_;
};

}  // namespace

namespace internal {
template <typename T>
class UniversalPrinter<Wrapper<T>> {
 public:
  static void Print(const Wrapper<T>& w, ::std::ostream* os) {
    *os << "Wrapper(";
    UniversalPrint(w.value(), os);
    *os << ')';
  }
};
}  // namespace internal

256
257
258
259
260
261
262
263
264
265
266
267
namespace gtest_printers_test {

using ::std::deque;
using ::std::list;
using ::std::make_pair;
using ::std::map;
using ::std::multimap;
using ::std::multiset;
using ::std::pair;
using ::std::set;
using ::std::vector;
using ::testing::PrintToString;
268
using ::testing::internal::FormatForComparisonFailureMessage;
269
using ::testing::internal::NativeArray;
billydonahue's avatar
billydonahue committed
270
using ::testing::internal::RelationToSourceReference;
271
272
273
using ::testing::internal::Strings;
using ::testing::internal::UniversalPrint;
using ::testing::internal::UniversalPrinter;
274
275
using ::testing::internal::UniversalTersePrint;
using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
Gennadiy Civil's avatar
Gennadiy Civil committed
276

277
278
279
// Prints a value to a string using the universal value printer.  This
// is a helper for testing UniversalPrinter<T>::Print() for various types.
template <typename T>
280
std::string Print(const T& value) {
281
282
283
284
285
286
287
288
289
  ::std::stringstream ss;
  UniversalPrinter<T>::Print(value, &ss);
  return ss.str();
}

// Prints a value passed by reference to a string, using the universal
// value printer.  This is a helper for testing
// UniversalPrinter<T&>::Print() for various types.
template <typename T>
290
std::string PrintByRef(const T& value) {
291
292
293
294
295
  ::std::stringstream ss;
  UniversalPrinter<T&>::Print(value, &ss);
  return ss.str();
}

296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Tests printing various enum types.

TEST(PrintEnumTest, AnonymousEnum) {
  EXPECT_EQ("-1", Print(kAE1));
  EXPECT_EQ("1", Print(kAE2));
}

TEST(PrintEnumTest, EnumWithoutPrinter) {
  EXPECT_EQ("-2", Print(kEWP1));
  EXPECT_EQ("42", Print(kEWP2));
}

TEST(PrintEnumTest, EnumWithStreaming) {
  EXPECT_EQ("kEWS1", Print(kEWS1));
  EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0)));
}

TEST(PrintEnumTest, EnumWithPrintTo) {
  EXPECT_EQ("kEWPT1", Print(kEWPT1));
  EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
}

318
// Tests printing a class implicitly convertible to BiggestInt.
319

320
321
TEST(PrintClassTest, BiggestIntConvertible) {
  EXPECT_EQ("42", Print(BiggestIntConvertible()));
322
323
}

324
325
326
327
328
// Tests printing various char types.

// char.
TEST(PrintCharTest, PlainChar) {
  EXPECT_EQ("'\\0'", Print('\0'));
329
330
  EXPECT_EQ("'\\'' (39, 0x27)", Print('\''));
  EXPECT_EQ("'\"' (34, 0x22)", Print('"'));
331
  EXPECT_EQ("'?' (63, 0x3F)", Print('?'));
332
  EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\'));
333
334
  EXPECT_EQ("'\\a' (7)", Print('\a'));
  EXPECT_EQ("'\\b' (8)", Print('\b'));
335
336
337
  EXPECT_EQ("'\\f' (12, 0xC)", Print('\f'));
  EXPECT_EQ("'\\n' (10, 0xA)", Print('\n'));
  EXPECT_EQ("'\\r' (13, 0xD)", Print('\r'));
338
  EXPECT_EQ("'\\t' (9)", Print('\t'));
339
  EXPECT_EQ("'\\v' (11, 0xB)", Print('\v'));
340
341
  EXPECT_EQ("'\\x7F' (127)", Print('\x7F'));
  EXPECT_EQ("'\\xFF' (255)", Print('\xFF'));
342
343
  EXPECT_EQ("' ' (32, 0x20)", Print(' '));
  EXPECT_EQ("'a' (97, 0x61)", Print('a'));
344
345
346
347
348
}

// signed char.
TEST(PrintCharTest, SignedChar) {
  EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
349
  EXPECT_EQ("'\\xCE' (-50)", Print(static_cast<signed char>(-50)));
350
351
352
353
354
}

// unsigned char.
TEST(PrintCharTest, UnsignedChar) {
  EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
355
  EXPECT_EQ("'b' (98, 0x62)", Print(static_cast<unsigned char>('b')));
356
357
}

358
TEST(PrintCharTest, Char16) { EXPECT_EQ("U+0041", Print(u'A')); }
dmauro's avatar
dmauro committed
359

360
TEST(PrintCharTest, Char32) { EXPECT_EQ("U+0041", Print(U'A')); }
dmauro's avatar
dmauro committed
361

362
#ifdef __cpp_lib_char8_t
363
TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); }
dmauro's avatar
dmauro committed
364
365
#endif

366
367
368
369
370
371
372
373
374
375
376
// Tests printing other simple, built-in types.

// bool.
TEST(PrintBuiltInTypeTest, Bool) {
  EXPECT_EQ("false", Print(false));
  EXPECT_EQ("true", Print(true));
}

// wchar_t.
TEST(PrintBuiltInTypeTest, Wchar_t) {
  EXPECT_EQ("L'\\0'", Print(L'\0'));
377
378
  EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\''));
  EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"'));
379
  EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?'));
380
  EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\'));
381
382
  EXPECT_EQ("L'\\a' (7)", Print(L'\a'));
  EXPECT_EQ("L'\\b' (8)", Print(L'\b'));
383
384
385
  EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f'));
  EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n'));
  EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r'));
386
  EXPECT_EQ("L'\\t' (9)", Print(L'\t'));
387
  EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v'));
388
389
  EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F'));
  EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF'));
390
391
  EXPECT_EQ("L' ' (32, 0x20)", Print(L' '));
  EXPECT_EQ("L'a' (97, 0x61)", Print(L'a'));
392
393
  EXPECT_EQ("L'\\x576' (1398)", Print(static_cast<wchar_t>(0x576)));
  EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D)));
394
395
}

Abseil Team's avatar
Abseil Team committed
396
// Test that int64_t provides more storage than wchar_t.
397
TEST(PrintTypeSizeTest, Wchar_t) {
Abseil Team's avatar
Abseil Team committed
398
  EXPECT_LT(sizeof(wchar_t), sizeof(int64_t));
399
400
401
402
403
404
}

// Various integer types.
TEST(PrintBuiltInTypeTest, Integer) {
  EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255)));  // uint8
  EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128)));  // int8
405
406
  EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max()));     // uint16
  EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min()));     // int16
Abseil Team's avatar
Abseil Team committed
407
408
409
410
  EXPECT_EQ("4294967295",
            Print(std::numeric_limits<uint32_t>::max()));  // uint32
  EXPECT_EQ("-2147483648",
            Print(std::numeric_limits<int32_t>::min()));  // int32
411
  EXPECT_EQ("18446744073709551615",
Abseil Team's avatar
Abseil Team committed
412
            Print(std::numeric_limits<uint64_t>::max()));  // uint64
413
  EXPECT_EQ("-9223372036854775808",
Abseil Team's avatar
Abseil Team committed
414
            Print(std::numeric_limits<int64_t>::min()));  // int64
415
#ifdef __cpp_lib_char8_t
dmauro's avatar
dmauro committed
416
417
418
419
420
421
422
423
424
425
426
427
428
  EXPECT_EQ("U+0000",
            Print(std::numeric_limits<char8_t>::min()));  // char8_t
  EXPECT_EQ("U+00FF",
            Print(std::numeric_limits<char8_t>::max()));  // char8_t
#endif
  EXPECT_EQ("U+0000",
            Print(std::numeric_limits<char16_t>::min()));  // char16_t
  EXPECT_EQ("U+FFFF",
            Print(std::numeric_limits<char16_t>::max()));  // char16_t
  EXPECT_EQ("U+0000",
            Print(std::numeric_limits<char32_t>::min()));  // char32_t
  EXPECT_EQ("U+FFFFFFFF",
            Print(std::numeric_limits<char32_t>::max()));  // char32_t
429
430
431
432
433
}

// Size types.
TEST(PrintBuiltInTypeTest, Size_t) {
  EXPECT_EQ("1", Print(sizeof('a')));  // size_t.
434
#ifndef GTEST_OS_WINDOWS
435
436
  // Windows has no ssize_t type.
  EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2)));  // ssize_t.
437
#endif                                               // !GTEST_OS_WINDOWS
438
439
}

Abseil Team's avatar
Abseil Team committed
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// gcc/clang __{u,}int128_t values.
#if defined(__SIZEOF_INT128__)
TEST(PrintBuiltInTypeTest, Int128) {
  // Small ones
  EXPECT_EQ("0", Print(__int128_t{0}));
  EXPECT_EQ("0", Print(__uint128_t{0}));
  EXPECT_EQ("12345", Print(__int128_t{12345}));
  EXPECT_EQ("12345", Print(__uint128_t{12345}));
  EXPECT_EQ("-12345", Print(__int128_t{-12345}));

  // Large ones
  EXPECT_EQ("340282366920938463463374607431768211455", Print(~__uint128_t{}));
  __int128_t max_128 = static_cast<__int128_t>(~__uint128_t{} / 2);
  EXPECT_EQ("-170141183460469231731687303715884105728", Print(~max_128));
  EXPECT_EQ("170141183460469231731687303715884105727", Print(max_128));
}
#endif  // __SIZEOF_INT128__

458
459
// Floating-points.
TEST(PrintBuiltInTypeTest, FloatingPoints) {
460
461
462
  // float (32-bit precision)
  EXPECT_EQ("1.5", Print(1.5f));

Tom Hughes's avatar
Tom Hughes committed
463
464
  EXPECT_EQ("1.0999999", Print(1.09999990f));
  EXPECT_EQ("1.1", Print(1.10000002f));
465
  EXPECT_EQ("1.10000014", Print(1.10000014f));
Tom Hughes's avatar
Tom Hughes committed
466
  EXPECT_EQ("9e+09", Print(9e9f));
467
468

  // double
469
470
471
  EXPECT_EQ("-2.5", Print(-2.5));  // double
}

Abseil Team's avatar
Abseil Team committed
472
473
474
475
476
477
478
479
480
481
#if GTEST_HAS_RTTI
TEST(PrintBuiltInTypeTest, TypeInfo) {
  struct MyStruct {};
  auto res = Print(typeid(MyStruct{}));
  // We can't guarantee that we can demangle the name, but either name should
  // contain the substring "MyStruct".
  EXPECT_NE(res.find("MyStruct"), res.npos) << res;
}
#endif  // GTEST_HAS_RTTI

482
483
484
// Since ::std::stringstream::operator<<(const void *) formats the pointer
// output differently with different compilers, we have to create the expected
// output first and use it as our expectation.
485
static std::string PrintPointer(const void* p) {
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
  ::std::stringstream expected_result_stream;
  expected_result_stream << p;
  return expected_result_stream.str();
}

// Tests printing C strings.

// const char*.
TEST(PrintCStringTest, Const) {
  const char* p = "World";
  EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
}

// char*.
TEST(PrintCStringTest, NonConst) {
  char p[] = "Hi";
  EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
            Print(static_cast<char*>(p)));
}

// NULL C string.
TEST(PrintCStringTest, Null) {
508
  const char* p = nullptr;
509
510
511
512
513
  EXPECT_EQ("NULL", Print(p));
}

// Tests that C strings are escaped properly.
TEST(PrintCStringTest, EscapesProperly) {
514
  const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
515
516
517
  EXPECT_EQ(PrintPointer(p) +
                " pointing to \"'\\\"?\\\\\\a\\b\\f"
                "\\n\\r\\t\\v\\x7F\\xFF a\"",
518
519
520
            Print(p));
}

521
#ifdef __cpp_lib_char8_t
Abseil Team's avatar
Abseil Team committed
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
// const char8_t*.
TEST(PrintU8StringTest, Const) {
  const char8_t* p = u8"界";
  EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE7\\x95\\x8C\"", Print(p));
}

// char8_t*.
TEST(PrintU8StringTest, NonConst) {
  char8_t p[] = u8"世";
  EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE4\\xB8\\x96\"",
            Print(static_cast<char8_t*>(p)));
}

// NULL u8 string.
TEST(PrintU8StringTest, Null) {
  const char8_t* p = nullptr;
  EXPECT_EQ("NULL", Print(p));
}

// Tests that u8 strings are escaped properly.
TEST(PrintU8StringTest, EscapesProperly) {
  const char8_t* p = u8"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
  EXPECT_EQ(PrintPointer(p) +
                " pointing to u8\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
                "hello \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
            Print(p));
}
#endif

// const char16_t*.
TEST(PrintU16StringTest, Const) {
  const char16_t* p = u"界";
  EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x754C\"", Print(p));
}

// char16_t*.
TEST(PrintU16StringTest, NonConst) {
  char16_t p[] = u"世";
  EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x4E16\"",
            Print(static_cast<char16_t*>(p)));
}

// NULL u16 string.
TEST(PrintU16StringTest, Null) {
  const char16_t* p = nullptr;
  EXPECT_EQ("NULL", Print(p));
}

// Tests that u16 strings are escaped properly.
TEST(PrintU16StringTest, EscapesProperly) {
  const char16_t* p = u"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
  EXPECT_EQ(PrintPointer(p) +
                " pointing to u\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
                "hello \\x4E16\\x754C\"",
            Print(p));
}

// const char32_t*.
TEST(PrintU32StringTest, Const) {
  const char32_t* p = U"🗺️";
  EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F5FA\\xFE0F\"", Print(p));
}

// char32_t*.
TEST(PrintU32StringTest, NonConst) {
  char32_t p[] = U"🌌";
  EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F30C\"",
            Print(static_cast<char32_t*>(p)));
}

// NULL u32 string.
TEST(PrintU32StringTest, Null) {
  const char32_t* p = nullptr;
  EXPECT_EQ("NULL", Print(p));
}

// Tests that u32 strings are escaped properly.
TEST(PrintU32StringTest, EscapesProperly) {
  const char32_t* p = U"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 🗺️";
  EXPECT_EQ(PrintPointer(p) +
                " pointing to U\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
                "hello \\x1F5FA\\xFE0F\"",
            Print(p));
}

607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
// possibly accessing more memory than intended and causing invalid
// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
// wchar_t is implemented as a native type.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)

// const wchar_t*.
TEST(PrintWideCStringTest, Const) {
  const wchar_t* p = L"World";
  EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
}

// wchar_t*.
TEST(PrintWideCStringTest, NonConst) {
  wchar_t p[] = L"Hi";
  EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
            Print(static_cast<wchar_t*>(p)));
}

// NULL wide C string.
TEST(PrintWideCStringTest, Null) {
630
  const wchar_t* p = nullptr;
631
632
633
634
635
  EXPECT_EQ("NULL", Print(p));
}

// Tests that wide C strings are escaped properly.
TEST(PrintWideCStringTest, EscapesProperly) {
636
637
638
639
640
641
  const wchar_t s[] = {'\'',  '"',   '?',    '\\', '\a', '\b',
                       '\f',  '\n',  '\r',   '\t', '\v', 0xD3,
                       0x576, 0x8D3, 0xC74D, ' ',  'a',  '\0'};
  EXPECT_EQ(PrintPointer(s) +
                " pointing to L\"'\\\"?\\\\\\a\\b\\f"
                "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
642
            Print(static_cast<const wchar_t*>(s)));
643
644
645
646
647
648
649
650
651
}
#endif  // native wchar_t

// Tests printing pointers to other char types.

// signed char*.
TEST(PrintCharPointerTest, SignedChar) {
  signed char* p = reinterpret_cast<signed char*>(0x1234);
  EXPECT_EQ(PrintPointer(p), Print(p));
652
  p = nullptr;
653
654
655
656
657
658
659
  EXPECT_EQ("NULL", Print(p));
}

// const signed char*.
TEST(PrintCharPointerTest, ConstSignedChar) {
  signed char* p = reinterpret_cast<signed char*>(0x1234);
  EXPECT_EQ(PrintPointer(p), Print(p));
660
  p = nullptr;
661
662
663
664
665
666
667
  EXPECT_EQ("NULL", Print(p));
}

// unsigned char*.
TEST(PrintCharPointerTest, UnsignedChar) {
  unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
  EXPECT_EQ(PrintPointer(p), Print(p));
668
  p = nullptr;
669
670
671
672
673
674
675
  EXPECT_EQ("NULL", Print(p));
}

// const unsigned char*.
TEST(PrintCharPointerTest, ConstUnsignedChar) {
  const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
  EXPECT_EQ(PrintPointer(p), Print(p));
676
  p = nullptr;
677
678
679
680
681
682
683
684
685
  EXPECT_EQ("NULL", Print(p));
}

// Tests printing pointers to simple, built-in types.

// bool*.
TEST(PrintPointerToBuiltInTypeTest, Bool) {
  bool* p = reinterpret_cast<bool*>(0xABCD);
  EXPECT_EQ(PrintPointer(p), Print(p));
686
  p = nullptr;
687
688
689
690
691
692
693
  EXPECT_EQ("NULL", Print(p));
}

// void*.
TEST(PrintPointerToBuiltInTypeTest, Void) {
  void* p = reinterpret_cast<void*>(0xABCD);
  EXPECT_EQ(PrintPointer(p), Print(p));
694
  p = nullptr;
695
696
697
698
699
700
701
  EXPECT_EQ("NULL", Print(p));
}

// const void*.
TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
  const void* p = reinterpret_cast<const void*>(0xABCD);
  EXPECT_EQ(PrintPointer(p), Print(p));
702
  p = nullptr;
703
704
705
706
707
708
709
  EXPECT_EQ("NULL", Print(p));
}

// Tests printing pointers to pointers.
TEST(PrintPointerToPointerTest, IntPointerPointer) {
  int** p = reinterpret_cast<int**>(0xABCD);
  EXPECT_EQ(PrintPointer(p), Print(p));
710
  p = nullptr;
711
712
713
714
715
716
717
718
719
720
721
722
  EXPECT_EQ("NULL", Print(p));
}

// Tests printing (non-member) function pointers.

void MyFunction(int /* n */) {}

TEST(PrintPointerTest, NonMemberFunctionPointer) {
  // We cannot directly cast &MyFunction to const void* because the
  // standard disallows casting between pointers to functions and
  // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
  // this limitation.
723
724
725
  EXPECT_EQ(PrintPointer(reinterpret_cast<const void*>(
                reinterpret_cast<internal::BiggestInt>(&MyFunction))),
            Print(&MyFunction));
726
727
728
729
730
731
732
733
  int (*p)(bool) = NULL;  // NOLINT
  EXPECT_EQ("NULL", Print(p));
}

// An assertion predicate determining whether a one string is a prefix for
// another.
template <typename StringType>
AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
734
  if (str.find(prefix, 0) == 0) return AssertionSuccess();
735
736
737
738

  const bool is_wide_string = sizeof(prefix[0]) > 1;
  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  return AssertionFailure()
739
740
         << begin_string_quote << prefix << "\" is not a prefix of "
         << begin_string_quote << str << "\"\n";
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
}

// Tests printing member variable pointers.  Although they are called
// pointers, they don't point to a location in the address space.
// Their representation is implementation-defined.  Thus they will be
// printed as raw bytes.

struct Foo {
 public:
  virtual ~Foo() {}
  int MyMethod(char x) { return x + 1; }
  virtual char MyVirtualMethod(int /* n */) { return 'a'; }

  int value;
};

TEST(PrintPointerTest, MemberVariablePointer) {
  EXPECT_TRUE(HasPrefix(Print(&Foo::value),
                        Print(sizeof(&Foo::value)) + "-byte object "));
760
  int Foo::*p = NULL;  // NOLINT
761
  EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
762
763
764
765
766
767
768
769
770
771
772
773
774
}

// Tests printing member function pointers.  Although they are called
// pointers, they don't point to a location in the address space.
// Their representation is implementation-defined.  Thus they will be
// printed as raw bytes.
TEST(PrintPointerTest, MemberFunctionPointer) {
  EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
                        Print(sizeof(&Foo::MyMethod)) + "-byte object "));
  EXPECT_TRUE(
      HasPrefix(Print(&Foo::MyVirtualMethod),
                Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
  int (Foo::*p)(char) = NULL;  // NOLINT
775
  EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
776
777
778
779
780
781
782
}

// Tests printing C arrays.

// The difference between this and Print() is that it ensures that the
// argument is a reference to an array.
template <typename T, size_t N>
783
std::string PrintArrayHelper(T (&a)[N]) {
784
785
786
787
788
  return Print(a);
}

// One-dimensional array.
TEST(PrintArrayTest, OneDimensionalArray) {
789
  int a[5] = {1, 2, 3, 4, 5};
790
791
792
793
794
  EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
}

// Two-dimensional array.
TEST(PrintArrayTest, TwoDimensionalArray) {
795
  int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
796
797
798
799
800
  EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
}

// Array of const elements.
TEST(PrintArrayTest, ConstArray) {
801
  const bool a[1] = {false};
802
803
804
  EXPECT_EQ("{ false }", PrintArrayHelper(a));
}

805
806
807
// char array without terminating NUL.
TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
  // Array a contains '\0' in the middle and doesn't end with '\0'.
808
  char a[] = {'H', '\0', 'i'};
809
810
811
  EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
}

Abseil Team's avatar
Abseil Team committed
812
813
// char array with terminating NUL.
TEST(PrintArrayTest, CharArrayWithTerminatingNul) {
814
815
816
817
  const char a[] = "\0Hi";
  EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
}

818
#ifdef __cpp_lib_char8_t
Abseil Team's avatar
Abseil Team committed
819
820
// char_t array without terminating NUL.
TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
821
  // Array a contains '\0' in the middle and doesn't end with '\0'.
Abseil Team's avatar
Abseil Team committed
822
823
  const char8_t a[] = {u8'H', u8'\0', u8'i'};
  EXPECT_EQ("u8\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
824
825
}

Abseil Team's avatar
Abseil Team committed
826
827
828
// char8_t array with terminating NUL.
TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {
  const char8_t a[] = u8"\0世界";
829
  EXPECT_EQ("u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", PrintArrayHelper(a));
dmauro's avatar
dmauro committed
830
831
832
}
#endif

Abseil Team's avatar
Abseil Team committed
833
834
835
836
837
838
// const char16_t array without terminating NUL.
TEST(PrintArrayTest, Char16ArrayWithNoTerminatingNul) {
  // Array a contains '\0' in the middle and doesn't end with '\0'.
  const char16_t a[] = {u'こ', u'\0', u'ん', u'に', u'ち', u'は'};
  EXPECT_EQ("u\"\\x3053\\0\\x3093\\x306B\\x3061\\x306F\" (no terminating NUL)",
            PrintArrayHelper(a));
dmauro's avatar
dmauro committed
839
840
}

Abseil Team's avatar
Abseil Team committed
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
// char16_t array with terminating NUL.
TEST(PrintArrayTest, Char16ArrayWithTerminatingNul) {
  const char16_t a[] = u"\0こんにちは";
  EXPECT_EQ("u\"\\0\\x3053\\x3093\\x306B\\x3061\\x306F\"", PrintArrayHelper(a));
}

// char32_t array without terminating NUL.
TEST(PrintArrayTest, Char32ArrayWithNoTerminatingNul) {
  // Array a contains '\0' in the middle and doesn't end with '\0'.
  const char32_t a[] = {U'👋', U'\0', U'🌌'};
  EXPECT_EQ("U\"\\x1F44B\\0\\x1F30C\" (no terminating NUL)",
            PrintArrayHelper(a));
}

// char32_t array with terminating NUL.
TEST(PrintArrayTest, Char32ArrayWithTerminatingNul) {
  const char32_t a[] = U"\0👋🌌";
  EXPECT_EQ("U\"\\0\\x1F44B\\x1F30C\"", PrintArrayHelper(a));
}

// wchar_t array without terminating NUL.
TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
  // Array a contains '\0' in the middle and doesn't end with '\0'.
  const wchar_t a[] = {L'H', L'\0', L'i'};
  EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
}

// wchar_t array with terminating NUL.
TEST(PrintArrayTest, WCharArrayWithTerminatingNul) {
  const wchar_t a[] = L"\0Hi";
  EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
dmauro's avatar
dmauro committed
872
873
}

874
875
// Array of objects.
TEST(PrintArrayTest, ObjectArray) {
876
  std::string a[3] = {"Hi", "Hello", "Ni hao"};
877
878
879
880
881
  EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
}

// Array with many elements.
TEST(PrintArrayTest, BigArray) {
882
  int a[100] = {1, 2, 3};
883
884
885
886
887
888
889
890
  EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
            PrintArrayHelper(a));
}

// Tests printing ::string and ::std::string.

// ::std::string.
TEST(PrintStringTest, StringInStdNamespace) {
891
  const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
892
  const ::std::string str(s, sizeof(s));
893
  EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
894
895
896
            Print(str));
}

897
898
899
900
901
TEST(PrintStringTest, StringAmbiguousHex) {
  // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
  // '\x6', '\x6B', or '\x6BA'.

  // a hex escaping sequence following by a decimal digit
902
903
  EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12"
                                                    "3")));
904
  // a hex escaping sequence following by a hex digit (lower-case)
905
906
  EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6"
                                                          "bananas")));
907
  // a hex escaping sequence following by a hex digit (upper-case)
908
909
  EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6"
                                                          "BANANA")));
910
911
912
913
  // a hex escaping sequence following by a non-xdigit
  EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
}

Abseil Team's avatar
Abseil Team committed
914
// Tests printing ::std::wstring.
915
916
917
#if GTEST_HAS_STD_WSTRING
// ::std::wstring.
TEST(PrintWideStringTest, StringInStdNamespace) {
918
  const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
919
920
921
922
923
  const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t));
  EXPECT_EQ(
      "L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
      "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
      Print(str));
924
}
925
926
927

TEST(PrintWideStringTest, StringAmbiguousHex) {
  // same for wide strings.
928
929
930
931
932
933
  EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12"
                                                       L"3")));
  EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", Print(::std::wstring(L"mm\x6"
                                                             L"bananas")));
  EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", Print(::std::wstring(L"NOM\x6"
                                                             L"BANANA")));
934
935
  EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
}
936
937
#endif  // GTEST_HAS_STD_WSTRING

938
#ifdef __cpp_lib_char8_t
dmauro's avatar
dmauro committed
939
TEST(PrintStringTest, U8String) {
Abseil Team's avatar
Abseil Team committed
940
  std::u8string str = u8"Hello, 世界";
dmauro's avatar
dmauro committed
941
  EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type.
Abseil Team's avatar
Abseil Team committed
942
  EXPECT_EQ("u8\"Hello, \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", Print(str));
dmauro's avatar
dmauro committed
943
944
945
946
947
948
}
#endif

TEST(PrintStringTest, U16String) {
  std::u16string str = u"Hello, 世界";
  EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type.
Abseil Team's avatar
Abseil Team committed
949
  EXPECT_EQ("u\"Hello, \\x4E16\\x754C\"", Print(str));
dmauro's avatar
dmauro committed
950
951
952
}

TEST(PrintStringTest, U32String) {
Abseil Team's avatar
Abseil Team committed
953
954
955
  std::u32string str = U"Hello, 🗺️";
  EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type
  EXPECT_EQ("U\"Hello, \\x1F5FA\\xFE0F\"", Print(str));
dmauro's avatar
dmauro committed
956
957
}

958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
// Tests printing types that support generic streaming (i.e. streaming
// to std::basic_ostream<Char, CharTraits> for any valid Char and
// CharTraits types).

// Tests printing a non-template type that supports generic streaming.

class AllowsGenericStreaming {};

template <typename Char, typename CharTraits>
std::basic_ostream<Char, CharTraits>& operator<<(
    std::basic_ostream<Char, CharTraits>& os,
    const AllowsGenericStreaming& /* a */) {
  return os << "AllowsGenericStreaming";
}

TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
  AllowsGenericStreaming a;
  EXPECT_EQ("AllowsGenericStreaming", Print(a));
}

// Tests printing a template type that supports generic streaming.

template <typename T>
class AllowsGenericStreamingTemplate {};

template <typename Char, typename CharTraits, typename T>
std::basic_ostream<Char, CharTraits>& operator<<(
    std::basic_ostream<Char, CharTraits>& os,
    const AllowsGenericStreamingTemplate<T>& /* a */) {
  return os << "AllowsGenericStreamingTemplate";
}

TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
  AllowsGenericStreamingTemplate<int> a;
  EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
}

// Tests printing a type that supports generic streaming and can be
// implicitly converted to another printable type.

template <typename T>
class AllowsGenericStreamingAndImplicitConversionTemplate {
 public:
  operator bool() const { return false; }
};

template <typename Char, typename CharTraits, typename T>
std::basic_ostream<Char, CharTraits>& operator<<(
    std::basic_ostream<Char, CharTraits>& os,
    const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
  return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
}

TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
  AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
  EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
}

Abseil Team's avatar
Abseil Team committed
1016
#if GTEST_INTERNAL_HAS_STRING_VIEW
1017

Abseil Team's avatar
Abseil Team committed
1018
// Tests printing internal::StringView.
1019

Gennadiy Civil's avatar
Gennadiy Civil committed
1020
TEST(PrintStringViewTest, SimpleStringView) {
Abseil Team's avatar
Abseil Team committed
1021
  const internal::StringView sp = "Hello";
1022
1023
1024
  EXPECT_EQ("\"Hello\"", Print(sp));
}

Gennadiy Civil's avatar
Gennadiy Civil committed
1025
TEST(PrintStringViewTest, UnprintableCharacters) {
1026
  const char str[] = "NUL (\0) and \r\t";
Abseil Team's avatar
Abseil Team committed
1027
  const internal::StringView sp(str, sizeof(str) - 1);
1028
1029
1030
  EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
}

Abseil Team's avatar
Abseil Team committed
1031
#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047

// Tests printing STL containers.

TEST(PrintStlContainerTest, EmptyDeque) {
  deque<char> empty;
  EXPECT_EQ("{}", Print(empty));
}

TEST(PrintStlContainerTest, NonEmptyDeque) {
  deque<int> non_empty;
  non_empty.push_back(1);
  non_empty.push_back(3);
  EXPECT_EQ("{ 1, 3 }", Print(non_empty));
}

TEST(PrintStlContainerTest, OneElementHashMap) {
Gennadiy Civil's avatar
Gennadiy Civil committed
1048
  ::std::unordered_map<int, char> map1;
1049
  map1[1] = 'a';
1050
  EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
1051
1052
1053
}

TEST(PrintStlContainerTest, HashMultiMap) {
Gennadiy Civil's avatar
Gennadiy Civil committed
1054
  ::std::unordered_multimap<int, bool> map1;
1055
1056
1057
1058
  map1.insert(make_pair(5, true));
  map1.insert(make_pair(5, false));

  // Elements of hash_multimap can be printed in any order.
1059
  const std::string result = Print(map1);
1060
1061
  EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
              result == "{ (5, false), (5, true) }")
1062
      << " where Print(map1) returns \"" << result << "\".";
1063
1064
1065
}

TEST(PrintStlContainerTest, HashSet) {
Gennadiy Civil's avatar
Gennadiy Civil committed
1066
  ::std::unordered_set<int> set1;
1067
1068
  set1.insert(1);
  EXPECT_EQ("{ 1 }", Print(set1));
1069
1070
1071
1072
}

TEST(PrintStlContainerTest, HashMultiSet) {
  const int kSize = 5;
1073
  int a[kSize] = {1, 1, 2, 5, 1};
Gennadiy Civil's avatar
Gennadiy Civil committed
1074
  ::std::unordered_multiset<int> set1(a, a + kSize);
1075
1076

  // Elements of hash_multiset can be printed in any order.
1077
1078
  const std::string result = Print(set1);
  const std::string expected_pattern = "{ d, d, d, d, d }";  // d means a digit.
1079
1080
1081
1082
1083
1084
1085

  // Verifies the result matches the expected pattern; also extracts
  // the numbers in the result.
  ASSERT_EQ(expected_pattern.length(), result.length());
  std::vector<int> numbers;
  for (size_t i = 0; i != result.length(); i++) {
    if (expected_pattern[i] == 'd') {
1086
      ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
1087
1088
      numbers.push_back(result[i] - '0');
    } else {
1089
1090
      EXPECT_EQ(expected_pattern[i], result[i])
          << " where result is " << result;
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
    }
  }

  // Makes sure the result contains the right numbers.
  std::sort(numbers.begin(), numbers.end());
  std::sort(a, a + kSize);
  EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
}

TEST(PrintStlContainerTest, List) {
1101
1102
  const std::string a[] = {"hello", "world"};
  const list<std::string> strings(a, a + 2);
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
  EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
}

TEST(PrintStlContainerTest, Map) {
  map<int, bool> map1;
  map1[1] = true;
  map1[5] = false;
  map1[3] = true;
  EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
}

TEST(PrintStlContainerTest, MultiMap) {
  multimap<bool, int> map1;
1116
1117
1118
1119
1120
1121
1122
1123
1124
  // The make_pair template function would deduce the type as
  // pair<bool, int> here, and since the key part in a multimap has to
  // be constant, without a templated ctor in the pair class (as in
  // libCstd on Solaris), make_pair call would fail to compile as no
  // implicit conversion is found.  Thus explicit typename is used
  // here instead.
  map1.insert(pair<const bool, int>(true, 0));
  map1.insert(pair<const bool, int>(true, 1));
  map1.insert(pair<const bool, int>(false, 2));
1125
1126
1127
1128
  EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
}

TEST(PrintStlContainerTest, Set) {
1129
  const unsigned int a[] = {3, 0, 5};
1130
1131
1132
1133
1134
  set<unsigned int> set1(a, a + 3);
  EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
}

TEST(PrintStlContainerTest, MultiSet) {
1135
  const int a[] = {1, 1, 2, 5, 1};
1136
1137
1138
1139
  multiset<int> set1(a, a + 5);
  EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
}

kosak's avatar
kosak committed
1140
TEST(PrintStlContainerTest, SinglyLinkedList) {
1141
  int a[] = {9, 2, 8};
kosak's avatar
kosak committed
1142
1143
1144
1145
  const std::forward_list<int> ints(a, a + 3);
  EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
}

1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
TEST(PrintStlContainerTest, Pair) {
  pair<const bool, int> p(true, 5);
  EXPECT_EQ("(true, 5)", Print(p));
}

TEST(PrintStlContainerTest, Vector) {
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  EXPECT_EQ("{ 1, 2 }", Print(v));
}

TEST(PrintStlContainerTest, LongSequence) {
1159
  const int a[100] = {1, 2, 3};
1160
  const vector<int> v(a, a + 100);
1161
1162
1163
1164
  EXPECT_EQ(
      "{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
      "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }",
      Print(v));
1165
1166
1167
}

TEST(PrintStlContainerTest, NestedContainer) {
1168
1169
  const int a1[] = {1, 2};
  const int a2[] = {3, 4, 5};
1170
1171
1172
  const list<int> l1(a1, a1 + 2);
  const list<int> l2(a2, a2 + 3);

1173
  vector<list<int>> v;
1174
1175
1176
1177
1178
1179
  v.push_back(l1);
  v.push_back(l2);
  EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
}

TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
1180
  const int a[3] = {1, 2, 3};
billydonahue's avatar
billydonahue committed
1181
  NativeArray<int> b(a, 3, RelationToSourceReference());
1182
1183
1184
1185
  EXPECT_EQ("{ 1, 2, 3 }", Print(b));
}

TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
1186
  const int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
billydonahue's avatar
billydonahue committed
1187
  NativeArray<int[3]> b(a, 2, RelationToSourceReference());
1188
1189
1190
  EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
}

1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
// Tests that a class named iterator isn't treated as a container.

struct iterator {
  char x;
};

TEST(PrintStlContainerTest, Iterator) {
  iterator it = {};
  EXPECT_EQ("1-byte object <00>", Print(it));
}

// Tests that a class named const_iterator isn't treated as a container.

struct const_iterator {
  char x;
};

TEST(PrintStlContainerTest, ConstIterator) {
  const_iterator it = {};
  EXPECT_EQ("1-byte object <00>", Print(it));
}

1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
// Tests printing ::std::tuples.

// Tuples of various arities.
TEST(PrintStdTupleTest, VariousSizes) {
  ::std::tuple<> t0;
  EXPECT_EQ("()", Print(t0));

  ::std::tuple<int> t1(5);
  EXPECT_EQ("(5)", Print(t1));

  ::std::tuple<char, bool> t2('a', true);
  EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));

  ::std::tuple<bool, int, int> t3(false, 2, 3);
  EXPECT_EQ("(false, 2, 3)", Print(t3));

  ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
  EXPECT_EQ("(false, 2, 3, 4)", Print(t4));

  const char* const str = "8";
Abseil Team's avatar
Abseil Team committed
1233
1234
  ::std::tuple<bool, char, short, int32_t, int64_t, float, double,  // NOLINT
               const char*, void*, std::string>
Gennadiy Civil's avatar
 
Gennadiy Civil committed
1235
      t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str,  // NOLINT
Abseil Team's avatar
Abseil Team committed
1236
          nullptr, "10");
1237
  EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1238
                " pointing to \"8\", NULL, \"10\")",
1239
1240
1241
1242
1243
            Print(t10));
}

// Nested tuples.
TEST(PrintStdTupleTest, NestedTuple) {
1244
1245
  ::std::tuple<::std::tuple<int, bool>, char> nested(::std::make_tuple(5, true),
                                                     'a');
1246
1247
1248
  EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
}

1249
TEST(PrintNullptrT, Basic) { EXPECT_EQ("(nullptr)", Print(nullptr)); }
Abseil Team's avatar
Abseil Team committed
1250
1251
1252

TEST(PrintReferenceWrapper, Printable) {
  int x = 5;
Abseil Team's avatar
Abseil Team committed
1253
1254
  EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::ref(x)));
  EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::cref(x)));
Abseil Team's avatar
Abseil Team committed
1255
1256
1257
1258
}

TEST(PrintReferenceWrapper, Unprintable) {
  ::foo::UnprintableInFoo up;
Abseil Team's avatar
Abseil Team committed
1259
1260
1261
1262
1263
1264
1265
1266
  EXPECT_EQ(
      "@" + PrintPointer(&up) +
          " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
      Print(std::ref(up)));
  EXPECT_EQ(
      "@" + PrintPointer(&up) +
          " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
      Print(std::cref(up)));
Abseil Team's avatar
Abseil Team committed
1267
1268
}

1269
1270
1271
1272
// Tests printing user-defined unprintable types.

// Unprintable types in the global namespace.
TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1273
  EXPECT_EQ("1-byte object <00>", Print(UnprintableTemplateInGlobal<char>()));
1274
1275
1276
1277
}

// Unprintable types in a user namespace.
TEST(PrintUnprintableTypeTest, InUserNamespace) {
1278
  EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
            Print(::foo::UnprintableInFoo()));
}

// Unprintable types are that too big to be printed completely.

struct Big {
  Big() { memset(array, 0, sizeof(array)); }
  char array[257];
};

TEST(PrintUnpritableTypeTest, BigObject) {
1290
1291
1292
1293
1294
1295
1296
1297
1298
  EXPECT_EQ(
      "257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
      "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
      Print(Big()));
1299
1300
1301
1302
1303
1304
}

// Tests printing user-defined streamable types.

// Streamable types in the global namespace.
TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1305
1306
1307
  StreamableInGlobal x;
  EXPECT_EQ("StreamableInGlobal", Print(x));
  EXPECT_EQ("StreamableInGlobal*", Print(&x));
1308
1309
1310
1311
1312
1313
1314
1315
}

// Printable template types in a user namespace.
TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
  EXPECT_EQ("StreamableTemplateInFoo: 0",
            Print(::foo::StreamableTemplateInFoo<int>()));
}

Abseil Team's avatar
Abseil Team committed
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
TEST(PrintStreamableTypeTest, TypeInUserNamespaceWithTemplatedStreamOperator) {
  EXPECT_EQ("TemplatedStreamableInFoo",
            Print(::foo::TemplatedStreamableInFoo()));
}

TEST(PrintStreamableTypeTest, SubclassUsesSuperclassStreamOperator) {
  ParentClass parent;
  ChildClassWithStreamOperator child_stream;
  ChildClassWithoutStreamOperator child_no_stream;
  EXPECT_EQ("ParentClass", Print(parent));
  EXPECT_EQ("ChildClassWithStreamOperator", Print(child_stream));
  EXPECT_EQ("ParentClass", Print(child_no_stream));
}

1330
1331
1332
1333
1334
// Tests printing a user-defined recursive container type that has a <<
// operator.
TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
  ::foo::PathLike x;
  EXPECT_EQ("Streamable-PathLike", Print(x));
1335
1336
  const ::foo::PathLike cx;
  EXPECT_EQ("Streamable-PathLike", Print(cx));
1337
1338
}

1339
1340
// Tests printing user-defined types that have a PrintTo() function.
TEST(PrintPrintableTypeTest, InUserNamespace) {
1341
  EXPECT_EQ("PrintableViaPrintTo: 0", Print(::foo::PrintableViaPrintTo()));
1342
1343
}

1344
1345
1346
1347
1348
1349
1350
// Tests printing a pointer to a user-defined type that has a <<
// operator for its pointer.
TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
  ::foo::PointerPrintable x;
  EXPECT_EQ("PointerPrintable*", Print(&x));
}

1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
// Tests printing user-defined class template that have a PrintTo() function.
TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
  EXPECT_EQ("PrintableViaPrintToTemplate: 5",
            Print(::foo::PrintableViaPrintToTemplate<int>(5)));
}

// Tests that the universal printer prints both the address and the
// value of a reference.
TEST(PrintReferenceTest, PrintsAddressAndValue) {
  int n = 5;
  EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));

1363
  int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
1364
1365
1366
1367
  EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
            PrintByRef(a));

  const ::foo::UnprintableInFoo x;
1368
1369
1370
  EXPECT_EQ("@" + PrintPointer(&x) +
                " 16-byte object "
                "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1371
1372
1373
1374
1375
1376
1377
            PrintByRef(x));
}

// Tests that the universal printer prints a function pointer passed by
// reference.
TEST(PrintReferenceTest, HandlesFunctionPointer) {
  void (*fp)(int n) = &MyFunction;
1378
  const std::string fp_pointer_string =
1379
1380
1381
1382
1383
      PrintPointer(reinterpret_cast<const void*>(&fp));
  // We cannot directly cast &MyFunction to const void* because the
  // standard disallows casting between pointers to functions and
  // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
  // this limitation.
1384
  const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
1385
      reinterpret_cast<internal::BiggestInt>(fp)));
1386
  EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp));
1387
1388
1389
1390
1391
1392
}

// Tests that the universal printer prints a member function pointer
// passed by reference.
TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
  int (Foo::*p)(char ch) = &Foo::MyMethod;
1393
1394
1395
  EXPECT_TRUE(HasPrefix(PrintByRef(p),
                        "@" + PrintPointer(reinterpret_cast<const void*>(&p)) +
                            " " + Print(sizeof(p)) + "-byte object "));
1396
1397

  char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1398
1399
1400
  EXPECT_TRUE(HasPrefix(PrintByRef(p2),
                        "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) +
                            " " + Print(sizeof(p2)) + "-byte object "));
1401
1402
1403
1404
1405
}

// Tests that the universal printer prints a member variable pointer
// passed by reference.
TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1406
  int Foo::*p = &Foo::value;  // NOLINT
1407
1408
  EXPECT_TRUE(HasPrefix(PrintByRef(p), "@" + PrintPointer(&p) + " " +
                                           Print(sizeof(p)) + "-byte object "));
1409
1410
}

1411
1412
1413
1414
1415
1416
// Tests that FormatForComparisonFailureMessage(), which is used to print
// an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion
// fails, formats the operand in the desired way.

// scalar
TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
1417
  EXPECT_STREQ("123", FormatForComparisonFailureMessage(123, 124).c_str());
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
}

// non-char pointer
TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
  int n = 0;
  EXPECT_EQ(PrintPointer(&n),
            FormatForComparisonFailureMessage(&n, &n).c_str());
}

// non-char array
TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
  // In expression 'array == x', 'array' is compared by pointer.
  // Therefore we want to print an array operand as a pointer.
1431
1432
  int n[] = {1, 2, 3};
  EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str());
1433
1434
1435
}

// Tests formatting a char pointer when it's compared with another pointer.
Troy Holsapple's avatar
Troy Holsapple committed
1436
// In this case we want to print it as a raw pointer, as the comparison is by
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
// pointer.

// char pointer vs pointer
TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
  // In expression 'p == x', where 'p' and 'x' are (const or not) char
  // pointers, the operands are compared by pointer.  Therefore we
  // want to print 'p' as a pointer instead of a C string (we don't
  // even know if it's supposed to point to a valid C string).

  // const char*
  const char* s = "hello";
1448
  EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464

  // char*
  char ch = 'a';
  EXPECT_EQ(PrintPointer(&ch),
            FormatForComparisonFailureMessage(&ch, &ch).c_str());
}

// wchar_t pointer vs pointer
TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
  // In expression 'p == x', where 'p' and 'x' are (const or not) char
  // pointers, the operands are compared by pointer.  Therefore we
  // want to print 'p' as a pointer instead of a wide C string (we don't
  // even know if it's supposed to point to a valid wide C string).

  // const wchar_t*
  const wchar_t* s = L"hello";
1465
  EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510

  // wchar_t*
  wchar_t ch = L'a';
  EXPECT_EQ(PrintPointer(&ch),
            FormatForComparisonFailureMessage(&ch, &ch).c_str());
}

// Tests formatting a char pointer when it's compared to a string object.
// In this case we want to print the char pointer as a C string.

// char pointer vs std::string
TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {
  const char* s = "hello \"world";
  EXPECT_STREQ("\"hello \\\"world\"",  // The string content should be escaped.
               FormatForComparisonFailureMessage(s, ::std::string()).c_str());

  // char*
  char str[] = "hi\1";
  char* p = str;
  EXPECT_STREQ("\"hi\\x1\"",  // The string content should be escaped.
               FormatForComparisonFailureMessage(p, ::std::string()).c_str());
}

#if GTEST_HAS_STD_WSTRING
// wchar_t pointer vs std::wstring
TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {
  const wchar_t* s = L"hi \"world";
  EXPECT_STREQ("L\"hi \\\"world\"",  // The string content should be escaped.
               FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());

  // wchar_t*
  wchar_t str[] = L"hi\1";
  wchar_t* p = str;
  EXPECT_STREQ("L\"hi\\x1\"",  // The string content should be escaped.
               FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());
}
#endif

// Tests formatting a char array when it's compared with a pointer or array.
// In this case we want to print the array as a row pointer, as the comparison
// is by pointer.

// char array vs pointer
TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {
  char str[] = "hi \"world\"";
1511
  char* p = nullptr;
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
  EXPECT_EQ(PrintPointer(str),
            FormatForComparisonFailureMessage(str, p).c_str());
}

// char array vs char array
TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {
  const char str[] = "hi \"world\"";
  EXPECT_EQ(PrintPointer(str),
            FormatForComparisonFailureMessage(str, str).c_str());
}

// wchar_t array vs pointer
TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {
  wchar_t str[] = L"hi \"world\"";
1526
  wchar_t* p = nullptr;
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
  EXPECT_EQ(PrintPointer(str),
            FormatForComparisonFailureMessage(str, p).c_str());
}

// wchar_t array vs wchar_t array
TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {
  const wchar_t str[] = L"hi \"world\"";
  EXPECT_EQ(PrintPointer(str),
            FormatForComparisonFailureMessage(str, str).c_str());
}

// Tests formatting a char array when it's compared with a string object.
// In this case we want to print the array as a C string.

// char array vs std::string
TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {
  const char str[] = "hi \"world\"";
  EXPECT_STREQ("\"hi \\\"world\\\"\"",  // The content should be escaped.
               FormatForComparisonFailureMessage(str, ::std::string()).c_str());
}

#if GTEST_HAS_STD_WSTRING
// wchar_t array vs std::wstring
TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
  const wchar_t str[] = L"hi \"w\0rld\"";
  EXPECT_STREQ(
      "L\"hi \\\"w\"",  // The content should be escaped.
                        // Embedded NUL terminates the string.
      FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());
}
#endif

1559
1560
1561
// Useful for testing PrintToString().  We cannot use EXPECT_EQ()
// there as its implementation uses PrintToString().  The caller must
// ensure that 'value' has no side effect.
1562
1563
#define EXPECT_PRINT_TO_STRING_(value, expected_string)  \
  EXPECT_TRUE(PrintToString(value) == (expected_string)) \
1564
1565
      << " where " #value " prints as " << (PrintToString(value))

1566
TEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, "123"); }
1567
1568
1569

TEST(PrintToStringTest, WorksForPointerToConstChar) {
  const char* p = "hello";
1570
  EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1571
1572
1573
1574
1575
}

TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
  char s[] = "hello";
  char* p = s;
1576
  EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1577
1578
}

1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
TEST(PrintToStringTest, EscapesForPointerToConstChar) {
  const char* p = "hello\n";
  EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\"");
}

TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
  char s[] = "hello\1";
  char* p = s;
  EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\"");
}

1590
TEST(PrintToStringTest, WorksForArray) {
1591
  int n[3] = {1, 2, 3};
1592
  EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1593
1594
}

1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
TEST(PrintToStringTest, WorksForCharArray) {
  char s[] = "hello";
  EXPECT_PRINT_TO_STRING_(s, "\"hello\"");
}

TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
  const char str_with_nul[] = "hello\0 world";
  EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\"");

  char mutable_str_with_nul[] = "hello\0 world";
  EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
}

1608
TEST(PrintToStringTest, ContainsNonLatin) {
1609
  // Test with valid UTF-8. Prints both in hex and as text.
Gennadiy Civil's avatar
Gennadiy Civil committed
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
  std::string non_ascii_str = ::std::string("오전 4:30");
  EXPECT_PRINT_TO_STRING_(non_ascii_str,
                          "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
                          "    As Text: \"오전 4:30\"");
  non_ascii_str = ::std::string("From ä — ẑ");
  EXPECT_PRINT_TO_STRING_(non_ascii_str,
                          "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
                          "\n    As Text: \"From ä — ẑ\"");
}

1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
TEST(PrintToStringTest, PrintStreamableInLocal) {
  EXPECT_STREQ("StreamableInLocal",
               PrintToString(foo::StreamableInLocal()).c_str());
}

TEST(PrintToStringTest, PrintReferenceToStreamableInLocal) {
  foo::StreamableInLocal s;
  std::reference_wrapper<foo::StreamableInLocal> r(s);
  EXPECT_STREQ("StreamableInLocal", PrintToString(r).c_str());
}

TEST(PrintToStringTest, PrintReferenceToStreamableInGlobal) {
  StreamableInGlobal s;
  std::reference_wrapper<StreamableInGlobal> r(s);
  EXPECT_STREQ("StreamableInGlobal", PrintToString(r).c_str());
}

Gennadiy Civil's avatar
Gennadiy Civil committed
1637
1638
1639
1640
1641
TEST(IsValidUTF8Test, IllFormedUTF8) {
  // The following test strings are ill-formed UTF-8 and are printed
  // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
  // expected to fail, thus output does not contain "As Text:".

1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
  static const char* const kTestdata[][2] = {
      // 2-byte lead byte followed by a single-byte character.
      {"\xC3\x74", "\"\\xC3t\""},
      // Valid 2-byte character followed by an orphan trail byte.
      {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
      // Lead byte without trail byte.
      {"abc\xC3", "\"abc\\xC3\""},
      // 3-byte lead byte, single-byte character, orphan trail byte.
      {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
      // Truncated 3-byte character.
      {"\xE2\x80", "\"\\xE2\\x80\""},
      // Truncated 3-byte character followed by valid 2-byte char.
      {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
      // Truncated 3-byte character followed by a single-byte character.
      {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
      // 3-byte lead byte followed by valid 3-byte character.
      {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
      // 4-byte lead byte followed by valid 3-byte character.
      {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
      // Truncated 4-byte character.
      {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
      // Invalid UTF-8 byte sequences embedded in other chars.
      {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
      {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
       "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
      // Non-shortest UTF-8 byte sequences are also ill-formed.
      // The classics: xC0, xC1 lead byte.
      {"\xC0\x80", "\"\\xC0\\x80\""},
      {"\xC1\x81", "\"\\xC1\\x81\""},
      // Non-shortest sequences.
      {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
      {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
      // Last valid code point before surrogate range, should be printed as
      // text,
      // too.
      {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n    As Text: \"\""},
      // Start of surrogate lead. Surrogates are not printed as text.
      {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
      // Last non-private surrogate lead.
      {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
      // First private-use surrogate lead.
      {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
      // Last private-use surrogate lead.
      {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
      // Mid-point of surrogate trail.
      {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
      // First valid code point after surrogate range, should be printed as
      // text,
      // too.
      {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n    As Text: \"\""}};

  for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) {
Gennadiy Civil's avatar
Gennadiy Civil committed
1694
1695
1696
1697
    EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
  }
}

1698
1699
#undef EXPECT_PRINT_TO_STRING_

1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
TEST(UniversalTersePrintTest, WorksForNonReference) {
  ::std::stringstream ss;
  UniversalTersePrint(123, &ss);
  EXPECT_EQ("123", ss.str());
}

TEST(UniversalTersePrintTest, WorksForReference) {
  const int& n = 123;
  ::std::stringstream ss;
  UniversalTersePrint(n, &ss);
  EXPECT_EQ("123", ss.str());
}

TEST(UniversalTersePrintTest, WorksForCString) {
  const char* s1 = "abc";
  ::std::stringstream ss1;
  UniversalTersePrint(s1, &ss1);
  EXPECT_EQ("\"abc\"", ss1.str());

  char* s2 = const_cast<char*>(s1);
  ::std::stringstream ss2;
  UniversalTersePrint(s2, &ss2);
  EXPECT_EQ("\"abc\"", ss2.str());

1724
  const char* s3 = nullptr;
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
  ::std::stringstream ss3;
  UniversalTersePrint(s3, &ss3);
  EXPECT_EQ("NULL", ss3.str());
}

TEST(UniversalPrintTest, WorksForNonReference) {
  ::std::stringstream ss;
  UniversalPrint(123, &ss);
  EXPECT_EQ("123", ss.str());
}

TEST(UniversalPrintTest, WorksForReference) {
  const int& n = 123;
  ::std::stringstream ss;
  UniversalPrint(n, &ss);
  EXPECT_EQ("123", ss.str());
}

Abseil Team's avatar
Abseil Team committed
1743
1744
1745
1746
1747
1748
1749
TEST(UniversalPrintTest, WorksForPairWithConst) {
  std::pair<const Wrapper<std::string>, int> p(Wrapper<std::string>("abc"), 1);
  ::std::stringstream ss;
  UniversalPrint(p, &ss);
  EXPECT_EQ("(Wrapper(\"abc\"), 1)", ss.str());
}

1750
1751
1752
1753
TEST(UniversalPrintTest, WorksForCString) {
  const char* s1 = "abc";
  ::std::stringstream ss1;
  UniversalPrint(s1, &ss1);
1754
  EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str()));
1755
1756
1757
1758

  char* s2 = const_cast<char*>(s1);
  ::std::stringstream ss2;
  UniversalPrint(s2, &ss2);
1759
  EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str()));
1760

1761
  const char* s3 = nullptr;
1762
1763
1764
1765
1766
  ::std::stringstream ss3;
  UniversalPrint(s3, &ss3);
  EXPECT_EQ("NULL", ss3.str());
}

1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
TEST(UniversalPrintTest, WorksForCharArray) {
  const char str[] = "\"Line\0 1\"\nLine 2";
  ::std::stringstream ss1;
  UniversalPrint(str, &ss1);
  EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str());

  const char mutable_str[] = "\"Line\0 1\"\nLine 2";
  ::std::stringstream ss2;
  UniversalPrint(mutable_str, &ss2);
  EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
}
1778

Abseil Team's avatar
Abseil Team committed
1779
1780
1781
1782
1783
1784
1785
TEST(UniversalPrintTest, IncompleteType) {
  struct Incomplete;
  char some_object = 0;
  EXPECT_EQ("(incomplete type)",
            PrintToString(reinterpret_cast<Incomplete&>(some_object)));
}

Abseil Team's avatar
Abseil Team committed
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
TEST(UniversalPrintTest, SmartPointers) {
  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
  std::unique_ptr<int> p(new int(17));
  EXPECT_EQ("(ptr = " + PrintPointer(p.get()) + ", value = 17)",
            PrintToString(p));
  std::unique_ptr<int[]> p2(new int[2]);
  EXPECT_EQ("(" + PrintPointer(p2.get()) + ")", PrintToString(p2));

  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
  std::shared_ptr<int> p3(new int(1979));
  EXPECT_EQ("(ptr = " + PrintPointer(p3.get()) + ", value = 1979)",
            PrintToString(p3));
1798
1799
#if defined(__cpp_lib_shared_ptr_arrays) && \
    (__cpp_lib_shared_ptr_arrays >= 201611L)
Abseil Team's avatar
Abseil Team committed
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
  std::shared_ptr<int[]> p4(new int[2]);
  EXPECT_EQ("(" + PrintPointer(p4.get()) + ")", PrintToString(p4));
#endif

  // modifiers
  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile const int>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int[]>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int[]>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int[]>()));
  EXPECT_EQ("(nullptr)",
            PrintToString(std::unique_ptr<volatile const int[]>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile const int>()));
1818
1819
#if defined(__cpp_lib_shared_ptr_arrays) && \
    (__cpp_lib_shared_ptr_arrays >= 201611L)
Abseil Team's avatar
Abseil Team committed
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int[]>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int[]>()));
  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int[]>()));
  EXPECT_EQ("(nullptr)",
            PrintToString(std::shared_ptr<volatile const int[]>()));
#endif

  // void
  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<void, void (*)(void*)>(
                             nullptr, nullptr)));
  EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
            PrintToString(
                std::unique_ptr<void, void (*)(void*)>(p.get(), [](void*) {})));
  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<void>()));
  EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
            PrintToString(std::shared_ptr<void>(p.get(), [](void*) {})));
}

1838
1839
1840
1841
1842
1843
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
  Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
  EXPECT_EQ(0u, result.size());
}

TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
1844
1845
  Strings result =
      UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1));
1846
1847
1848
1849
1850
  ASSERT_EQ(1u, result.size());
  EXPECT_EQ("1", result[0]);
}

TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
1851
1852
  Strings result =
      UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a'));
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
  ASSERT_EQ(2u, result.size());
  EXPECT_EQ("1", result[0]);
  EXPECT_EQ("'a' (97, 0x61)", result[1]);
}

TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
  const int n = 1;
  Strings result = UniversalTersePrintTupleFieldsToStrings(
      ::std::tuple<const int&, const char*>(n, "a"));
  ASSERT_EQ(2u, result.size());
  EXPECT_EQ("1", result[0]);
  EXPECT_EQ("\"a\"", result[1]);
}

1867
#if GTEST_INTERNAL_HAS_ANY
1868
1869
1870
1871
1872
1873
1874
class PrintAnyTest : public ::testing::Test {
 protected:
  template <typename T>
  static std::string ExpectedTypeName() {
#if GTEST_HAS_RTTI
    return internal::GetTypeName<T>();
#else
1875
    return "<unknown_type>";
1876
1877
1878
1879
1880
#endif  // GTEST_HAS_RTTI
  }
};

TEST_F(PrintAnyTest, Empty) {
1881
  internal::Any any;
1882
  EXPECT_EQ("no value", PrintToString(any));
1883
1884
}

1885
TEST_F(PrintAnyTest, NonEmpty) {
1886
1887
1888
1889
1890
  internal::Any any;
  constexpr int val1 = 10;
  const std::string val2 = "content";

  any = val1;
1891
  EXPECT_EQ("value of type " + ExpectedTypeName<int>(), PrintToString(any));
1892
1893

  any = val2;
1894
  EXPECT_EQ("value of type " + ExpectedTypeName<std::string>(),
1895
1896
1897
            PrintToString(any));
}
#endif  // GTEST_INTERNAL_HAS_ANY
1898

1899
#if GTEST_INTERNAL_HAS_OPTIONAL
1900
TEST(PrintOptionalTest, Basic) {
Abseil Team's avatar
Abseil Team committed
1901
  EXPECT_EQ("(nullopt)", PrintToString(internal::Nullopt()));
1902
  internal::Optional<int> value;
1903
1904
1905
  EXPECT_EQ("(nullopt)", PrintToString(value));
  value = {7};
  EXPECT_EQ("(7)", PrintToString(value));
1906
1907
  EXPECT_EQ("(1.1)", PrintToString(internal::Optional<double>{1.1}));
  EXPECT_EQ("(\"A\")", PrintToString(internal::Optional<std::string>{"A"}));
1908
}
1909
#endif  // GTEST_INTERNAL_HAS_OPTIONAL
1910

1911
#if GTEST_INTERNAL_HAS_VARIANT
1912
1913
1914
1915
1916
struct NonPrintable {
  unsigned char contents = 17;
};

TEST(PrintOneofTest, Basic) {
1917
  using Type = internal::Variant<int, StreamableInGlobal, NonPrintable>;
1918
1919
  EXPECT_EQ("('int(index = 0)' with value 7)", PrintToString(Type(7)));
  EXPECT_EQ("('StreamableInGlobal(index = 1)' with value StreamableInGlobal)",
1920
1921
            PrintToString(Type(StreamableInGlobal{})));
  EXPECT_EQ(
1922
1923
      "('testing::gtest_printers_test::NonPrintable(index = 2)' with value "
      "1-byte object <11>)",
1924
1925
      PrintToString(Type(NonPrintable{})));
}
1926
#endif  // GTEST_INTERNAL_HAS_VARIANT
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
namespace {
class string_ref;

/**
 * This is a synthetic pointer to a fixed size string.
 */
class string_ptr {
 public:
  string_ptr(const char* data, size_t size) : data_(data), size_(size) {}

  string_ptr& operator++() noexcept {
    data_ += size_;
    return *this;
  }

  string_ref operator*() const noexcept;

 private:
  const char* data_;
  size_t size_;
};

/**
 * This is a synthetic reference of a fixed size string.
 */
class string_ref {
 public:
  string_ref(const char* data, size_t size) : data_(data), size_(size) {}

  string_ptr operator&() const noexcept { return {data_, size_}; }  // NOLINT

  bool operator==(const char* s) const noexcept {
    if (size_ > 0 && data_[size_ - 1] != 0) {
      return std::string(data_, size_) == std::string(s);
    } else {
      return std::string(data_) == std::string(s);
    }
  }

 private:
  const char* data_;
  size_t size_;
};

string_ref string_ptr::operator*() const noexcept { return {data_, size_}; }

TEST(string_ref, compare) {
  const char* s = "alex\0davidjohn\0";
  string_ptr ptr(s, 5);
  EXPECT_EQ(*ptr, "alex");
  EXPECT_TRUE(*ptr == "alex");
  ++ptr;
  EXPECT_EQ(*ptr, "david");
  EXPECT_TRUE(*ptr == "david");
  ++ptr;
  EXPECT_EQ(*ptr, "john");
}

}  // namespace
1986

1987
1988
}  // namespace gtest_printers_test
}  // namespace testing