Last active
May 9, 2016 11:41
-
-
Save fomkin/e22edfe56e6cdce11c0511caf81032d1 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 scala.concurrent.Future | |
import scala.util.{Failure, Success} | |
object Czar { | |
class Context | |
case class ApiTestException(message: String, context: Context, cause: Option[Throwable] = None) | |
extends Exception(message) | |
} | |
trait Czar { | |
import Czar._ | |
implicit val ec = scala.concurrent.ExecutionContext.Implicits.global | |
val GRAY = "\u001b[37m" | |
val BALLOTX = "\u2717" | |
val CHECKMARK = "\u2713" | |
def assert(description: String)(condition: Boolean)(implicit context: Context): Future[Unit] = { | |
if (condition) Future.successful(()) | |
else Future.failed(ApiTestException(description, context)) | |
} | |
def assertMatch[T, R](x: T)(f: PartialFunction[T, R])(implicit context: Context): Future[R] = { | |
if (f.isDefinedAt(x)) ok(f(x)) else fail(s"Match error: $x") | |
} | |
def ok[T](x: T): Future[T] = Future.successful(x) | |
def fail[T](s: String)(implicit context: Context): Future[T] = { | |
Future.failed(ApiTestException(s, context)) | |
} | |
def step[T](description: String)(f: Context => Future[T]) = { | |
val context = new Context() | |
def error(s: String) = s"$description\n -> $s" | |
def printResult(color: String, sing: String, message: String) = | |
println(" ["+color+sing+Console.RESET+"] " + message) | |
f(context) recover { | |
case e if !e.isInstanceOf[ApiTestException] ⇒ | |
throw ApiTestException(e.getMessage, context, Some(e)) | |
} andThen { | |
case Failure(ApiTestException(message, `context`, None)) => printResult(Console.RED, BALLOTX, error(message)) | |
case Failure(ApiTestException(message, `context`, Some(e))) => | |
val padding = " " * 5 | |
val stackTrace = padding + e.getStackTrace.mkString(s"\n$padding") | |
printResult(Console.RED, BALLOTX, error(s"$message\n$stackTrace")) | |
case Failure(ApiTestException(message, _, _)) => printResult(GRAY, " ", description) | |
case Failure(e) => printResult(Console.RED, BALLOTX, error(e.getMessage)) | |
case Success(_) => printResult(Console.GREEN, CHECKMARK, description) | |
} | |
} | |
} |
Author
fomkin
commented
May 5, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment