how can I mock Mojo::UserAgent in non-blocking request

34 views
Skip to first unread message

xiao_cang

unread,
Nov 14, 2017, 2:24:53 AM11/14/17
to Mojolicious
I notice that Mojo::UserAgent can make mock web server when I run unit test.
code like this:

use 5.010;
use strict;
use warnings;
use Mojolicious;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;

# Mock web service
$ua->server->app(Mojolicious->new);
$ua->server->app->routes->get(
    '/time' => sub {
        my $c = shift;
        $c->render(json => {now => time});
    }
);

my $time;
$ua->get('/time', sub {
    my ($ua, $tx) = @_;

    $time = $tx->res->json->{now};
});

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

say $time;

When I try to execute the script, I found Mojo::IOLoop won't stop until I press Ctrl-C.

Is there a way to mock Mojo::UserAgent in non-blocking request ?

sri

unread,
Nov 14, 2017, 5:21:38 AM11/14/17
to Mojolicious
my $time;
$ua->get('/time', sub {
    my ($ua, $tx) = @_;

    $time = $tx->res->json->{now};
});

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

say $time;

For this specific case you could just use a promise.

    my $time;
    $ua->get_p('/time')->then(sub { $time = $tx->res->json->{now} })->wait;
    say $time;

--
sebastian

sri

unread,
Nov 14, 2017, 5:22:44 AM11/14/17
to Mojolicious
    my $time;
    $ua->get_p('/time')->then(sub { $time = $tx->res->json->{now} })->wait;
    say $time;

I did a typo, oops.

    my $time;
    $ua->get_p('/time')->then(sub { $time = shift->res->json->{now} })->wait;
    say $time;

--
sebastian

xiao_cang

unread,
Nov 14, 2017, 6:07:32 AM11/14/17
to Mojolicious
it works for me. thx :)
I still want to know what's wrong with my demo code, it seems like mojo::ioloop's counter went some wrong, but I can't find it.

在 2017年11月14日星期二 UTC+8下午6:22:44,sri写道:

Sebastian Riedel

unread,
Nov 14, 2017, 6:13:17 AM11/14/17
to mojol...@googlegroups.com
> it works for me. thx :)
> I still want to know what's wrong with my demo code, it seems like
> mojo::ioloop's counter went some wrong, but I can't find it.

Since you're not stopping the event loop manually it keeps running
until there are no events to watch anymore. Mojo::UserAgent has a
pool of keep-alive connections that remain in the event loop, leaving
it file descriptors to watch, so it has no reason to stop by itself.

--
Sebastian Riedel
http://mojolicio.us
http://github.com/kraih
http://twitter.com/kraih
Reply all
Reply to author
Forward
0 new messages