1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.core5.http.impl.io;
29
30 import java.io.ByteArrayOutputStream;
31 import java.io.IOException;
32 import java.io.OutputStream;
33
34 import org.apache.hc.core5.http.StreamClosedException;
35 import org.apache.hc.core5.http.io.SessionOutputBuffer;
36 import org.junit.Assert;
37 import org.junit.Test;
38
39
40
41
42 public class TestIdentityOutputStream {
43
44 @Test
45 public void testBasics() throws Exception {
46 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
47 final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16);
48 final OutputStream out = new IdentityOutputStream(outbuffer, outputStream);
49
50 final byte[] tmp = new byte[10];
51 out.write(tmp, 0, 10);
52 out.write(tmp);
53 out.write(1);
54 out.flush();
55 out.close();
56 final byte[] data = outputStream.toByteArray();
57 Assert.assertEquals(21, data.length);
58 }
59
60 @Test
61 public void testClose() throws Exception {
62 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
63 final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16);
64 final OutputStream out = new IdentityOutputStream(outbuffer, outputStream);
65 out.close();
66 out.close();
67 final byte[] tmp = new byte[10];
68 try {
69 out.write(tmp);
70 Assert.fail("IOException should have been thrown");
71 } catch (final IOException ex) {
72
73 }
74 try {
75 out.write(1);
76 Assert.fail("IOException should have been thrown");
77 } catch (final IOException ex) {
78
79 }
80 }
81
82 @Test
83 public void testBasicWrite() throws Exception {
84 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
85 final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16);
86 final OutputStream out = new IdentityOutputStream(outbuffer, outputStream);
87 out.write(new byte[] {'a', 'b'}, 0, 2);
88 out.write('c');
89 out.flush();
90
91 final byte[] input = outputStream.toByteArray();
92
93 Assert.assertNotNull(input);
94 final byte[] expected = new byte[] {'a', 'b', 'c'};
95 Assert.assertEquals(expected.length, input.length);
96 for (int i = 0; i < expected.length; i++) {
97 Assert.assertEquals(expected[i], input[i]);
98 }
99 out.close();
100 }
101
102 @Test
103 public void testClosedCondition() throws Exception {
104 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
105 final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16);
106 final OutputStream out = new IdentityOutputStream(outbuffer, outputStream);
107 out.close();
108 out.close();
109
110 try {
111 final byte[] tmp = new byte[2];
112 out.write(tmp, 0, tmp.length);
113 Assert.fail("StreamClosedException expected");
114 } catch (final StreamClosedException expected) {
115 }
116 try {
117 out.write('a');
118 Assert.fail("StreamClosedException expected");
119 } catch (final IOException expected) {
120 }
121 }
122
123 }
124