summaryrefslogtreecommitdiff
path: root/test/base64.cc
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2025-10-19 00:08:11 +0200
committerJoel Klinghed <the_jk@spawned.biz>2025-10-19 00:19:30 +0200
commitdf56d2eb26b34b0af590f3aedfda7896f4b103dd (patch)
treef58c38e7ed25c2cec3f0fc16d7c8a75806c0d569 /test/base64.cc
parent800bdbb18617dfac36067b8841781a92b19d57c1 (diff)
base64: Add new module
Encodes and decodes base64. No linebreaks, always padding.
Diffstat (limited to 'test/base64.cc')
-rw-r--r--test/base64.cc70
1 files changed, 70 insertions, 0 deletions
diff --git a/test/base64.cc b/test/base64.cc
new file mode 100644
index 0000000..47cdfa4
--- /dev/null
+++ b/test/base64.cc
@@ -0,0 +1,70 @@
+#include "base64.hh"
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <gtest/gtest.h>
+#include <iterator>
+#include <vector>
+
+TEST(Base64, empty) {
+ auto str = base64::encode({});
+ EXPECT_EQ("", str);
+
+ auto data = base64::decode("");
+ ASSERT_TRUE(data.has_value());
+ EXPECT_TRUE(data->empty());
+}
+
+TEST(Base64, all_bytes) {
+ std::vector<uint8_t> in;
+ in.push_back(0);
+ for (uint8_t i = 0; i < 255; ++i) {
+ in.push_back(i + 1);
+ }
+ auto str = base64::encode(in);
+ EXPECT_EQ(
+ "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1"
+ "Njc4"
+ "OTo7PD0+"
+ "P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3Bx"
+ "cnN0dXZ3eHl6e3x9fn+"
+ "AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmq"
+ "q6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/"
+ "g4eLj"
+ "5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==",
+ str);
+
+ auto data = base64::decode(str);
+ ASSERT_TRUE(data.has_value());
+ EXPECT_EQ(in, data.value());
+}
+
+TEST(Base64, rfc) {
+ std::string_view in = "foobar";
+ std::vector<std::string_view> expected{
+ "", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy",
+ };
+ for (size_t i = 0; i <= in.size(); ++i) {
+ auto in_part = in.substr(0, i);
+ std::vector<uint8_t> in_bytes;
+ std::ranges::copy(in_part, std::back_inserter(in_bytes));
+ auto str = base64::encode(in_bytes);
+ EXPECT_EQ(expected[i], str);
+ auto data = base64::decode(str);
+ ASSERT_TRUE(data.has_value());
+ EXPECT_EQ(in_bytes, data.value());
+ }
+}
+
+TEST(Base64, invalid) {
+ std::vector<uint8_t> out;
+ EXPECT_FALSE(base64::decode("=", out));
+ EXPECT_FALSE(base64::decode("==", out));
+ EXPECT_FALSE(base64::decode("===", out));
+ EXPECT_FALSE(base64::decode("====", out));
+ EXPECT_FALSE(base64::decode("<>", out));
+ EXPECT_FALSE(base64::decode("Z", out));
+ EXPECT_FALSE(base64::decode("Zg", out));
+ EXPECT_FALSE(base64::decode("Zg=", out));
+}