1
2
3
4
5
6
7
8
9
10
11 package org.eclipse.jgit.internal.storage.io;
12
13 import static org.eclipse.jgit.internal.storage.io.CancellableDigestOutputStream.BYTES_TO_WRITE_BEFORE_CANCEL_CHECK;
14 import static org.junit.Assert.assertEquals;
15 import static org.junit.Assert.assertThrows;
16 import static org.junit.Assert.assertTrue;
17
18 import java.io.InterruptedIOException;
19
20 import org.eclipse.jgit.lib.ProgressMonitor;
21 import org.eclipse.jgit.util.io.NullOutputStream;
22 import org.junit.Test;
23
24 public class CancellableDigestOutputStreamTest {
25 private static class CancelledTestMonitor implements ProgressMonitor {
26
27 private boolean cancelled = false;
28
29 public void setCancelled(boolean cancelled) {
30 this.cancelled = cancelled;
31 }
32
33 @Override
34 public void start(int totalTasks) {
35
36 }
37
38 @Override
39 public void beginTask(String title, int totalWork) {
40
41 }
42
43 @Override
44 public void update(int completed) {
45
46 }
47
48 @Override
49 public void endTask() {
50
51 }
52
53 @Override
54 public boolean isCancelled() {
55 return cancelled;
56 }
57 }
58
59 @Test
60 public void testCancelInProcess() throws Exception {
61 CancelledTestMonitor m = new CancelledTestMonitor();
62 try (CancellableDigestOutputStream out = new CancellableDigestOutputStream(
63 m, NullOutputStream.INSTANCE)) {
64 byte[] KB = new byte[1024];
65 int triggerCancelWriteCnt = BYTES_TO_WRITE_BEFORE_CANCEL_CHECK
66 / KB.length;
67 for (int i = 0; i < triggerCancelWriteCnt + 1; i++) {
68 out.write(KB);
69 }
70 assertTrue(out.length() > BYTES_TO_WRITE_BEFORE_CANCEL_CHECK);
71 m.setCancelled(true);
72
73 for (int i = 0; i < triggerCancelWriteCnt - 1; i++) {
74 out.write(KB);
75 }
76
77 long lastLength = out.length();
78 assertThrows(InterruptedIOException.class, () -> {
79 out.write(1);
80 });
81 assertEquals(lastLength, out.length());
82
83 assertThrows(InterruptedIOException.class, () -> {
84 out.write(new byte[1]);
85 });
86 assertEquals(lastLength, out.length());
87 }
88 }
89
90 @Test
91 public void testTriggerCheckAfterSingleBytes() throws Exception {
92 CancelledTestMonitor m = new CancelledTestMonitor();
93 try (CancellableDigestOutputStream out = new CancellableDigestOutputStream(
94 m, NullOutputStream.INSTANCE)) {
95
96 byte[] bytes = new byte[BYTES_TO_WRITE_BEFORE_CANCEL_CHECK + 1];
97 m.setCancelled(true);
98
99 assertThrows(InterruptedIOException.class, () -> {
100 out.write(bytes);
101 });
102 assertEquals(BYTES_TO_WRITE_BEFORE_CANCEL_CHECK, out.length());
103 }
104 }
105 }