/Non-Blocking-Test.pl Secret
Last active
December 15, 2015 17:59
-
-
Save jberger/6460c9d1017a267ff451 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env perl | |
use Test::More; | |
use Test::Mojo; | |
use Mojolicious::Lite; | |
use Mojo::UserAgent; | |
$|++; | |
my $t = Test::Mojo->new; | |
my $app = $t->app; | |
my $c = Mojolicious::Controller->new; | |
# Simple route | |
get '/' => sub { | |
shift->render(text => 'Hello World'); | |
}; | |
# Helper with an async request inside | |
app->helper( | |
get_doc => sub { | |
my ($c, $path, $cb) = @_; | |
my $delay = Mojo::IOLoop->delay; | |
my $ua = Mojo::UserAgent->new; | |
$delay->begin; | |
$ua->get( | |
$path => sub { | |
shift; | |
$cb->(shift->success->body); | |
$delay->end; | |
}); | |
# Start IOLoop if not started already | |
$delay->wait unless $delay->ioloop->is_running; | |
} | |
); | |
# Use async helper - works fine | |
app->get_doc( | |
'https://www.google.de/' => sub { | |
my $doc = shift; | |
ok($doc, 'This is an XRD 1'); | |
}); | |
# Get Resource - works fine | |
$t->get_ok('/'); | |
# Use async helper again - works kind of fine | |
app->get_doc( | |
'https://www.google.de/' => sub { | |
my $doc = shift; | |
ok($doc, 'This is an XRD 2'); | |
}); | |
# Get resource - Not reached ever | |
$t->get_ok('/'); | |
done_testing; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much!