Created
February 17, 2023 17:26
-
-
Save faveoled/98b1913c6ebfdc80c0dc89123577b46c to your computer and use it in GitHub Desktop.
Scala single-file drop-in testing framework
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.scalajs.js | |
import scala.util.Success | |
import scala.util.Failure | |
object SelfTest { | |
def GREEN_CIRCLE: String = "\uD83D\uDFE2" | |
def RED_CIRCLE: String = "\uD83D\uDD34" | |
def runTests(): Unit = { | |
runTestSync("test1", test1) | |
runTestSync("test2", test2) | |
runTestAsync("test3", test3) | |
} | |
def test1(): Unit = { | |
var expected = "1" | |
var actual = Integer.toString(1); | |
assertEquals(expected, actual) | |
} | |
def test2(): Unit = { | |
val expected = "2" | |
val actual = 1.toString() | |
assertEquals(expected, actual) | |
} | |
def test3(): Future[Unit] = { | |
val future = OdrsClient.fetchRatings() | |
future.map(s => assertEquals(7412, s.size)) | |
} | |
private def runTestSync(testName: String, testMethod: () => Unit): Unit = { | |
val errorMsg = | |
try { | |
testMethod() | |
Option.empty | |
} catch { | |
case e: Exception => | |
Some(e.toString()) | |
} | |
val toPrint = if (errorMsg.isEmpty) then GREEN_CIRCLE else s"$RED_CIRCLE. ${errorMsg.get}" | |
println(s"Test $testName: ${toPrint}") | |
} | |
private def runTestAsync(testName: String, testMethod: () => Future[Unit]): Unit = { | |
val res = testMethod.apply() | |
res.onComplete { | |
case Success(s) => { | |
println(s"Test $testName: $GREEN_CIRCLE") | |
} | |
case Failure(ex) => { | |
println(s"Test $testName: $RED_CIRCLE. ${ex.toString()}") | |
} | |
} | |
} | |
private def assertEquals(expected: Any, actual: Any): Unit = { | |
if (!expected.equals(actual)) { | |
throw new RuntimeException("Failed: expected " + expected + ", got " + actual) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment