Last active
June 23, 2023 06:46
-
-
Save williammartin/00ef01947cadfeb9d2be9740024c1582 to your computer and use it in GitHub Desktop.
abc
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
# typed: true | |
require "minitest/autorun" | |
require_relative "../lib/option" | |
class TestOption < Minitest::Test | |
extend T::Sig | |
def test_unwrap_on_some | |
o = Option.some("value") | |
assert_equal o.unwrap, "value" | |
end | |
def test_unwrap_on_none | |
o = Option.none | |
error = assert_raises(Option::UnwrapError) { | |
o.unwrap | |
} | |
assert_equal error.message, "called `Option::unwrap` on a None" | |
end | |
def test_map_on_some | |
o = Option.some("foo") | |
o = o.map { |v| v + "bar" } | |
assert_equal o.unwrap, "foobar" | |
end | |
def test_map_on_none | |
o = Option.none | |
o.map { |v| raise "should never be called" } | |
error = assert_raises(Option::UnwrapError) { | |
o.unwrap | |
} | |
assert_equal error.message, "called `Option::unwrap` on a None" | |
end | |
def test_flat_map_on_some | |
o = Option.some("foo") | |
o = o.flat_map { |v| Option.some(v + "bar") } | |
assert_equal o.unwrap, "foobar" | |
end | |
def test_flat_map_on_none | |
o = Option.none | |
o.flat_map { |v| raise "should never be called" } | |
error = assert_raises(Option::UnwrapError) { | |
o.unwrap | |
} | |
assert_equal error.message, "called `Option::unwrap` on a None" | |
end | |
def test_ok_or_success | |
o = Option.some("value") | |
r = o.ok_or("shouldn't be used") | |
assert_equal r.unwrap, "value" | |
end | |
def test_ok_or_failure | |
o = Option.none | |
r = o.ok_or("oh no") | |
err = assert_raises(Result::UnwrapError) { | |
r.unwrap | |
} | |
assert_equal err.message, "called `Result::unwrap` on a Failure containing: 'oh no'" end | |
def test_real_world_scenario | |
email_address = "williammartin@github.com" | |
parse_email_address(email_address) | |
.flat_map { |e| lookup_user_id(e) } | |
end | |
sig { params(unparsed_email: String).returns(Option[String]) } | |
def parse_email_address(unparsed_email) | |
if !unparsed_email.include?("@") | |
Option.none | |
else | |
Option.some(unparsed_email) | |
end | |
end | |
sig { params(parsed_email: String).returns(Option[Integer]) } | |
def lookup_user_id(parsed_email) | |
if parsed_email != "williammartin@github.com" | |
Option.none | |
else | |
Option.some(1) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment