File: live.t

package info (click to toggle)
libtemplate-plugin-json-escape-perl 0.2-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 76 kB
  • sloc: perl: 63; makefile: 2
file content (98 lines) | stat: -rw-r--r-- 2,384 bytes parent folder | download | duplicates (2)
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
use strict;
use warnings;

use Test::More tests => 14;
use Template;
use JSON qw/from_json to_json/;

BEGIN {
    use_ok 'Template::Plugin::JSON::Escape';
}

{
    my $vars = {
        blah => { foo => "bar" },
        baz  => "ze special string wis some ' qvotes\"",
        oink => [ 1..3 ],
    };
    my $tt = Template->new;
    my $ret = $tt->process(
        \q{
            [%~ USE JSON.Escape( pretty => 1 ) ~%]
            { "blah":[% blah.json %], "baz":[% baz.json %], "oink":[% oink.json %] }
        },
        $vars,
        \my $out,
    );

    ok $ret, "template processing" or diag $tt->error;
    like $out, qr/\{\W*foo\W*:\W*bar\W*\}/, "output seems OK";
    like $out, qr/\n/, "pretty output";
    is_deeply from_json( $out ), $vars, "round tripping";
}

{
    my $warnings = 0;
    local $SIG{__WARN__} = sub { $warnings++ };
    my $tt = Template->new;
    my $ret = $tt->process(
        \q{
            [%~ USE JSON.Escape ~%]
            [%~ SET foo = [ 1, 2, 3 ]; foo.json ~%]
        },
        {},
        \my $out,
    );

    ok $ret, "template processing" or diag $tt->error;
    is $warnings, 0, "no warning";
}

{
    # pass JSON to the template
    my $tt = Template->new;
    my $ret = $tt->process(
        \q{
            [%~ USE JSON.Escape ~%]
            [%~ val = JSON.Escape.json_decode(json_string) ~%]
            [%~ 'ok' IF val.blah.foo == 'bar' ~%]
        },
        { json_string => '{ "blah": { "foo": "bar" }, "oink": [1, 2, 3] }' },
        \my $out,
    );

    ok $ret, "template processing" or diag $tt->error;
    is $out, 'ok', 'match on extract';
}

{
    my $tt = Template->new;
    my $ret = $tt->process(
        \q{
            [%~ USE JSON.Escape ~%]
            [%~ data.json ~%]
        },
        { data => { foo => 'bar & baz <3' } },
        \my $out,
    );

    ok $ret, "template processing" or diag $tt->error;
    unlike $out, qr/[<&]/, 'escape special characters';
}

{
    my $data = { foo => 'bar & baz <3' };
    my $tt = Template->new;
    my $ret = $tt->process(
        \q{
            [%~ USE JSON.Escape ~%]
            [%~ string | json ~%]
        },
        { string => to_json( $data ) },
        \my $out,
    );

    ok $ret, "template processing" or diag $tt->error;
    unlike $out, qr/[<&]/, 'escape special characters by filter';
    is_deeply from_json( $out ), $data, 'still valid json'
}