1+ package com .jnape .palatable .lambda .functions .builtin .fn3 ;
2+
3+ import com .jnape .palatable .lambda .io .IO ;
4+ import org .junit .Before ;
5+ import org .junit .Test ;
6+
7+ import java .util .concurrent .atomic .AtomicInteger ;
8+
9+ import static com .jnape .palatable .lambda .functions .builtin .fn3 .Bracket .bracket ;
10+ import static com .jnape .palatable .lambda .io .IO .io ;
11+ import static org .junit .Assert .assertArrayEquals ;
12+ import static org .junit .Assert .assertEquals ;
13+ import static org .junit .Assert .fail ;
14+
15+ public class BracketTest {
16+
17+ private AtomicInteger count ;
18+
19+ @ Before
20+ public void setUp () {
21+ count = new AtomicInteger (0 );
22+ }
23+
24+ @ Test
25+ public void cleanupHappyPath () {
26+ IO <Integer > hashIO = bracket (io (() -> count ), c -> io (c ::incrementAndGet ), c -> io (c ::hashCode ));
27+
28+ assertEquals (0 , count .get ());
29+ assertEquals ((Integer ) count .hashCode (), hashIO .unsafePerformIO ());
30+ assertEquals (1 , count .get ());
31+ }
32+
33+ @ Test
34+ public void cleanupSadPath () {
35+ IllegalStateException thrown = new IllegalStateException ("kaboom" );
36+ IO <Integer > hashIO = bracket (io (count ), c -> io (c ::incrementAndGet ), c -> io (() -> {throw thrown ;}));
37+
38+ try {
39+ hashIO .unsafePerformIO ();
40+ fail ("Expected exception to be raised" );
41+ } catch (IllegalStateException actual ) {
42+ assertEquals (thrown , actual );
43+ assertEquals (1 , count .get ());
44+ }
45+ }
46+
47+ @ Test
48+ public void cleanupOnlyRunsIfInitialIORuns () {
49+ IllegalStateException thrown = new IllegalStateException ("kaboom" );
50+ IO <Integer > hashIO = bracket (io (() -> {throw thrown ;}),
51+ __ -> io (count ::incrementAndGet ),
52+ __ -> io (count ::incrementAndGet ));
53+ try {
54+ hashIO .unsafePerformIO ();
55+ fail ("Expected exception to be raised" );
56+ } catch (IllegalStateException actual ) {
57+ assertEquals (thrown , actual );
58+ assertEquals (0 , count .get ());
59+ }
60+ }
61+
62+ @ Test
63+ public void errorsInCleanupAreAddedToBodyErrors () {
64+ IllegalStateException bodyError = new IllegalStateException ("kaboom" );
65+ IllegalStateException cleanupError = new IllegalStateException ("KABOOM" );
66+ IO <Integer > hashIO = bracket (io (count ),
67+ c -> io (() -> {throw cleanupError ;}),
68+ c -> io (() -> {throw bodyError ;}));
69+ try {
70+ hashIO .unsafePerformIO ();
71+ fail ("Expected exception to be raised" );
72+ } catch (IllegalStateException actual ) {
73+ assertEquals (bodyError , actual );
74+ assertArrayEquals (new Throwable []{cleanupError }, actual .getSuppressed ());
75+ }
76+ }
77+ }
0 commit comments