1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package libcore.util; 18 19import java.nio.charset.StandardCharsets; 20import java.util.Arrays; 21import junit.framework.TestCase; 22import static libcore.util.HexEncoding.decode; 23import static libcore.util.HexEncoding.encode; 24 25public class HexEncodingTest extends TestCase { 26 public void testEncode() { 27 final byte[] avocados = "avocados".getBytes(StandardCharsets.UTF_8); 28 29 assertArraysEqual("61766F6361646F73".toCharArray(), encode(avocados)); 30 assertArraysEqual(avocados, decode(encode(avocados), false)); 31 // Make sure we can handle lower case hex encodings as well. 32 assertArraysEqual(avocados, decode("61766f6361646f73".toCharArray(), false)); 33 } 34 35 public void testDecode_allow4Bit() { 36 assertArraysEqual(new byte[] { 6 }, decode("6".toCharArray(), true)); 37 assertArraysEqual(new byte[] { 6, 'v' }, decode("676".toCharArray(), true)); 38 } 39 40 public void testDecode_disallow4Bit() { 41 try { 42 decode("676".toCharArray(), false); 43 fail(); 44 } catch (IllegalArgumentException expected) { 45 } 46 } 47 48 public void testDecode_invalid() { 49 try { 50 decode("DEADBARD".toCharArray(), false); 51 fail(); 52 } catch (IllegalArgumentException expected) { 53 } 54 55 // This demonstrates a difference in behaviour from apache commons : apache 56 // commons uses Character.isDigit and would successfully decode a string with 57 // arabic and devanagari characters. 58 try { 59 decode("६१٧٥٥F6361646F73".toCharArray(), false); 60 fail(); 61 } catch (IllegalArgumentException expected) { 62 } 63 64 try { 65 decode("#%6361646F73".toCharArray(), false); 66 fail(); 67 } catch (IllegalArgumentException expected) { 68 } 69 } 70 71 private static void assertArraysEqual(char[] lhs, char[] rhs) { 72 assertEquals(new String(lhs), new String(rhs)); 73 } 74 75 private static void assertArraysEqual(byte[] lhs, byte[] rhs) { 76 assertEquals(Arrays.toString(lhs), Arrays.toString(rhs)); 77 } 78} 79