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.Writer;
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 TaggedWriterTest {
35
36 @Test
37 public void testBrokenWriter() {
38 final IOException exception = new IOException("test exception");
39 final TaggedWriter writer = new TaggedWriter(new BrokenWriter(exception));
40
41
42 try {
43 writer.write(new char[] { 'x' }, 0, 1);
44 fail("Expected exception not thrown.");
45 } catch (final IOException e) {
46 assertTrue(writer.isCauseOf(e));
47 try {
48 writer.throwIfCauseOf(e);
49 fail("Expected exception not thrown.");
50 } catch (final IOException e2) {
51 assertEquals(exception, e2);
52 }
53 }
54
55
56 try {
57 writer.flush();
58 fail("Expected exception not thrown.");
59 } catch (final IOException e) {
60 assertTrue(writer.isCauseOf(e));
61 try {
62 writer.throwIfCauseOf(e);
63 fail("Expected exception not thrown.");
64 } catch (final IOException e2) {
65 assertEquals(exception, e2);
66 }
67 }
68
69
70 try {
71 writer.close();
72 fail("Expected exception not thrown.");
73 } catch (final IOException e) {
74 assertTrue(writer.isCauseOf(e));
75 try {
76 writer.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 testNormalWriter() throws IOException {
86 try (StringBuilderWriter buffer = new StringBuilderWriter()) {
87 try (Writer writer = new TaggedWriter(buffer)) {
88 writer.write('a');
89 writer.write(new char[] { 'b' });
90 writer.write(new char[] { 'c' }, 0, 1);
91 writer.flush();
92 }
93 assertEquals(3, buffer.getBuilder().length());
94 assertEquals('a', buffer.getBuilder().charAt(0));
95 assertEquals('b', buffer.getBuilder().charAt(1));
96 assertEquals('c', buffer.getBuilder().charAt(2));
97 }
98 }
99
100 @Test
101 public void testOtherException() throws Exception {
102 final IOException exception = new IOException("test exception");
103 try (TaggedWriter writer = new TaggedWriter(ClosedWriter.INSTANCE)) {
104 assertFalse(writer.isCauseOf(exception));
105 assertFalse(writer.isCauseOf(new TaggedIOException(exception, UUID.randomUUID())));
106 writer.throwIfCauseOf(exception);
107 writer.throwIfCauseOf(new TaggedIOException(exception, UUID.randomUUID()));
108 }
109 }
110
111 }