Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaSpektrum ScalaCheck Example
import org.scalatest.prop.PropertyChecks
import org.scalatest.PropSpec
import org.scalatest.matchers.MustMatchers
import JsonGenerator._
import play.api.libs.json.{Json, JsNumber, JsObject}
import stock.Stock
class StockInfoParserSpec extends PropSpec with PropertyChecks with MustMatchers {
property("JSON-Werte entsprechen Aktie") {
forAll { (json: JsObject, last: JsNumber, high: JsNumber, low: JsNumber) =>
val stockJson = json ++ baseStockData(last, high, low)
Stock.fromJson(stockJson) must
be(Stock("ABC", "ABC AG", "EUR", last.value, high.value, low.value))
}
}
property("Nicht valide Kursdaten werden zurückgewiesen") {
forAll { (last: JsNumber, high: JsNumber, low: JsNumber) =>
whenever(low.value > last.value && last.value > high.value) {
val stockJson = baseStockData(last, high, low)
Stock.validateJson(stockJson) must not be ('defined)
}
}
}
def baseStockData(last: JsNumber, yearHigh: JsNumber, yearLow: JsNumber) = Json.obj(
"sym" -> "ABC",
"name" -> "ABC AG",
"curr" -> "EUR",
"last" -> last,
"yearHigh" -> yearHigh,
"yearLow" -> yearLow
)
}
case class Stock(sym: String, name: String, curr: String, last: BigDecimal, yearHigh : BigDecimal, yearLow: BigDecimal)
object Stock {
import play.api.libs.json._
import play.api.libs.functional.syntax._
implicit val stockRead = (
(__ \ "sym").read[String] and
(__ \ "name").read[String] and
(__ \ "curr").read[String] and
(__ \ "last").read[BigDecimal] and
(__ \ "yearHigh").read[BigDecimal] and
(__ \ "yearLow").read[BigDecimal]
)(Stock.apply _)
def fromJson(json: JsObject) = {
extractJson(json).getOrElse(null)
}
def validateJson(json: JsObject) = {
extractJson(json)
.filter(stock => stock.last <= stock.yearHigh)
.filter(stock => stock.last >= stock.yearLow)
.asOpt
}
def extractJson(json: JsObject): JsResult[Stock] = {
Json.fromJson[Stock](json)
}
}
import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json._
import org.scalacheck.Gen._
import play.api.libs.json.JsObject
import play.api.libs.json.JsString
import play.api.libs.json.JsNumber
object JsonGenerator {
def jsString: Gen[JsString] = for {
str <- Gen.alphaStr
} yield JsString(str)
def jsNumber: Gen[JsNumber] = for {
decimal <- Gen.chooseNum(0.1, 1000.0)
} yield JsNumber(decimal)
def jsTuples: Gen[(String, JsValue)] = for {
key <- Gen.alphaStr
v <- oneOf(jsNumber, jsString)
} yield (key, v)
def jsObjects: Gen[JsObject] = Gen.sized { size => for {
amount <- Gen.chooseNum(1, 10)
elems <- Gen.listOfN(amount, jsTuples)
} yield JsObject(elems)
}
implicit lazy val arbObj: Arbitrary[JsObject] = Arbitrary(jsObjects)
implicit lazy val arbNum: Arbitrary[JsNumber] = Arbitrary(jsNumber)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.