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 static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertFalse;
23  import static org.junit.Assert.assertTrue;
24  import static org.junit.Assert.fail;
25  
26  import java.io.ByteArrayInputStream;
27  import java.util.Arrays;
28  import java.util.Random;
29  
30  import org.junit.Before;
31  import org.junit.Test;
32  
33  public class InputStreamBytePacketProducerTest {
34  	
35  	private static final int bufSize = 10;
36  	private static final int dataWaitTime = 10;
37  	
38  	private StoreBytePacketConsumer consumer;
39  	
40  	private InputStreamBytePacketProducer producer;
41  	
42  	private Random rand;
43  
44  	@Before
45  	public void runBeforeEveryTest() throws Exception {
46  		this.consumer = new StoreBytePacketConsumer();
47  		this.producer = new InputStreamBytePacketProducer();
48  		this.producer.setBufferSize(bufSize);
49  		this.producer.setDataWaitTime(dataWaitTime);
50  		this.producer.addConsumer(this.consumer);
51  		this.rand = new Random(1);
52  	}
53  
54  	@Test
55  	public void readMuchMoreDataThanBufferSize() {
56  		executeTest(bufSize*10);
57  	}
58  	
59  	@Test
60  	public void readSingleByte() {
61  		executeTest(1);
62  	}
63  	
64  	@Test
65  	public void readEmptyStream() {
66  		executeTest(0);
67  	}
68  	
69  	private void executeTest(int dataSize) {
70  		byte[] testData = new byte[dataSize];
71  		this.rand.nextBytes(testData);
72  		
73  		this.producer.setIstream(new ByteArrayInputStream(testData));
74  		
75  		try {
76  			Thread t = new Thread(this.producer);
77  			t.start();
78  
79  			Thread.sleep(dataWaitTime * 10);
80  
81  			t.interrupt();
82  			t.join(1000);
83  			assertFalse(t.isAlive());
84  		}
85  		catch (InterruptedException e) {
86  			fail("unexpected interruption: " + e);
87  		}
88  
89  		byte[] consumedBytes = this.consumer.retrieveData();
90  		
91  		assertEquals(testData.length, consumedBytes.length);
92  		assertTrue(Arrays.equals(testData, consumedBytes));
93  	}
94  
95  }