Debian Codegraph @

t/deserialize.t

raw
1 use strict;
2 use warnings;
3
4 use Test::More tests => 16;
5 use Plack::Test;
6 use HTTP::Request::Common;
7 use Dancer2::Logger::Capture;
8
9 my $logger = Dancer2::Logger::Capture->new;
10 isa_ok( $logger, 'Dancer2::Logger::Capture' );
11
12 {
13 package App;
14 use Dancer2;
15
16 # default, we're actually overriding this later
17 set serializer => 'JSON';
18
19 # for now
20 set logger => 'Console';
21
22 # deserialization fail hook
23 hook 'core.error.before' => sub {
24 my ($err) = @_; # Dancer2::Core::Error object
25 if ( $err->message =~ m!Failed to deserialize content! ) {
26 $err->status(444); # custom status
27 }
28 };
29
30 put '/from_params' => sub {
31 my %p = params();
32 return [ map +( $_ => $p{$_} ), sort keys %p ];
33 };
34
35 put '/from_data' => sub {
36 my $p = request->data;
37 return [ map +( $_ => $p->{$_} ), sort keys %{$p} ];
38 };
39
40 # This route is used for both toure and body params.
41 post '/from/:town' => sub {
42 my $p = params;
43 return [ map +( $_ => $p->{$_} ), sort keys %{$p} ];
44 };
45
46 any [qw/del patch/] => '/from/:town' => sub {
47 my $p = params('body');
48 return [ map +( $_ => $p->{$_} ), sort keys %{$p} ];
49 };
50 }
51
52 my $test = Plack::Test->create( App->to_app );
53
54 subtest 'PUT request with parameters' => sub {
55 for my $type ( qw<params data> ) {
56 my $res = $test->request(
57 PUT "/from_$type",
58 'Content-Type' => 'application/json',
59 Content => '{ "foo": 1, "bar": 2 }'
60 );
61
62 is(
63 $res->content,
64 '["bar",2,"foo",1]',
65 "Parameters deserialized from $type",
66 );
67 }
68 };
69
70 my $app = App->to_app;
71 use utf8;
72 use JSON::MaybeXS;
73 use Encode;
74 use Module::Runtime 'use_module';
75
76 note "Verify Serializers decode into characters"; {
77 my $utf8 = '∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i)';
78
79 test_psgi $app, sub {
80 my $cb = shift;
81
82 for my $type ( qw/JSON YAML/ ) {
83 my $class = "Dancer2::Serializer::$type";
84 use_module($class);
85
86 my $serializer = $class->new();
87 my $body = $serializer->serialize({utf8 => $utf8});
88
89 # change the app serializer
90 # we're overiding a RO attribute only for this test!
91 Dancer2->runner->apps->[0]->set_serializer_engine(
92 $serializer
93 );
94
95 my $r = $cb->(
96 PUT '/from_params',
97 'Content-Type' => $serializer->content_type,
98 Content => $body,
99 );
100
101 my $content = Encode::decode( 'UTF-8', $r->content );
102
103 like(
104 $content,
105 qr{\Q$utf8\E},
106 "utf-8 string returns the same using the $type serializer",
107 );
108 }
109 };
110 }
111
112 # default back to JSON for the rest
113 # we're overiding a RO attribute only for this test!
114 Dancer2->runner->apps->[0]->set_serializer_engine(
115 Dancer2::Serializer::JSON->new
116 );
117
118 note "Decoding of mixed route and deserialized body params"; {
119 # Check integers from request body remain integers
120 # but route params get decoded.
121 test_psgi $app, sub {
122 my $cb = shift;
123
124 my @req_params = (
125 "/from/D\x{c3}\x{bc}sseldorf", # /from/d%C3%BCsseldorf
126 'Content-Type' => 'application/json',
127 Content => JSON::MaybeXS::encode_json({ population => 592393 }),
128 );
129
130 my $r = $cb->( POST @req_params );
131
132 # Watch out for hash order randomization..
133 is_deeply(
134 $r->content,
135 '["population",592393,"town","'."D\x{c3}\x{bc}sseldorf".'"]',
136 "Integer from JSON body remains integer and route params decoded",
137 );
138 };
139 }
140
141 # Check body is deserialized on PATCH and DELETE.
142 # The RFC states the behaviour for DELETE is undefined; We take the lenient
143 # and deserialize it.
144 # http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-24#section-4.3.5
145 note "Deserialze any body content that is allowed or undefined"; {
146 test_psgi $app, sub {
147 my $cb = shift;
148
149 for my $method ( qw/DELETE PATCH/ ) {
150 my $request = HTTP::Request->new(
151 $method,
152 "/from/D\x{c3}\x{bc}sseldorf", # /from/d%C3%BCsseldorf
153 [ 'Content-Type' => 'application/json' ],
154 JSON::MaybeXS::encode_json({ population => 592393 }),
155 );
156 my $response = $cb->($request);
157 my $content = Encode::decode( 'UTF-8', $response->content );
158
159 # Only body params returned
160 is(
161 $content,
162 '["population",592393]',
163 "JSON body deserialized for " . uc($method) . " requests",
164 );
165 }
166 }
167 }
168
169 note 'Check serialization errors'; {
170 Dancer2->runner->apps->[0]->set_serializer_engine(
171 Dancer2::Serializer::JSON->new( log_cb => sub { $logger->log(@_) } )
172 );
173
174 test_psgi $app, sub {
175 my $cb = shift;
176
177 my $r = $cb->(
178 PUT '/from_params',
179 'Content-Type' => 'application/json',
180 Content => '---',
181 );
182
183 # Ensure error is logged
184 my $trap = $logger->trapper;
185 isa_ok( $trap, 'Dancer2::Logger::Capture::Trap' );
186
187 my $errors = $trap->read;
188 isa_ok( $errors, 'ARRAY' );
189 is( scalar @{$errors}, 1, 'One error caught' );
190
191 my $msg = $errors->[0];
192 delete $msg->{'formatted'};
193 isa_ok( $msg, 'HASH' );
194 is( scalar keys %{$msg}, 2, 'Two items in the error' );
195
196 my $err_regex = qr{
197 ^
198 \QFailed to deserialize content: \E
199 \Qmalformed number\E
200 }x;
201
202 is( $msg->{'level'}, 'core', 'Correct level' );
203 like( $msg->{'message'}, $err_regex, 'Logged correct error message' );
204
205 # Check we get a 444 response
206 is( $r->code, 444, "444 custom response" );
207 my $content = Dancer2::Serializer::JSON::decode_json( $r->content );
208 like( $content->{message}, $err_regex, "Failed to deserialize content error");
209
210 }
211 }
212