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.jupiter.api.Assertions;
37 import org.junit.jupiter.api.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 Assertions.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 Assertions.assertThrows(IOException.class, () -> out.write(tmp));
69 Assertions.assertThrows(IOException.class, () -> out.write(1));
70 }
71
72 @Test
73 public void testBasicWrite() throws Exception {
74 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
75 final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16);
76 final OutputStream out = new IdentityOutputStream(outbuffer, outputStream);
77 out.write(new byte[] {'a', 'b'}, 0, 2);
78 out.write('c');
79 out.flush();
80
81 final byte[] input = outputStream.toByteArray();
82
83 Assertions.assertNotNull(input);
84 final byte[] expected = new byte[] {'a', 'b', 'c'};
85 Assertions.assertEquals(expected.length, input.length);
86 for (int i = 0; i < expected.length; i++) {
87 Assertions.assertEquals(expected[i], input[i]);
88 }
89 out.close();
90 }
91
92 @Test
93 public void testClosedCondition() throws Exception {
94 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
95 final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16);
96 final OutputStream out = new IdentityOutputStream(outbuffer, outputStream);
97 out.close();
98 out.close();
99 final byte[] tmp = new byte[2];
100 Assertions.assertThrows(StreamClosedException.class, () -> out.write(tmp, 0, tmp.length));
101 Assertions.assertThrows(StreamClosedException.class, () -> out.write('a'));
102 }
103
104 }
105