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.chars.consumer;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertTrue;
23  
24  import java.util.Arrays;
25  
26  import net.sourceforge.quexec.packet.chars.consumer.StoreCharPacketConsumer;
27  
28  import org.apache.commons.lang.RandomStringUtils;
29  import org.junit.Before;
30  import org.junit.Test;
31  
32  public class StoreCharPacketConsumerTest {
33  	
34  	private static final int bufSize = 10;
35  	
36  	private StoreCharPacketConsumer consumer;
37  
38  	@Before
39  	public void runBeforeEveryTest() throws Exception {
40  		this.consumer = new StoreCharPacketConsumer();
41  		this.consumer.setInitialBufferSize(bufSize);
42  	}
43  
44  	@Test
45  	public void dataFitsInBufOneChunk() {
46  		generateAndSendData(bufSize, 2*bufSize);
47  	}
48  	
49  	@Test
50  	public void dataFitsInBufMultipleChunks() {
51  		generateAndSendData(bufSize, 3);
52  	}
53  	
54  	@Test
55  	public void dataDoesNotFitInInitialBufSmallChunks() {
56  		generateAndSendData(9*bufSize + bufSize/2, 5);
57  	}
58  
59  	@Test
60  	public void dataFitsInBufBigChunks() {
61  		generateAndSendData(9*bufSize + bufSize/2, 2*bufSize);
62  	}
63  
64  	private void generateAndSendData(int dataSize, int chunkSize) {
65  		String randStr = RandomStringUtils.random(dataSize);
66  		char[] testData = randStr.toCharArray();
67  		
68  		int pos = 0;
69  		while (pos < dataSize - chunkSize) {
70  			assertTrue(this.consumer.consume(chunkSize,
71  					Arrays.copyOfRange(testData, pos, pos + chunkSize)));
72  			pos += chunkSize;
73  		}
74  		assertTrue(this.consumer.consume(dataSize-pos,
75  				Arrays.copyOfRange(testData, pos, dataSize)));
76  		
77  		String consumedChars = this.consumer.retrieveData();
78  		
79  		assertEquals(testData.length, consumedChars.length());
80  		assertEquals(randStr, consumedChars);
81  	}
82  }