blob: 873b5656e48668833cef2889fa118259024ae078 [file] [log] [blame]
Jordan Bayles79c6ea22020-12-10 11:12:44 -08001// Copyright 2020 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
5#include "util/base64.h"
6
Jordan Bayles6f3efdb2021-04-06 09:43:46 -07007#include <string>
8#include <vector>
9
Jordan Bayles79c6ea22020-12-10 11:12:44 -080010#include "gtest/gtest.h"
11
12namespace openscreen {
13namespace base64 {
14
15namespace {
16
17constexpr char kText[] = "hello world";
18constexpr char kBase64Text[] = "aGVsbG8gd29ybGQ=";
19
Jordan Bayles34fd6642021-04-06 21:37:26 -070020// More sophisticated comparisons here, such as EXPECT_STREQ, may
21// cause memory failures on some platforms (e.g. ASAN) due to mismatched
22// lengths.
23void CheckEquals(const char* expected, const std::vector<uint8_t>& actual) {
24 EXPECT_EQ(0, std::memcmp(actual.data(), expected, actual.size()));
25}
26
Jordan Bayles79c6ea22020-12-10 11:12:44 -080027void CheckEncodeDecode(const char* to_encode, const char* encode_expected) {
28 std::string encoded = Encode(to_encode);
29 EXPECT_EQ(encode_expected, encoded);
30
Jordan Bayles6f3efdb2021-04-06 09:43:46 -070031 std::vector<uint8_t> decoded;
Jordan Bayles79c6ea22020-12-10 11:12:44 -080032 EXPECT_TRUE(Decode(encoded, &decoded));
Jordan Bayles7e0a4ca2021-04-06 15:42:11 -070033
Jordan Bayles34fd6642021-04-06 21:37:26 -070034 CheckEquals(to_encode, decoded);
Jordan Bayles79c6ea22020-12-10 11:12:44 -080035}
36
37} // namespace
38
39TEST(Base64Test, ZeroSize) {
40 CheckEncodeDecode("", "");
41}
42
43TEST(Base64Test, Basic) {
44 CheckEncodeDecode(kText, kBase64Text);
45}
46
47TEST(Base64Test, Binary) {
48 const uint8_t kData[] = {0x00, 0x01, 0xFE, 0xFF};
49
50 std::string binary_encoded = Encode(absl::MakeConstSpan(kData));
51
52 // Check that encoding the same data through the StringPiece interface gives
53 // the same results.
54 std::string string_piece_encoded = Encode(
55 absl::string_view(reinterpret_cast<const char*>(kData), sizeof(kData)));
56
57 EXPECT_EQ(binary_encoded, string_piece_encoded);
58}
59
60TEST(Base64Test, InPlace) {
61 std::string text(kText);
62
63 text = Encode(text);
64 EXPECT_EQ(kBase64Text, text);
65
Jordan Bayles6f3efdb2021-04-06 09:43:46 -070066 std::vector<uint8_t> out;
67 EXPECT_TRUE(Decode(text, &out));
Jordan Bayles34fd6642021-04-06 21:37:26 -070068 CheckEquals(kText, out);
Jordan Bayles79c6ea22020-12-10 11:12:44 -080069}
70
71} // namespace base64
72} // namespace openscreen