File: 07_ajax_plack_builder.t

package info (click to toggle)
libdancer-perl 1.3521%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,460 kB
  • sloc: perl: 7,436; xml: 2,211; sh: 54; makefile: 32; sql: 5
file content (73 lines) | stat: -rw-r--r-- 2,022 bytes parent folder | download | duplicates (3)
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
use strict;
use warnings;
use Test::More import => ['!pass'];
use Dancer::Plugin::Ajax;
# GH #671

BEGIN {
    use Dancer::ModuleLoader;
    plan skip_all => "skip test with Test::TCP in win32" if $^O eq 'MSWin32';
    plan skip_all => "Test::TCP is needed to run this test"
      unless Dancer::ModuleLoader->load('Test::TCP' => "1.30");
    plan skip_all => "Plack is needed to run this test"
      unless Dancer::ModuleLoader->load('Plack::Builder');
}

use HTTP::Tiny::NoProxy;
use Plack::Builder;
use HTTP::Server::Simple::PSGI;

plan tests => 6;

my $js_content = q[<script type="text/javascript">
    var xhr = new XMLHttpRequest();
    xhr.open( 'POST', '/foo' );
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.send();
    </script>
];

Test::TCP::test_tcp(
    client => sub {
        my $port = shift;
        my $url  = "http://127.0.0.1:$port/";

        my $ua  = HTTP::Tiny::NoProxy->new();

        ok my $res = $ua->get($url), 'Got GET result';
        ok $res->{success}, 'Successful';
        is $res->{content}, $js_content, 'Correct JS content';

        my %headers = ( 'X-Requested-With' => 'XMLHttpRequest' );

        ok( $res = $ua->post("${url}foo", { headers => \%headers }), 'Got POST result' );
        ok( $res->{success}, 'Successful' );
        is( $res->{content}, 'bar', 'Correct content' );
    },

    server => sub {
        my $port    = shift;
        my $handler = sub {
            use Dancer;

            set port => $port, server => '127.0.0.1', apphandler => 'PSGI', startup_info => 0;

            get  '/'    => sub {$js_content};
            ajax '/foo' => sub {'bar'};

            my $env     = shift;
            my $request = Dancer::Request->new( env => $env );
            Dancer->dance($request);
        };

        my $app = builder {
            mount "/" => $handler;
        };

        my $server = HTTP::Server::Simple::PSGI->new($port);
        $server->host("127.0.0.1");
        $server->app($app);
        $server->run;
    },
);