Imported Upstream version 0.16
[liburi-template-perl.git] / t / 12-suite.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Scalar::Util ();
6
7 BEGIN {
8     eval "use JSON ();";
9     plan skip_all => "JSON required" if $@;
10     plan( 'no_plan' );
11     use_ok( 'URI::Template' );
12 }
13
14 my @files = glob( $ENV{ UT_SPEC_GLOB } || 't/cases/*.json' );
15
16 for my $file ( @files ) {
17     next unless -e $file;
18
19     # skip these tests for now
20     next if $file =~ m{negative};
21
22     open( my $json, $file );
23     my $data = do { local $/; <$json> };
24     close( $json );
25
26     eval { JSON->VERSION( 2 ) };
27     my $suite = $@ ? JSON::jsonToObj( $data ) : JSON::from_json( $data );
28
29     for my $name ( sort keys %$suite ) {
30         my $info  = $suite->{ $name };
31         my $vars  = $info->{ variables };
32         my $cases = $info->{ testcases };
33
34         note( sprintf( '%s [level %d]', $name, ( $info->{ level } || 4 ) ) );
35
36         for my $case ( @$cases ) {
37             my ( $input, $expect ) = @$case;
38             my $result;
39             eval {
40                 my $template = URI::Template->new( $input );
41                 $result = $template->process_to_string( $vars );
42             };
43
44             _check_result( $result, $expect, $input );
45         }
46
47     }
48 }
49
50 sub _check_result {
51     my ( $result, $expect, $input ) = @_;
52
53     # boolean
54     if ( Scalar::Util::blessed( $expect ) ) {
55         ok( !defined $result, $input );
56     }
57
58     # list of possible results
59     elsif ( ref $expect ) {
60         my $ok = 0;
61         for my $e ( @$expect ) {
62             if ( $result eq $e ) {
63                 $ok = 1;
64                 last;
65             }
66         }
67         diag( "got: $result" ) if !$ok;
68         ok( $ok, $input );
69     }
70
71     # exact comparison
72     else {
73         is( $result, $expect, $input );
74     }
75 }