|
| 1 | +package ox.channels |
| 2 | + |
| 3 | +import org.scalatest.flatspec.AnyFlatSpec |
| 4 | +import org.scalatest.matchers.should.Matchers |
| 5 | +import ox.* |
| 6 | + |
| 7 | +import scala.concurrent.duration.* |
| 8 | + |
| 9 | +class SourceOpsThrottleTest extends AnyFlatSpec with Matchers { |
| 10 | + behavior of "Source.throttle" |
| 11 | + |
| 12 | + it should "not throttle the empty source" in supervised { |
| 13 | + val s = Source.empty[Int] |
| 14 | + val (result, executionTime) = measure { s.throttle(1, 1.second).toList } |
| 15 | + result shouldBe List.empty |
| 16 | + executionTime.toMillis should be < 1.second.toMillis |
| 17 | + } |
| 18 | + |
| 19 | + it should "throttle to specified elements per time units" in supervised { |
| 20 | + val s = Source.fromValues(1, 2) |
| 21 | + val (result, executionTime) = measure { s.throttle(1, 50.millis).toList } |
| 22 | + result shouldBe List(1, 2) |
| 23 | + executionTime.toMillis should (be >= 100L and be <= 150L) |
| 24 | + } |
| 25 | + |
| 26 | + it should "fail to throttle when elements <= 0" in supervised { |
| 27 | + val s = Source.empty[Int] |
| 28 | + the[IllegalArgumentException] thrownBy { |
| 29 | + s.throttle(-1, 50.millis) |
| 30 | + } should have message "requirement failed: elements must be > 0" |
| 31 | + } |
| 32 | + |
| 33 | + it should "fail to throttle when per lower than 1ms" in supervised { |
| 34 | + val s = Source.empty[Int] |
| 35 | + the[IllegalArgumentException] thrownBy { |
| 36 | + s.throttle(1, 50.nanos) |
| 37 | + } should have message "requirement failed: per time must be >= 1 ms" |
| 38 | + } |
| 39 | + |
| 40 | + private def measure[T](f: => T): (T, Duration) = |
| 41 | + val before = System.currentTimeMillis() |
| 42 | + val result = f |
| 43 | + val after = System.currentTimeMillis(); |
| 44 | + (result, (after - before).millis) |
| 45 | +} |
0 commit comments