1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #include <boost/test/unit_test.hpp>
21 #include <thrift/protocol/TBase64Utils.h>
22 
23 using apache::thrift::protocol::base64_encode;
24 using apache::thrift::protocol::base64_decode;
25 
BOOST_AUTO_TEST_SUITE(Base64Test)26 BOOST_AUTO_TEST_SUITE(Base64Test)
27 
28 void setupTestData(int i, uint8_t* data, int& len) {
29   len = 0;
30   do {
31     data[len] = (uint8_t)(i & 0xFF);
32     i >>= 8;
33     len++;
34   } while ((len < 3) && (i != 0));
35 
36   BOOST_ASSERT(i == 0);
37 }
38 
checkEncoding(uint8_t * data,int len)39 void checkEncoding(uint8_t* data, int len) {
40 #ifdef NDEBUG
41   ((void)data);
42 #endif
43 
44   for (int i = 0; i < len; i++) {
45     BOOST_ASSERT(isalnum(data[i]) || data[i] == '/' || data[i] == '+');
46   }
47 }
48 
BOOST_AUTO_TEST_CASE(test_Base64_Encode_Decode)49 BOOST_AUTO_TEST_CASE(test_Base64_Encode_Decode) {
50   int len;
51   uint8_t testInput[3];
52   uint8_t testOutput[4];
53 
54   // Test all possible encoding / decoding cases given the
55   // three byte limit for base64_encode.
56 
57   for (int i = 0xFFFFFF; i >= 0; i--) {
58 
59     // fill testInput based on i
60     setupTestData(i, testInput, len);
61 
62     // encode the test data, then decode it again
63     base64_encode(testInput, len, testOutput);
64 
65     // verify each byte has a valid Base64 value (alphanumeric or either + or /)
66     checkEncoding(testOutput, len);
67 
68     // decode output and check that it matches input
69     base64_decode(testOutput, len + 1);
70     BOOST_ASSERT(0 == memcmp(testInput, testOutput, len));
71   }
72 }
73 
74 BOOST_AUTO_TEST_SUITE_END()
75