View Javadoc
1   /*
2    * Copyright (C) 2017, 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  package org.eclipse.jgit.diff;
11  
12  import org.eclipse.jgit.errors.BinaryBlobException;
13  import org.eclipse.jgit.internal.storage.file.FileRepository;
14  import org.eclipse.jgit.junit.RepositoryTestCase;
15  import org.eclipse.jgit.lib.Constants;
16  import org.eclipse.jgit.lib.ObjectId;
17  import org.eclipse.jgit.lib.ObjectInserter;
18  import org.eclipse.jgit.lib.ObjectLoader;
19  import org.junit.Assert;
20  import org.junit.Test;
21  
22  import java.io.IOException;
23  
24  public class RawTextLoadTest extends RepositoryTestCase {
25  	private static byte[] generate(int size, int nullAt) {
26  		byte[] data = new byte[size];
27  		for (int i = 0; i < data.length; i++) {
28  			data[i] = (byte) ((i % 72 == 0) ? '\n' : (i%10) + '0');
29  		}
30  		if (nullAt >= 0) {
31  			data[nullAt] = '\0';
32  		}
33  		return data;
34  	}
35  
36  	private RawText textFor(byte[] data, int limit) throws IOException, BinaryBlobException {
37  		FileRepository repo = createBareRepository();
38  		ObjectId id;
39  		try (ObjectInserter ins = repo.getObjectDatabase().newInserter()) {
40  			id = ins.insert(Constants.OBJ_BLOB, data);
41  		}
42  		ObjectLoader ldr = repo.open(id);
43  		return RawText.load(ldr, limit);
44  	}
45  
46  	@Test
47  	public void testSmallOK() throws Exception {
48  		byte[] data = generate(1000, -1);
49  		RawText result = textFor(data, 1 << 20);
50  		Assert.assertArrayEquals(result.content, data);
51  	}
52  
53  	@Test(expected = BinaryBlobException.class)
54  	public void testSmallNull() throws Exception {
55  		byte[] data = generate(1000, 22);
56  		textFor(data, 1 << 20);
57  	}
58  
59  	@Test
60  	public void testBigOK() throws Exception {
61  		byte[] data = generate(10000, -1);
62  		RawText result = textFor(data, 1 << 20);
63  		Assert.assertArrayEquals(result.content, data);
64  	}
65  
66  	@Test(expected = BinaryBlobException.class)
67  	public void testBigWithNullAtStart() throws Exception {
68  		byte[] data = generate(10000, 22);
69  		textFor(data, 1 << 20);
70  	}
71  
72  	@Test(expected = BinaryBlobException.class)
73  	public void testBinaryThreshold() throws Exception {
74  		byte[] data = generate(2 << 20, -1);
75  		textFor(data, 1 << 20);
76  	}
77  }