File: upload_stream_lite_app.t

package info (click to toggle)
libmojolicious-perl 7.21%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 3,432 kB
  • ctags: 1,253
  • sloc: perl: 11,603; makefile: 10
file content (71 lines) | stat: -rw-r--r-- 1,679 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use Mojo::Base -strict;

BEGIN { $ENV{MOJO_REACTOR} = 'Mojo::Reactor::Poll' }

use Test::More;
use Mojolicious::Lite;
use Scalar::Util 'weaken';
use Test::Mojo;

# Stream multipart uploads into cache
my %cache;
hook after_build_tx => sub {
  my $tx = shift;

  weaken $tx;
  $tx->req->content->on(
    upgrade => sub {
      my ($single, $multi) = @_;

      return unless $tx->req->url->path->contains('/upload');

      my $id = $tx->req->url->query->param('id');
      $multi->on(
        part => sub {
          my ($multi, $single) = @_;
          $single->on(
            body => sub {
              my $single = shift;
              return unless $single->headers->content_disposition =~ /my_file/;
              $single->unsubscribe('read');
              $single->on(read => sub { $cache{$id} .= pop });
            }
          );
        }
      );
    }
  );
};

post '/upload' => sub {
  my $c  = shift;
  my $id = $c->param('id');
  $c->render(data => $cache{$id});
};

get '/download' => sub {
  my $c = shift;
  $c->render(data => $cache{$c->param('id')});
};

my $t = Test::Mojo->new;

# Small upload
$t->post_ok('/upload?id=23' => form => {my_file => {content => 'whatever'}})
  ->status_is(200)->content_is('whatever');

# Small download
$t->get_ok('/download?id=23')->status_is(200)->content_is('whatever');

# Big upload
$t->post_ok(
  '/upload?id=24' => form => {my_file => {content => '1234' x 131072}})
  ->status_is(200)->content_is('1234' x 131072);

# Big download
$t->get_ok('/download?id=24')->status_is(200)->content_is('1234' x 131072);

# Small download again
$t->get_ok('/download?id=23')->status_is(200)->content_is('whatever');

done_testing();