base64_unittest.cc 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright (c) 2012 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/base64.h"
  5. #include "testing/gmock/include/gmock/gmock.h"
  6. #include "testing/gtest/include/gtest/gtest.h"
  7. namespace base {
  8. TEST(Base64Test, Basic) {
  9. const std::string kText = "hello world";
  10. const std::string kBase64Text = "aGVsbG8gd29ybGQ=";
  11. std::string encoded;
  12. std::string decoded;
  13. bool ok;
  14. Base64Encode(kText, &encoded);
  15. EXPECT_EQ(kBase64Text, encoded);
  16. ok = Base64Decode(encoded, &decoded);
  17. EXPECT_TRUE(ok);
  18. EXPECT_EQ(kText, decoded);
  19. }
  20. TEST(Base64Test, Binary) {
  21. const uint8_t kData[] = {0x00, 0x01, 0xFE, 0xFF};
  22. std::string binary_encoded = Base64Encode(make_span(kData));
  23. // Check that encoding the same data through the StringPiece interface gives
  24. // the same results.
  25. std::string string_piece_encoded;
  26. Base64Encode(StringPiece(reinterpret_cast<const char*>(kData), sizeof(kData)),
  27. &string_piece_encoded);
  28. EXPECT_EQ(binary_encoded, string_piece_encoded);
  29. EXPECT_THAT(Base64Decode(binary_encoded),
  30. testing::Optional(testing::ElementsAreArray(kData)));
  31. EXPECT_FALSE(Base64Decode("invalid base64!"));
  32. }
  33. TEST(Base64Test, InPlace) {
  34. const std::string kText = "hello world";
  35. const std::string kBase64Text = "aGVsbG8gd29ybGQ=";
  36. std::string text(kText);
  37. Base64Encode(text, &text);
  38. EXPECT_EQ(kBase64Text, text);
  39. bool ok = Base64Decode(text, &text);
  40. EXPECT_TRUE(ok);
  41. EXPECT_EQ(text, kText);
  42. }
  43. } // namespace base