scoped_bstr_unittest.cc 2.4 KB

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