CatalystX-CRUD-Controller-REST

 view release on metacpan or  search on metacpan

t/001-file.t  view on Meta::CPAN

#!/usr/bin/env perl

use Test::More tests => 43;
use strict;
use lib qw( lib t/lib );
use_ok('CatalystX::CRUD::Model::File');
use_ok('CatalystX::CRUD::Object::File');

use Catalyst::Test 'MyApp';
use Data::Dump qw( dump );
use HTTP::Request::Common;
use JSON;

####################################################
# basic CRUD

sub json_PUT {
    my ( $url, $body, $headers ) = @_;
    my $req = HTTP::Request->new( PUT => $url );
    $req->headers($headers) if $headers;
    $req->header( 'Content-Type'   => 'application/json' );
    $req->header( 'Content-Length' => length($body) );
    $req->content($body);
    $req;
}

my $res;

# confirm testfile is not there
ok( $res = request( GET('/rest/file/testfile') ), "GET testfile" );
is( $res->code, 404, "no testfile at start" );

# create testfile
ok( $res = request(
        json_PUT(
            '/rest/file/testfile', encode_json( { content => 'hello world' } )
        )
    ),
    "PUT new file"
);
is( $res->code, 201, "PUT returns 201" );
is_deeply(
    decode_json( $res->content ),
    { content => "hello world", file => "testfile" },
    "PUT new file response"
);

# read the file we just created
ok( $res = request( HTTP::Request->new( GET => '/rest/file/testfile' ) ),
    "GET new file" );

#diag( $res->content );

is_deeply(
    decode_json( $res->content ),
    { content => "hello world", file => "testfile" },
    "GET file response"
);

# update the file
ok( $res = request(
        json_PUT(
            '/rest/file/testfile', encode_json( { content => 'foo bar baz' } )
        )
    ),
    "update file"
);

is_deeply(
    decode_json( $res->content ),
    { content => "foo bar baz", file => "testfile" },
    "PUT file update response"
);

####################################################
# create another new file
ok( $res = request(
        json_PUT(
            '/rest/file/otherdir%2ftestfile2',
            encode_json( { content => 'hello world 2' } )
        )
    ),
    "PUT new file2"
);

is_deeply(
    decode_json( $res->content ),
    { content => "hello world 2", file => "otherdir/testfile2" },
    "PUT new file2 response"
);

is( $res->code, 201, "new file 201 status" );

###################################################
# test with no args

#system("tree t/lib/MyApp/root");

ok( $res = request('/rest/file'), "/ request with multiple items" );
is( $res->code, 200, "/ request with multiple items lists" );

#diag( dump( decode_json( $res->content ) ) );
is_deeply(
    decode_json( $res->content ),
    {   count   => 2,
        query   => 1,
        results => [
            { content => "foo bar baz",   file => "./testfile" },
            { content => "hello world 2", file => "otherdir/testfile2" },



( run in 1.581 second using v1.01-cache-2.11-cpan-39bf76dae61 )