Skip to content

Instantly share code, notes, and snippets.

@yowcow
Created December 24, 2015 10:38
Show Gist options
  • Save yowcow/b0b8abb8ca2be570f848 to your computer and use it in GitHub Desktop.
Save yowcow/b0b8abb8ca2be570f848 to your computer and use it in GitHub Desktop.
Mojolicious 6 hints
use common::sense;
use Data::Dumper;
use Encode ();
use JSON::XS qw(decode_json);
use Mojo::Util qw(monkey_patch);
use Mojolicious::Lite;
use Test::Deep;
use Test::Mojo;
use Test::More;
use Test::Pretty;
my $app = app();
$app->secrets([qw( hogefuga )]);
#
# Override default exception behavior
#
$app->renderer->add_helper(
'reply.exception' => sub {
my ($c, $e) = @_; # $e isa Mojo::Exception
$c->render(
json => {
status => 500,
message => $e->message,
},
status => 500,
);
}
);
my $r = $app->routes;
$r->get('/')->to(
cb => sub {
my $c = shift;
$c->render(json => { path => '/' });
}
);
my $item_r = $r->under('/item/:item_id')->to(
cb => sub {
my $c = shift;
my $item_id = $c->stash->{item_id};
warn "Is item ID > 0 ?: ${item_id}";
$c->reply->not_found and return
if not $item_id;
1;
}
);
#
# "bridge" is deprecated. Just use "under"
#
my $even_item_r = $item_r->under->to(
cb => sub {
my $c = shift;
my $item_id = $c->stash->{item_id};
warn "Is item ID even?: ${item_id}";
die "item_id must be even!" if $item_id % 2;
1;
}
);
$even_item_r->get('/')->to(
cb => sub {
my $c = shift;
my $item_id = $c->stash->{item_id};
$c->render(
json => {
path => '/item/:item_id',
item_id => $item_id,
}
);
}
);
my $t = Test::Mojo->new;
#
# Patching Test::Mojo stays the same
#
monkey_patch 'Test::Mojo', json_cmp_deeply => sub {
my $t = shift;
my ($p, $data) = @_ > 1 ? (shift, shift) : ('', shift);
my $desc = Encode::encode('UTF-8', qq{cmp_deeply OK for JSON Pointer "$p"});
return $t->success(Test::Deep->can('cmp_deeply')->($t->tx->res->json($p), $data, $desc));
};
subtest 'GET /' => sub {
$t->get_ok('/')->json_is({ path => '/', });
};
subtest 'GET /item/:item_id' => sub {
subtest '404 if item_id => 0' => sub {
$t->get_ok('/item/0')->status_is(404);
};
subtest '500 if item_id => 1' => sub {
$t->get_ok('/item/1')->status_is(500)->json_cmp_deeply(
{ status => 500,
message => re('^item_id must be even!'),
}
);
};
subtest '200 if item_id => 2' => sub {
$t->get_ok('/item/2')->status_is(200)->json_is(
{ path => '/item/:item_id',
item_id => '2',
}
);
};
};
done_testing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment