Add Either type
This commit is contained in:
@@ -4,6 +4,12 @@ import unittest
|
||||
import op
|
||||
|
||||
suite "Basic tests":
|
||||
proc divide(a, b: int): OP[float] =
|
||||
if b == 0:
|
||||
return fail "Cannot divide by zero!"
|
||||
else:
|
||||
return ok a / b
|
||||
|
||||
test "Check OK":
|
||||
let test = ok 1
|
||||
check test.isOk == true
|
||||
@@ -16,9 +22,9 @@ suite "Basic tests":
|
||||
proc createValue: OP[string] =
|
||||
let myString = "This is test code!"
|
||||
ok myString
|
||||
let data = createValue()
|
||||
check data.isOk
|
||||
check data.val == "This is test code!"
|
||||
let r = createValue()
|
||||
check r.isOk
|
||||
check r.val == "This is test code!"
|
||||
|
||||
test "Check failing result proc":
|
||||
proc someProc(): OP[int] =
|
||||
@@ -54,38 +60,53 @@ suite "Basic tests":
|
||||
check data.isOk == false
|
||||
check data.error == "data got corrupted"
|
||||
|
||||
test "Check divider proc":
|
||||
proc divide(a, b: int): OP[float] =
|
||||
if b == 0:
|
||||
return fail(float, "Cannot divide by zero!")
|
||||
else:
|
||||
return ok a / b
|
||||
|
||||
let
|
||||
a = 42
|
||||
b = 0
|
||||
let r = divide(a, b)
|
||||
check r.isOk == false
|
||||
check r.error == "Cannot divide by zero!"
|
||||
test "Check divider OK":
|
||||
let r = divide(12, 6)
|
||||
check r.isOk == true
|
||||
check r.val == 2
|
||||
|
||||
test "Check implicit fail type":
|
||||
proc divide(a, b: int): OP[float] =
|
||||
if b == 0:
|
||||
return fail "Cannot divide by zero!"
|
||||
else:
|
||||
return ok a / b
|
||||
|
||||
let r = divide(1, 0)
|
||||
check r.isOk == false
|
||||
check r.error == "Cannot divide by zero!"
|
||||
|
||||
test "Check type of impolicit fail":
|
||||
proc divide(a, b: int): OP[float] =
|
||||
if b == 0:
|
||||
return fail "Cannot divide by zero!"
|
||||
else:
|
||||
return ok a / b
|
||||
test "Check case":
|
||||
let r = divide(1, 2)
|
||||
case r.isOK:
|
||||
of true:
|
||||
check r.val == 0.5
|
||||
of false:
|
||||
echo r.error
|
||||
|
||||
let r = divide(1, 0)
|
||||
check r.isOk == false
|
||||
check r.error == "Cannot divide by zero!"
|
||||
test "Check hiding of Either":
|
||||
let r = divide(1, 2)
|
||||
case r.isOK:
|
||||
of true:
|
||||
check r.val == 0.5
|
||||
of false:
|
||||
echo r.error
|
||||
|
||||
test "Expect invalid field":
|
||||
let r = divide(1, 2)
|
||||
expect FieldError:
|
||||
echo r.error
|
||||
|
||||
test "Expect in case":
|
||||
let r = divide(1, 2)
|
||||
case r.isOK:
|
||||
of true:
|
||||
expect FieldError:
|
||||
echo r.error
|
||||
of false:
|
||||
echo r.error
|
||||
|
||||
# These will not work. How could this be done?
|
||||
# test "Expect access before check":
|
||||
# let r = divide(1, 2)
|
||||
# expect FieldError:
|
||||
# echo r.val
|
||||
|
||||
# test "Expect invalid field after check":
|
||||
# let r = divide(1, 2)
|
||||
# if r.isOK:
|
||||
# echo r.error
|
||||
Reference in New Issue
Block a user