Skip to content

Commit f98f0fa

Browse files
committed
#20 Add more tests for edge cases.
1 parent 2bc02e2 commit f98f0fa

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

src/main/scala/com/github/yruslan/channel/ChannelDecoratorFilter.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ class ChannelDecoratorFilter[T](inputChannel: ReadChannel[T], pred: T => Boolean
5555
val startInstant = Instant.now()
5656
var elapsedTime = 0L
5757

58-
while (elapsedTime < timeoutMilli) {
58+
while (elapsedTime <= timeoutMilli) {
5959
val newTimeout = Duration(timeoutMilli - elapsedTime, MILLISECONDS)
6060
val valueOpt = inputChannel.tryRecv(newTimeout)
6161
val found = valueOpt.isEmpty || valueOpt.forall(v => pred(v))

src/test/scala/com/github/yruslan/channel/ChannelFilterSuite.scala

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package com.github.yruslan.channel
1717

1818
import org.scalatest.wordspec.AnyWordSpec
1919

20+
import java.time.Instant
2021
import java.util.concurrent.Executors
2122
import scala.concurrent._
2223
import scala.concurrent.duration.{Duration, MILLISECONDS}
@@ -142,6 +143,62 @@ class ChannelFilterSuite extends AnyWordSpec {
142143

143144
assert(v1.contains(3))
144145
}
146+
"filter the correct value even with 0 millisecond timeout" in {
147+
val ch1 = Channel.make[Int](2)
148+
149+
val ch2 = ch1.filter(v => v == 2)
150+
151+
ch1.send(1)
152+
ch1.send(2)
153+
154+
val v1 = ch2.tryRecv(Duration.Zero)
155+
ch1.close()
156+
157+
assert(v1.contains(2))
158+
}
159+
160+
"return None if no values match and zero timeout" in {
161+
val ch1 = Channel.make[Int](2)
162+
163+
val ch2 = ch1.filter(v => v == 3)
164+
165+
ch1.send(1)
166+
ch1.send(2)
167+
168+
val v1 = ch2.tryRecv(Duration.Zero)
169+
ch1.close()
170+
171+
assert(v1.isEmpty)
172+
}
173+
174+
"return instantly on empty channel and zero timeout" in {
175+
val ch1 = Channel.make[Int](2)
176+
177+
val ch2 = ch1.filter(v => v == 3)
178+
179+
val start = Instant.now()
180+
val v1 = ch2.tryRecv(Duration.Zero)
181+
val finish = Instant.now()
182+
183+
assert(v1.isEmpty)
184+
assert(java.time.Duration.between(start, finish).toMillis <= 10L)
185+
}
186+
187+
"return None after proper wait for a non-zero timeout" in {
188+
val ch1 = Channel.make[Int](2)
189+
190+
val ch2 = ch1.filter(v => v == 3)
191+
192+
ch1.send(1)
193+
ch1.send(2)
194+
195+
val start = Instant.now()
196+
val v1 = ch2.tryRecv(Duration(10, MILLISECONDS))
197+
val finish = Instant.now()
198+
199+
assert(v1.isEmpty)
200+
assert(java.time.Duration.between(start, finish).toMillis >= 10L)
201+
}
145202
}
146203

147204
"filter input channel on recver()" in {

0 commit comments

Comments
 (0)