1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.io.output;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertFalse;
21 import static org.junit.jupiter.api.Assertions.assertTrue;
22 import static org.junit.jupiter.api.Assertions.fail;
23
24 import java.io.IOException;
25 import java.io.OutputStream;
26 import java.util.UUID;
27
28 import org.apache.commons.io.TaggedIOException;
29 import org.junit.jupiter.api.Test;
30
31
32
33
34 public class TaggedOutputStreamTest {
35
36 @Test
37 public void testBrokenStream() {
38 final IOException exception = new IOException("test exception");
39 final TaggedOutputStream stream = new TaggedOutputStream(new BrokenOutputStream(exception));
40
41
42 try {
43 stream.write('x');
44 fail("Expected exception not thrown.");
45 } catch (final IOException e) {
46 assertTrue(stream.isCauseOf(e));
47 try {
48 stream.throwIfCauseOf(e);
49 fail("Expected exception not thrown.");
50 } catch (final IOException e2) {
51 assertEquals(exception, e2);
52 }
53 }
54
55
56 try {
57 stream.flush();
58 fail("Expected exception not thrown.");
59 } catch (final IOException e) {
60 assertTrue(stream.isCauseOf(e));
61 try {
62 stream.throwIfCauseOf(e);
63 fail("Expected exception not thrown.");
64 } catch (final IOException e2) {
65 assertEquals(exception, e2);
66 }
67 }
68
69
70 try {
71 stream.close();
72 fail("Expected exception not thrown.");
73 } catch (final IOException e) {
74 assertTrue(stream.isCauseOf(e));
75 try {
76 stream.throwIfCauseOf(e);
77 fail("Expected exception not thrown.");
78 } catch (final IOException e2) {
79 assertEquals(exception, e2);
80 }
81 }
82 }
83
84 @Test
85 public void testNormalStream() {
86 try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
87 try (OutputStream stream = new TaggedOutputStream(buffer)) {
88 stream.write('a');
89 stream.write(new byte[] { 'b' });
90 stream.write(new byte[] { 'c' }, 0, 1);
91 stream.flush();
92 }
93 assertEquals(3, buffer.size());
94 assertEquals('a', buffer.toByteArray()[0]);
95 assertEquals('b', buffer.toByteArray()[1]);
96 assertEquals('c', buffer.toByteArray()[2]);
97 } catch (final IOException e) {
98 fail("Unexpected exception thrown");
99 }
100 }
101
102 @Test
103 public void testOtherException() throws Exception {
104 final IOException exception = new IOException("test exception");
105 try (TaggedOutputStream stream = new TaggedOutputStream(ClosedOutputStream.INSTANCE)) {
106
107 assertFalse(stream.isCauseOf(exception));
108 assertFalse(stream.isCauseOf(new TaggedIOException(exception, UUID.randomUUID())));
109
110 try {
111 stream.throwIfCauseOf(exception);
112 } catch (final IOException e) {
113 fail("Unexpected exception thrown");
114 }
115
116 try {
117 stream.throwIfCauseOf(new TaggedIOException(exception, UUID.randomUUID()));
118 } catch (final IOException e) {
119 fail("Unexpected exception thrown");
120 }
121 }
122 }
123
124 }