Help language development. Donate to The Perl Foundation

Result cpan:SAMGWISE last updated on 2019-08-28

t/01-basic.t6
#! /usr/bin/env perl6
use v6;
use Test;
use lib 'lib';
# plan 4;

use-ok 'Result';
use Result;

# Test factory routines
is  Ok('foo').is-ok, True,  "Ok factory";
is Err('bar').is-err, True, "Err factory";

# Ok
{
    my $result = Ok 'test';
    is $result.defined, True, "Create defined Result::Ok";
    is $result.so, True, "Result::Ok is True (.so)";
    is $result.Bool, True, "Result::Ok is True (.bool)";
    is $result.ok('testing'), 'test', "Result:OK resolves value";

    my $handled = do given $result {
        when Result::Ok { True }
        when Result::Err { False }
    }
    is $handled, True, "Handle Result::Ok with given when";

    with $result.err-to-undef {
        pass "Result:Ok.err-to-undef does pass through to with block";
        is .value, 'test', "err-to-undef returns Result::Ok";
    }
    else {
        fail "Result:Ok.err-to-undef does not pass through to with block"
    }
}

# Err
{
    my $result = Err "I'm an error!";
    is $result.defined, True, "Create defined Result::Err";
    is $result.so, False, "Result::Err is falsy (.so)";
    is $result.Bool, False, "Result::Err is falsy (.bool)";

    my $handled = do given $result {
        when Result::Ok { True }
        when Result::Err { False }
    }
    is $handled, False, "Handle Result::Err with given when";

    with $result.err-to-undef {
        fail "Result:Err.err-to-undef should not pass through to with block"
    }
    else {
        pass "Result:Err.err-to-undef does not pass through to with block"
    }

    dies-ok { $result.ok('testing') }, "Result:Err dies on resolution";
}

# Test Result::Any in sub signitures
{
    my sub test(Result::Any $r --> Result::Any) { $r };

    is test(Ok('foo')).is-ok, True, "Result::Any signiture with Result::Ok";
    is test(Err('foo')).is-err, True, "Result::Any signiture with Result::Err";
}

done-testing