Skip to content

Commit

Permalink
feat: Improve Either tests
Browse files Browse the repository at this point in the history
  • Loading branch information
RyanSkraba committed Dec 26, 2024
1 parent d85ce10 commit ce7a5c5
Showing 1 changed file with 11 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,45 +19,35 @@ class EitherSpec extends AnyFunSpecLike with Matchers {

it("can be asserted as Left or Right") {
l123 shouldBe Left(123)
l123 shouldBe 'left
l123.left.get shouldBe 123
l123 shouldBe Symbol("left")
l123.left.getOrElse(-1) shouldBe 123
rAbc shouldBe Right("ABC")
rAbc shouldBe 'right
rAbc.right.get shouldBe "ABC"
rAbc shouldBe Symbol("right")
rAbc.getOrElse("") shouldBe "ABC"

// And the directions can be reversed
l123.swap shouldBe Right(123)
rAbc.swap shouldBe Left("ABC")

// An exception is thrown if we try to get the wrong side
intercept[NoSuchElementException] { l123.right.get }
intercept[NoSuchElementException] { rAbc.left.get }
}

it("can use EitherValues for more complex expressions") {
import org.scalatest.EitherValues._

// Tests that something is defined then applies the test to the value
l123.left.value should (be > 100 and be < 200)
rAbc.right.value should (be > "AAA" and be < "BBB")

intercept[TestFailedException] {
l123.right.value
}
intercept[TestFailedException] {
rAbc.left.value
}
rAbc.value should (be > "AAA" and be < "BBB")

intercept[TestFailedException] { l123.value }
intercept[TestFailedException] { rAbc.left.value }
}

it("is right-biased in for comprehensions") {
val rDef: Either[Int, String] = Right("DEF")
val rGhi = Right("GHI"): Right[Int, String]
val l456: Either[Int, String] = Left(456)

// In a for comprehension, if all of the arguments are right, they can be used in the yield
(for { x <- rAbc; y <- rDef; z <- rGhi } yield x + y + z) shouldBe Right(
"ABCDEFGHI"
)
// In a for comprehension, if all the arguments are right, they can be used in the yield
(for { x <- rAbc; y <- rDef; z <- rGhi } yield x + y + z) shouldBe Right("ABCDEFGHI")

// If any turn out to be a left, the first one is the return value of the comprehension, no matter what
(for { x <- l123; y <- rDef; z <- rGhi } yield x + y + z) shouldBe l123
Expand Down Expand Up @@ -154,7 +144,7 @@ class EitherSpec extends AnyFunSpecLike with Matchers {
val good: Either[Exception, Int] = Right(100)
val bad: Either[Exception, Int] = Left(new IllegalArgumentException())
good.toTry shouldBe Success(100)
bad.toTry shouldBe Failure(bad.left.get)
bad.toTry shouldBe Failure(bad.left.toOption.get)
}

it("can be an option or a sequence") {
Expand Down

0 comments on commit ce7a5c5

Please sign in to comment.