1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.lang3.concurrent;
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.assertThrows;
22 import static org.junit.jupiter.api.Assertions.assertTrue;
23
24 import org.apache.commons.lang3.AbstractLangTest;
25 import org.junit.jupiter.api.Test;
26
27
28
29
30 class ThresholdCircuitBreakerTest extends AbstractLangTest {
31
32
33
34
35 private static final long threshold = 10L;
36
37 private static final long zeroThreshold = 0L;
38
39
40
41
42 @Test
43 void testClosingThresholdCircuitBreaker() {
44 final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold);
45 circuit.incrementAndCheckState(9L);
46 circuit.close();
47
48 assertTrue(circuit.incrementAndCheckState(9L), "Internal counter was not reset back to zero");
49 }
50
51
52
53
54 @Test
55 void testGettingThreshold() {
56 final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold);
57 assertEquals(Long.valueOf(threshold), Long.valueOf(circuit.getThreshold()), "Wrong value of threshold");
58 }
59
60
61
62
63 @Test
64 void testNegativeIncrementRejected() {
65 final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold);
66 assertThrows(IllegalArgumentException.class, () -> circuit.incrementAndCheckState(-1L), "Negative increments must be rejected");
67 }
68
69
70
71
72
73 @Test
74 void testOverflowSaturatesAndOpens() {
75 final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(Long.MAX_VALUE);
76 circuit.incrementAndCheckState(Long.MAX_VALUE);
77
78 assertFalse(circuit.incrementAndCheckState(1L), "Overflow must open the circuit, not wrap the counter");
79 assertFalse(circuit.checkState(), "Circuit must stay open after overflow");
80 }
81
82
83
84
85 @Test
86 void testThreshold() {
87 final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold);
88 circuit.incrementAndCheckState(9L);
89 assertTrue(circuit.incrementAndCheckState(1L), "Circuit opened before reaching the threshold");
90 }
91
92
93
94
95 @Test
96 void testThresholdCircuitBreakingException() {
97 final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold);
98 circuit.incrementAndCheckState(9L);
99 assertFalse(circuit.incrementAndCheckState(2L), "The circuit was supposed to be open after increment above the threshold");
100 }
101
102
103
104
105 @Test
106 void testThresholdEqualsZero() {
107 final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(zeroThreshold);
108 assertFalse(circuit.incrementAndCheckState(0L), "When the threshold is zero, the circuit is supposed to be always open");
109 }
110
111 }