Skip to content

Instantly share code, notes, and snippets.

@BenWhitehead
Last active August 29, 2015 14:04
Show Gist options
  • Save BenWhitehead/4675ffec4c840afa883d to your computer and use it in GitHub Desktop.
Save BenWhitehead/4675ffec4c840afa883d to your computer and use it in GitHub Desktop.
Scala Twitter Try Testing and Finagle Experimentation
import com.twitter.finagle.{Filter, Service}
import com.twitter.util.{Await, Future}
import io.finch.AnyOps
object test {
def main(args: Array[String]) {
val s = "12345"
val s1 = new Service1
val s2 = new Service2
val ss = s1 andThen s2
val sf = ss(s)
val sfs = Await.result(sf)
println(s"$sfs")
val ff = new filter1().apply(s, s2)
val sff = Await.result(ff)
println(s"$sff")
val f2 = new filter2().apply(s.toList, service)
val f2f = Await.result(f2)
println(f2f)
}
class Service1 extends Service[String, Int] {
override def apply(request: String): Future[Int] = request.toInt.toFuture
}
class Service2 extends Service[Future[Int], String] {
override def apply(request: Future[Int]): Future[String] = request.flatMap { case r => f"$r%x".toFuture }
}
class filter1 extends Filter[String, String, Future[Int], String] {
def apply(request: String, service: Service[Future[Int], String]): Future[String] = {
service(request.toInt.toFuture)
}
}
def service = new Service[String, Int] {
override def apply(request: String): Future[Int] = request.toInt.toFuture
}
class filter2 extends Filter[List[Char], List[Char], String, Int] {
override def apply(
request: List[Char],
service: Service[String, Int]
): Future[List[Char]] = {
request match {
case x :: xs => service(s"$x${xs.mkString("")}") flatMap { case i => f"$i%x".toList.toFuture }
}
}
}
}
import com.twitter.util.{Return, Throw, Try}
import org.scalatest.FreeSpec
class TryTesting extends FreeSpec {
"123" in {
test("123")
runSomething("123")
}
"abc" in {
test("abc")
runSomething("abc")
}
"1" in {
test("1")
runSomething("1")
}
"MAX_INT + 1" in {
test("2147483648")
runSomething("2147483648")
}
"-1" in {
test("-1")
runSomething("-1")
}
"-250" in {
test("-250")
runSomething("-250")
}
"IllegalArgumentException" in {
test("IllegalArgumentException")
runSomething({throw new IllegalArgumentException})
}
def runSomething(s: => String) = {
Try { s.toInt }
.handle { case ex: NumberFormatException =>
println("NumberFormatException")
1
}
.handle { case ex: IllegalArgumentException =>
println("handle")
2
}
.filter {
println("filter")
_ < 0
}
.flatMap { case i =>
println("flatMap")
if (i < -100) Throw(new RuntimeException) else Return(i)
}
.onSuccess { case i =>
println("onSuccess")
}
// .onFailure { case rescueException: Throwable =>
// println(s"onFailure: $rescueException")
// }
.ensure {
println("ensure")
}
}
def test(s: String) = {
System.out.println(s"--- $s ---")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment