Added toPrice() extension.

This commit is contained in:
Erik C. Thauvin 2021-05-08 10:21:12 -07:00
parent cd76f2d9cb
commit 8cb6ac4c0b
3 changed files with 31 additions and 18 deletions

View file

@ -42,6 +42,16 @@ import java.time.LocalDate
data class Price(val base: String, val currency: String, val amount: Double)
fun String.toPrice(): Price {
val json = JSONObject(this)
if (json.has("data")) {
val data = json.getJSONObject("data")
return Price(data.getString("base"), data.getString("currency"), data.getString("amount").toDouble())
} else {
throw CryptoException("Missing JSON data.")
}
}
open class CryptoPrice private constructor() {
companion object {
// Coinbase API URL
@ -101,13 +111,7 @@ open class CryptoPrice private constructor() {
params.put("date", "$date")
}
val body = apiCall(listOf("prices", "$base-$currency", "spot"), params)
val json = JSONObject(body)
if (json.has("data")) {
val data = json.getJSONObject("data")
return Price(data.getString("base"), data.getString("currency"), data.getString("amount").toDouble())
} else {
throw CryptoException("Missing JSON data.")
}
return body.toPrice()
}
}
}

View file

@ -42,24 +42,33 @@ class CryptoPriceTest {
@Throws(CryptoException::class)
fun testBCHPrice() {
val price = marketPrice("BCH", "GBP", LocalDate.now().minusDays(1))
assertEquals(price.base, "BCH", "ETH2")
assertEquals(price.base, "BCH", "BCH")
assertEquals(price.currency, "GBP", "is GBP")
assertTrue(price.amount > 0.00, "BCH > 0")
}
@Test
@Throws(CryptoException::class)
fun testMarketPriceExceptions() {
assertFailsWith(
message = "FOO did not fail",
exceptionClass = CryptoException::class,
block = { marketPrice("FOO") }
message = "FOO did not fail",
exceptionClass = CryptoException::class,
block = { marketPrice("FOO") }
)
assertFailsWith(
message = "BAR did not fail",
exceptionClass = CryptoException::class,
block = { marketPrice("BTC", "BAR") }
message = "BAR did not fail",
exceptionClass = CryptoException::class,
block = { marketPrice("BTC", "BAR") }
)
}
@Test
@Throws(CryptoException::class)
fun testToPrice() {
val price = "{\"data\":{\"base\":\"BTC\",\"currency\":\"USD\",\"amount\":\"57515.69\"}}".toPrice()
assertEquals(price.base, "BTC", "base is BTC")
assertEquals(price.currency, "USD", "currency is USD")
assertEquals(price.amount, "57515.69".toDouble(), "amount is 57515.69")
}
}