View Javadoc
1   /*
2    * Copyright (C) 2010, Google Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.util;
12  
13  import static org.eclipse.jgit.util.Base64.decode;
14  import static org.eclipse.jgit.util.Base64.encodeBytes;
15  import static org.junit.Assert.assertEquals;
16  import static org.junit.Assert.fail;
17  
18  import org.eclipse.jgit.junit.JGitTestUtil;
19  import org.eclipse.jgit.lib.Constants;
20  import org.junit.Test;
21  
22  public class Base64Test {
23  	@Test
24  	public void testEncode() {
25  		assertEquals("aGkK", encodeBytes(b("hi\n")));
26  		assertEquals("AAECDQoJcQ==", encodeBytes(b("\0\1\2\r\n\tq")));
27  	}
28  
29  	@Test
30  	public void testDecode() {
31  		JGitTestUtil.assertEquals(b("hi\n"), decode("aGkK"));
32  		JGitTestUtil.assertEquals(b("\0\1\2\r\n\tq"), decode("AAECDQoJcQ=="));
33  		JGitTestUtil.assertEquals(b("\0\1\2\r\n\tq"),
34  				decode("A A E\tC D\rQ o\nJ c Q=="));
35  		JGitTestUtil.assertEquals(b("\u000EB"), decode("DkL="));
36  	}
37  
38  	@Test
39  	public void testDecodeFail_NonBase64Character() {
40  		try {
41  			decode("! a bad base64 string !");
42  			fail("Accepted bad string in decode");
43  		} catch (IllegalArgumentException fail) {
44  			// Expected
45  		}
46  	}
47  
48  	@Test
49  	public void testEncodeMatchesDecode() {
50  		String[] testStrings = { "", //
51  				"cow", //
52  				"a", //
53  				"a secret string", //
54  				"\0\1\2\r\n\t" //
55  		};
56  		for (String e : testStrings)
57  			JGitTestUtil.assertEquals(b(e), decode(encodeBytes(b(e))));
58  	}
59  
60  	private static byte[] b(String str) {
61  		return Constants.encode(str);
62  	}
63  
64  }