@@ -136,4 +136,67 @@ class IteratorDecoratorTest {
136136 Iterator .from(0 ).map(_ / 3 ).splitBy(identity).take(3 ).toSeq
137137 )
138138 }
139+
140+ @ Test
141+ def takeUntilExceptionShouldWrapAnyNonThrowingIterator (): Unit = {
142+ Assert .assertEquals(Seq (1 , 2 , 3 , 4 , 5 ), Iterator (1 , 2 , 3 , 4 , 5 ).takeUntilException.toSeq)
143+ Assert .assertEquals(Seq (1 , 2 , 3 , 4 , 5 ), Iterator (1 , 2 , 3 , 4 , 5 ).takeUntilException(_ => ()).toSeq)
144+ Assert .assertEquals(Seq .empty, Iterator .empty.takeUntilException.toSeq)
145+ Assert .assertEquals(Seq .empty, Iterator .empty.takeUntilException(_ => ()).toSeq)
146+ // Works with infinite iterators:
147+ Assert .assertEquals(Seq (1 , 2 , 3 , 4 , 5 ), Iterator .from(1 ).takeUntilException.take(5 ).toSeq)
148+ Assert .assertEquals(Seq (1 , 2 , 3 , 4 , 5 ), Iterator .from(1 ).takeUntilException(_ => ()).take(5 ).toSeq)
149+ }
150+
151+ @ Test
152+ def takeUntilExceptionShouldTakeTillAnExceptionFromHasNext (): Unit = {
153+ val toThrow = new RuntimeException (" ~expected exception~" )
154+ def brokenIterator : Iterator [Int ] = new AbstractIterator [Int ] {
155+ private var previousPosition = 0
156+
157+ override def hasNext : Boolean = {
158+ if (previousPosition == 3 ) {
159+ throw toThrow
160+ } else {
161+ true
162+ }
163+ }
164+
165+ override def next (): Int = {
166+ previousPosition += 1
167+ previousPosition
168+ }
169+ }
170+
171+ Assert .assertEquals(Seq (1 , 2 , 3 ), brokenIterator.takeUntilException.toSeq)
172+
173+ var caught : Throwable = null
174+ Assert .assertEquals(Seq (1 , 2 , 3 ), brokenIterator.takeUntilException(caught = _).toSeq)
175+ Assert .assertSame(toThrow, caught)
176+ }
177+
178+ @ Test
179+ def takeUntilExceptionShouldTakeTillAnExceptionFromNext (): Unit = {
180+ val toThrow = new RuntimeException (" ~expected exception~" )
181+ def brokenIterator : Iterator [Int ] = new AbstractIterator [Int ] {
182+ private var previousPosition = 0
183+
184+ override def hasNext : Boolean = true
185+
186+ override def next (): Int = {
187+ if (previousPosition == 3 ) {
188+ throw toThrow
189+ } else {
190+ previousPosition += 1
191+ previousPosition
192+ }
193+ }
194+ }
195+
196+ Assert .assertEquals(Seq (1 , 2 , 3 ), brokenIterator.takeUntilException.toSeq)
197+
198+ var caught : Throwable = null
199+ Assert .assertEquals(Seq (1 , 2 , 3 ), brokenIterator.takeUntilException(caught = _).toSeq)
200+ Assert .assertSame(toThrow, caught)
201+ }
139202}
0 commit comments