Last active
March 19, 2016 18:46
-
-
Save mgodave/1b2c8e01c424b7451681 to your computer and use it in GitHub Desktop.
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
import com.twitter.util.{Var, Witness} | |
import org.mockito.Matchers.anyInt | |
import org.mockito.Mockito.{times, verify} | |
import org.scalatest.mockito.MockitoSugar | |
import org.scalatest.prop.PropertyChecks | |
import org.scalatest.{MustMatchers, WordSpec} | |
class VarsTest extends WordSpec with MustMatchers with PropertyChecks with MockitoSugar { | |
def max[T](values: Var[T])(implicit ord: Ordering[T]): Var[T] = { | |
val initial = values.sample() | |
Var.async[T](initial) { u => | |
var max = initial | |
values.changes.respond { v => | |
if (ord.gt(v, max)) { | |
max = v | |
u.update(max) | |
} | |
} | |
} | |
} | |
def max2[T](values: Var[T])(implicit ord: Ordering[T]): Var[T] = { | |
val initial = values.sample() | |
val maxEvents = values.changes.foldLeft(initial) { (x, y) => | |
if (ord.gt(x, y)) x else y | |
}.dedup | |
Var(initial, maxEvents) | |
} | |
"always return max value" in { | |
val value = Var(10) | |
val maxValue = max2(value) | |
val mockWitness = mock[Witness[Int]] | |
maxValue.changes.register(mockWitness) | |
value.update(1) | |
maxValue.sample() must be(10) | |
value.update(2) | |
maxValue.sample() must be(10) | |
value.update(3) | |
maxValue.sample() must be(10) | |
value.update(11) | |
maxValue.sample() must be(11) | |
value.update(12) | |
maxValue.sample() must be(12) | |
value.update(13) | |
maxValue.sample() must be(13) | |
verify(mockWitness, times(4)).notify(anyInt()) | |
} | |
} |
Author
mgodave
commented
Mar 19, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment