1 // Copyright 2012 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.
5 #include "base/base64.h"
7 #include "base/numerics/checked_math.h"
8 #include "base/test/gtest_util.h"
9 #include "testing/gmock/include/gmock/gmock.h"
10 #include "testing/gtest/include/gtest/gtest.h"
11 #include "third_party/modp_b64/modp_b64.h"
15 TEST(Base64Test, Basic) {
16 const std::string kText = "hello world";
17 const std::string kBase64Text = "aGVsbG8gd29ybGQ=";
23 Base64Encode(kText, &encoded);
24 EXPECT_EQ(kBase64Text, encoded);
26 ok = Base64Decode(encoded, &decoded);
28 EXPECT_EQ(kText, decoded);
31 TEST(Base64Test, Binary) {
32 const uint8_t kData[] = {0x00, 0x01, 0xFE, 0xFF};
34 std::string binary_encoded = Base64Encode(kData);
36 // Check that encoding the same data through the StringPiece interface gives
38 std::string string_piece_encoded;
39 Base64Encode(StringPiece(reinterpret_cast<const char*>(kData), sizeof(kData)),
40 &string_piece_encoded);
42 EXPECT_EQ(binary_encoded, string_piece_encoded);
44 EXPECT_THAT(Base64Decode(binary_encoded),
45 testing::Optional(testing::ElementsAreArray(kData)));
46 EXPECT_FALSE(Base64Decode("invalid base64!"));
48 std::string encoded_with_prefix = "PREFIX";
49 Base64EncodeAppend(kData, &encoded_with_prefix);
50 EXPECT_EQ(encoded_with_prefix, "PREFIX" + binary_encoded);
53 TEST(Base64Test, InPlace) {
54 const std::string kText = "hello world";
55 const std::string kBase64Text = "aGVsbG8gd29ybGQ=";
56 std::string text(kText);
58 Base64Encode(text, &text);
59 EXPECT_EQ(kBase64Text, text);
61 bool ok = Base64Decode(text, &text);
63 EXPECT_EQ(text, kText);
66 TEST(Base64Test, Overflow) {
67 // `Base64Encode` makes the input larger, which means inputs whose base64
68 // output overflows `size_t`. Actually allocating a span of this size will
69 // likely fail, but we test it with a fake span and assume a correct
70 // implementation will check for overflow before touching the input.
72 // Note that, with or without an overflow check, the function will still
73 // crash. This test is only meaningful because `EXPECT_CHECK_DEATH` looks for
74 // a `CHECK`-based failure.
76 auto large_span = base::make_span(&b, MODP_B64_MAX_INPUT_LEN + 1);
77 EXPECT_CHECK_DEATH(Base64Encode(large_span));
79 std::string output = "PREFIX";
80 EXPECT_CHECK_DEATH(Base64EncodeAppend(large_span, &output));
82 // `modp_b64_encode_len` is a macro, so check `MODP_B64_MAX_INPUT_LEN` is
83 // correct be verifying the computation doesn't overflow.
84 base::CheckedNumeric<size_t> max_len = MODP_B64_MAX_INPUT_LEN;
85 EXPECT_TRUE(modp_b64_encode_len(max_len).IsValid());