File: 502-example-long-poll.t

package info (click to toggle)
libweb-machine-perl 0.17-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 940 kB
  • sloc: perl: 5,481; makefile: 2
file content (108 lines) | stat: -rw-r--r-- 2,352 bytes parent folder | download | duplicates (5)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;

BEGIN {
    if (!eval { require Test::TCP; Test::TCP->import; 1 }) {
        plan skip_all => "Test::TCP is required for this test";
    }
    if (!eval { require JSON::XS; JSON::XS->import; 1 }) {
        plan skip_all => "JSON is required for this test";
    }
}

use Net::HTTP;
use Plack::Runner;

use Web::Machine;

pipe(my $read, my $write);
alarm(60);

{
    package My::Resource;
    use strict;
    use warnings;

    use IO::Handle::Util 'io_from_getline';

    use parent 'Web::Machine::Resource';

    sub content_types_provided { [{ 'application/json' => 'to_json' }] }

    sub to_json {
        my $self = shift;

        my @lines = (
            '[',
            '{"foo": "1"}',
            '{"bar": "2"}',
            '{"baz": "3"}',
            ']',
        );

        return io_from_getline sub {
            { sysread($read, my $buf, 1) }
            my $line = shift @lines;
            return "$line\n";
        };
    }
}

my $app = Web::Machine->new(resource => 'My::Resource')->to_app;

test_tcp
    client => sub {
        my ($port, $pid) = @_;

        close $read;

        my $http = Net::HTTP->new(
            Host     => 'localhost',
            PeerPort => $port,
        );
        $http->write_request(GET => '/', Accept => 'application/json');

        my ($code, $mess, %headers) = $http->read_response_headers;
        is($code, 200);
        is($headers{'Content-Type'}, 'application/json');

        syswrite($write, 'a');

        my $chunk;
        $http->read_entity_body($chunk, 1024);
        is($chunk, "[\n");

        syswrite($write, 'a');

        $http->read_entity_body($chunk, 1024);
        is_deeply(decode_json($chunk), { foo => 1 });

        syswrite($write, 'a');

        $http->read_entity_body($chunk, 1024);
        is_deeply(decode_json($chunk), { bar => 2 });

        syswrite($write, 'a');

        $http->read_entity_body($chunk, 1024);
        is_deeply(decode_json($chunk), { baz => 3 });
    },
    server => sub {
        my ($port) = @_;

        close $write;

        my $runner = Plack::Runner->new;
        $runner->parse_options(
            '--server' => 'Standalone',
            '--env'    => 'test',
            '--port'   => $port,
        );
        $runner->run($app);
    };

alarm(0);

done_testing;