Skip to content

Instantly share code, notes, and snippets.

@Marcool04
Last active October 30, 2022 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Marcool04/cfeca8df967c832a0560fcf6f123f10d to your computer and use it in GitHub Desktop.
Save Marcool04/cfeca8df967c832a0560fcf6f123f10d to your computer and use it in GitHub Desktop.
use Test;
class X::Timeout is Exception {
has $.payload;
method message() {
"Timeout error occurred: {self.payload}";
}
}
throws-like {
await timeout_promise(
start {
sleep 5;
42;
},
timeout => 2,
description => "5 sec promise to 42"
);
},
X::Timeout,
"promise timeout yields correct error",
message => /Timeout.*/;
my Str $actual_result = "HERE IS MY RESULT";
my $two_sec_result;
lives-ok {
$two_sec_result = await timeout_promise(
Promise.in(2).then({ $actual_result; }),
timeout => 4,
);
},
"2 second timed out promise didn't time out under 4 seconds";
is $two_sec_result, $actual_result, "2 second promise result is correct";
sub timeout_promise(
Promise $promise,
Int :$timeout!,
Str :$description = "",
--> Promise
) {
say "Requested a $timeout second timed out promise for $description";
await Promise.anyof(
$promise,
Promise.in($timeout);
).then({
if ($promise.status != Kept) {
X::Timeout.new(payload => "$description").throw;
}
$promise;
});
}
@Marcool04
Copy link
Author

Here is the output:

Requested a 2 second timed out promise for 5 second promise
# Subtest: promise timeout yields correct error
    1..3
    not ok 1 - code dies
    # Failed test 'code dies'
    # at ./minimal_timeout_example.raku line 19
    ok 2 - # SKIP Code did not die, can not check exception
    ok 3 - # SKIP Code did not die, can not check exception
    # You failed 1 test of 3
not ok 1 - promise timeout yields correct error
# Failed test 'promise timeout yields correct error'
# at ./minimal_timeout_example.raku line 19

@Marcool04
Copy link
Author

Now gives:

# Subtest: promise timeout yields correct error
    1..3
Requested a 2 second timed out promise for 5 sec promise to 42
    ok 1 - code dies
    ok 2 - right exception type (X::Timeout)
    ok 3 - .message matches /Timeout.*/
ok 1 - promise timeout yields correct error
Requested a 4 second timed out promise for 
ok 2 - 2 second timed out promise didn't time out under 4 seconds
ok 3 - 2 second promise result is correct

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment