1 // Copyright 2010 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/win/scoped_bstr.h"
6
7 #include <stddef.h>
8
9 #include <iterator>
10
11 #include "testing/gtest/include/gtest/gtest.h"
12
13 namespace base {
14 namespace win {
15
16 namespace {
17
18 constexpr wchar_t kTestString1[] = L"123";
19 constexpr wchar_t kTestString2[] = L"456789";
20 constexpr size_t test1_len = std::size(kTestString1) - 1;
21 constexpr size_t test2_len = std::size(kTestString2) - 1;
22
23 } // namespace
24
TEST(ScopedBstrTest,Empty)25 TEST(ScopedBstrTest, Empty) {
26 ScopedBstr b;
27 EXPECT_EQ(nullptr, b.Get());
28 EXPECT_EQ(0u, b.Length());
29 EXPECT_EQ(0u, b.ByteLength());
30 b.Reset(nullptr);
31 EXPECT_EQ(nullptr, b.Get());
32 EXPECT_EQ(nullptr, b.Release());
33 ScopedBstr b2;
34 b.Swap(b2);
35 EXPECT_EQ(nullptr, b.Get());
36 }
37
TEST(ScopedBstrTest,Basic)38 TEST(ScopedBstrTest, Basic) {
39 ScopedBstr b(kTestString1);
40 EXPECT_EQ(test1_len, b.Length());
41 EXPECT_EQ(test1_len * sizeof(kTestString1[0]), b.ByteLength());
42 }
43
44 namespace {
45
CreateTestString1(BSTR * ret)46 void CreateTestString1(BSTR* ret) {
47 *ret = SysAllocString(kTestString1);
48 }
49
50 } // namespace
51
TEST(ScopedBstrTest,Swap)52 TEST(ScopedBstrTest, Swap) {
53 ScopedBstr b1(kTestString1);
54 ScopedBstr b2;
55 b1.Swap(b2);
56 EXPECT_EQ(test1_len, b2.Length());
57 EXPECT_EQ(0u, b1.Length());
58 EXPECT_STREQ(kTestString1, b2.Get());
59
60 BSTR tmp = b2.Release();
61 EXPECT_NE(nullptr, tmp);
62 EXPECT_STREQ(kTestString1, tmp);
63 EXPECT_EQ(nullptr, b2.Get());
64 SysFreeString(tmp);
65 }
66
TEST(ScopedBstrTest,OutParam)67 TEST(ScopedBstrTest, OutParam) {
68 ScopedBstr b;
69 CreateTestString1(b.Receive());
70 EXPECT_STREQ(kTestString1, b.Get());
71 }
72
TEST(ScopedBstrTest,AllocateBytesAndSetByteLen)73 TEST(ScopedBstrTest, AllocateBytesAndSetByteLen) {
74 constexpr size_t num_bytes = 100;
75 ScopedBstr b;
76 EXPECT_NE(nullptr, b.AllocateBytes(num_bytes));
77 EXPECT_EQ(num_bytes, b.ByteLength());
78 EXPECT_EQ(num_bytes / sizeof(kTestString1[0]), b.Length());
79
80 lstrcpy(b.Get(), kTestString1);
81 EXPECT_EQ(test1_len, static_cast<size_t>(lstrlen(b.Get())));
82 EXPECT_EQ(num_bytes / sizeof(kTestString1[0]), b.Length());
83
84 b.SetByteLen(lstrlen(b.Get()) * sizeof(kTestString2[0]));
85 EXPECT_EQ(b.Length(), static_cast<size_t>(lstrlen(b.Get())));
86 }
87
TEST(ScopedBstrTest,AllocateAndSetByteLen)88 TEST(ScopedBstrTest, AllocateAndSetByteLen) {
89 ScopedBstr b;
90 EXPECT_NE(nullptr, b.Allocate(kTestString2));
91 EXPECT_EQ(test2_len, b.Length());
92
93 b.SetByteLen((test2_len - 1) * sizeof(kTestString2[0]));
94 EXPECT_EQ(test2_len - 1, b.Length());
95 }
96
97 } // namespace win
98 } // namespace base
99