View Javadoc
1   /*
2    * Copyright (C) 2008, 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.lib;
12  
13  import static org.junit.Assert.assertArrayEquals;
14  import static org.junit.Assert.assertEquals;
15  import static org.junit.Assert.fail;
16  
17  import java.io.UnsupportedEncodingException;
18  
19  import org.junit.Test;
20  
21  public class ConstantsEncodingTest {
22  	@Test
23  	public void testEncodeASCII_SimpleASCII()
24  			throws UnsupportedEncodingException {
25  		final String src = "abc";
26  		final byte[] exp = { 'a', 'b', 'c' };
27  		final byte[] res = Constants.encodeASCII(src);
28  		assertArrayEquals(exp, res);
29  		assertEquals(src, new String(res, 0, res.length, "UTF-8"));
30  	}
31  
32  	@Test
33  	public void testEncodeASCII_FailOnNonASCII() {
34  		final String src = "Ūnĭcōde̽";
35  		try {
36  			Constants.encodeASCII(src);
37  			fail("Incorrectly accepted a Unicode character");
38  		} catch (IllegalArgumentException err) {
39  			assertEquals("Not ASCII string: " + src, err.getMessage());
40  		}
41  	}
42  
43  	@Test
44  	public void testEncodeASCII_Number13() {
45  		final long src = 13;
46  		final byte[] exp = { '1', '3' };
47  		final byte[] res = Constants.encodeASCII(src);
48  		assertArrayEquals(exp, res);
49  	}
50  
51  	@Test
52  	public void testEncode_SimpleASCII() throws UnsupportedEncodingException {
53  		final String src = "abc";
54  		final byte[] exp = { 'a', 'b', 'c' };
55  		final byte[] res = Constants.encode(src);
56  		assertArrayEquals(exp, res);
57  		assertEquals(src, new String(res, 0, res.length, "UTF-8"));
58  	}
59  
60  	@Test
61  	public void testEncode_Unicode() throws UnsupportedEncodingException {
62  		final String src = "Ūnĭcōde̽";
63  		final byte[] exp = { (byte) 0xC5, (byte) 0xAA, 0x6E, (byte) 0xC4,
64  				(byte) 0xAD, 0x63, (byte) 0xC5, (byte) 0x8D, 0x64, 0x65,
65  				(byte) 0xCC, (byte) 0xBD };
66  		final byte[] res = Constants.encode(src);
67  		assertArrayEquals(exp, res);
68  		assertEquals(src, new String(res, 0, res.length, "UTF-8"));
69  	}
70  }