1   /*
2       This file is part of quExec.
3   
4       quExec is free software; you can redistribute it and/or modify
5       it under the terms of the GNU Lesser General Public License as published by
6       the Free Software Foundation; either version 2 of the License, or
7       (at your option) any later version.
8   
9       quExec is distributed in the hope that it will be useful,
10      but WITHOUT ANY WARRANTY; without even the implied warranty of
11      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12      GNU Lesser General Public License for more details.
13  
14      You should have received a copy of the GNU Lesser General Public License
15      along with quExec; if not, write to the Free Software
16      Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18  
19  package net.sourceforge.quexec.packet.bytes;
20  
21  import java.util.Arrays;
22  import java.util.Random;
23  
24  import static org.junit.Assert.*;
25  import org.junit.Before;
26  import org.junit.Test;
27  
28  public class StoreBytePacketConsumerTest {
29  	
30  	private static final int bufSize = 10;
31  	
32  	private StoreBytePacketConsumer consumer;
33  	
34  	private Random rand;
35  	
36  	@Before
37  	public void runBeforeEveryTest() throws Exception {
38  		this.consumer = new StoreBytePacketConsumer();
39  		this.consumer.setInitialBufferSize(bufSize);
40  		this.rand = new Random(1);
41  	}
42  
43  	@Test
44  	public void dataFitsInBufOneChunk() {
45  		generateAndSendData(bufSize, 2*bufSize);
46  	}
47  	
48  	@Test
49  	public void dataFitsInBufMultipleChunks() {
50  		generateAndSendData(bufSize, 3);
51  	}
52  	
53  	@Test
54  	public void dataDoesNotFitInInitialBufSmallChunks() {
55  		generateAndSendData(9*bufSize + bufSize/2, 5);
56  	}
57  
58  	@Test
59  	public void dataFitsInBufBigChunks() {
60  		generateAndSendData(9*bufSize + bufSize/2, 2*bufSize);
61  	}
62  
63  	private void generateAndSendData(int dataSize, int chunkSize) {
64  		byte[] testData = new byte[dataSize];
65  		this.rand.nextBytes(testData);
66  		
67  		int pos = 0;
68  		while (pos < dataSize - chunkSize) {
69  			assertTrue(this.consumer.consume(chunkSize,
70  					Arrays.copyOfRange(testData, pos, pos + chunkSize)));
71  			pos += chunkSize;
72  		}
73  		assertTrue(this.consumer.consume(dataSize-pos,
74  				Arrays.copyOfRange(testData, pos, dataSize)));
75  		
76  		byte[] consumedBytes = consumer.retrieveData();
77  		
78  		assertEquals(testData.length, consumedBytes.length);
79  		assertTrue(Arrays.equals(testData, consumedBytes));
80  	}
81  }