Skip to content

Commit

Permalink
Merge pull request #1583 from CPAN-API/json-view-errors
Browse files Browse the repository at this point in the history
Json view errors
  • Loading branch information
oalders committed Aug 25, 2015
2 parents 3dfd724 + 29387f2 commit 4102fbf
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/MetaCPAN/Web/View/JSON.pm
@@ -1,9 +1,15 @@
package MetaCPAN::Web::View::JSON;

use Moose;
use JSON::MaybeXS ();

extends 'Catalyst::View::JSON';

sub encode_json {
my ( $self, $c, $data ) = @_;
JSON::MaybeXS->new->utf8->encode($data);
}

# Catalyst::View::JSON is not a Moose.
__PACKAGE__->meta->make_immutable( inline_constructor => 0 );

Expand Down
23 changes: 23 additions & 0 deletions t/lib/MetaCPAN/Web/Controller/Test.pm
@@ -0,0 +1,23 @@
package MetaCPAN::Web::Controller::Test;

use Moose;
BEGIN { extends 'MetaCPAN::Web::Controller' }

sub _json_body {
my ( $self, $c ) = @_;
JSON::MaybeXS->new->utf8->decode(
do { local $/; $c->req->body->getline }
);
}

sub json_echo : Local {
my ( $self, $c ) = @_;

$c->stash->{echo} = $self->_json_body($c);

$c->detach( $c->view('JSON') );
}

__PACKAGE__->meta->make_immutable;

1;
52 changes: 52 additions & 0 deletions t/view/json.t
@@ -0,0 +1,52 @@
use strict;
use warnings;
use lib 't/lib';
use Test::More;
use HTTP::Request::Common 'POST';
use MetaCPAN::Web::Test;
use JSON::MaybeXS;

sub post_json {
POST(
shift(),
Content => shift(),
Content_type => 'application/json',
@_
);
}

my $cb;

sub echo_json_ok {
my ( $json, $desc ) = @_;

subtest $desc => sub {
my $exp = decode_json($json);

ok( my $res = $cb->( post_json '/test/json_echo', $json ),
'http post' );
is( $res->code, 200, '200 OK' );

my $res_json = $res->content;
ok( my $obj = eval { decode_json($res_json); }, 'decode json' );

note "received: $res_json";

is_deeply $obj, { echo => $exp }, "json passed through unchanged";
};
}

test_psgi app, sub {
$cb = shift; # global
};

{

echo_json_ok( q!{"test": 1}!, 'minimal json' );

echo_json_ok( q!{"test": [1, 2, {"hash": {}}] }!, 'arrays and hashes' );

echo_json_ok( q!{"test": true}!, 'booleans' );
}

done_testing;

0 comments on commit 4102fbf

Please sign in to comment.