xref: /llvm-project/lldb/unittests/Utility/VASprintfTest.cpp (revision 5706f1e6f6fc9c4c01bfbc2690a9bc40c592985d)
1 //===-- VASprintfTest.cpp ---------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Utility/VASPrintf.h"
11 #include "llvm/ADT/SmallString.h"
12 
13 #include "gtest/gtest.h"
14 
15 #include <locale.h>
16 
17 #if defined (_WIN32)
18 #define TEST_ENCODING ".932"  // On Windows, test codepage 932
19 #else
20 #define TEST_ENCODING "C"     // ...otherwise, any widely available uni-byte LC
21 #endif
22 
23 using namespace lldb_private;
24 using namespace llvm;
25 
26 static bool Sprintf(llvm::SmallVectorImpl<char> &Buffer, const char *Fmt, ...) {
27   va_list args;
28   va_start(args, Fmt);
29   bool Result = VASprintf(Buffer, Fmt, args);
30   va_end(args);
31   return Result;
32 }
33 
34 TEST(VASprintfTest, NoBufferResize) {
35   std::string TestStr("small");
36 
37   llvm::SmallString<32> BigBuffer;
38   ASSERT_TRUE(Sprintf(BigBuffer, "%s", TestStr.c_str()));
39   EXPECT_STREQ(TestStr.c_str(), BigBuffer.c_str());
40   EXPECT_EQ(TestStr.size(), BigBuffer.size());
41 }
42 
43 TEST(VASprintfTest, BufferResize) {
44   std::string TestStr("bigger");
45   llvm::SmallString<4> SmallBuffer;
46   ASSERT_TRUE(Sprintf(SmallBuffer, "%s", TestStr.c_str()));
47   EXPECT_STREQ(TestStr.c_str(), SmallBuffer.c_str());
48   EXPECT_EQ(TestStr.size(), SmallBuffer.size());
49 }
50 
51 TEST(VASprintfTest, EncodingError) {
52   // Save the current locale first.
53   std::string Current(::setlocale(LC_ALL, nullptr));
54 
55   // Ensure tested locale is successfully set
56   ASSERT_TRUE(setlocale(LC_ALL, TEST_ENCODING));
57 
58   wchar_t Invalid[2];
59   Invalid[0] = 0x100;
60   Invalid[1] = 0;
61   llvm::SmallString<32> Buffer;
62   EXPECT_FALSE(Sprintf(Buffer, "%ls", Invalid));
63   EXPECT_EQ("<Encoding error>", Buffer);
64 
65   // Ensure we've restored the original locale once tested
66   ASSERT_TRUE(setlocale(LC_ALL, Current.c_str()));
67 }
68