-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #24 from softwaremill/feat_throttle
feat: implement `throttle` function
- Loading branch information
Showing
2 changed files
with
85 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 45 additions & 0 deletions
45
core/src/test/scala/ox/channels/SourceOpsThrottleTest.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package ox.channels | ||
|
||
import org.scalatest.flatspec.AnyFlatSpec | ||
import org.scalatest.matchers.should.Matchers | ||
import ox.* | ||
|
||
import scala.concurrent.duration.* | ||
|
||
class SourceOpsThrottleTest extends AnyFlatSpec with Matchers { | ||
behavior of "Source.throttle" | ||
|
||
it should "not throttle the empty source" in supervised { | ||
val s = Source.empty[Int] | ||
val (result, executionTime) = measure { s.throttle(1, 1.second).toList } | ||
result shouldBe List.empty | ||
executionTime.toMillis should be < 1.second.toMillis | ||
} | ||
|
||
it should "throttle to specified elements per time units" in supervised { | ||
val s = Source.fromValues(1, 2) | ||
val (result, executionTime) = measure { s.throttle(1, 50.millis).toList } | ||
result shouldBe List(1, 2) | ||
executionTime.toMillis should (be >= 100L and be <= 150L) | ||
} | ||
|
||
it should "fail to throttle when elements <= 0" in supervised { | ||
val s = Source.empty[Int] | ||
the[IllegalArgumentException] thrownBy { | ||
s.throttle(-1, 50.millis) | ||
} should have message "requirement failed: elements must be > 0" | ||
} | ||
|
||
it should "fail to throttle when per lower than 1ms" in supervised { | ||
val s = Source.empty[Int] | ||
the[IllegalArgumentException] thrownBy { | ||
s.throttle(1, 50.nanos) | ||
} should have message "requirement failed: per time must be >= 1 ms" | ||
} | ||
|
||
private def measure[T](f: => T): (T, Duration) = | ||
val before = System.currentTimeMillis() | ||
val result = f | ||
val after = System.currentTimeMillis(); | ||
(result, (after - before).millis) | ||
} |