jsonfmt: Add TO_JSON convert_blessed support

This commit is contained in:
Yorhel 2025-01-29 13:59:49 +01:00
parent 8ef2a724d1
commit a85ff98914
2 changed files with 51 additions and 11 deletions

View file

@ -5,19 +5,24 @@ use Tie::Array;
use Tie::Hash;
use FU::Util 'json_format';
# TODO: gab some more tests from other JSON libs
# TODO: Test invalid utf8
sub MyToJSON::TO_JSON { [scalar @_, ref $_[0], ${$_[0]}] }
sub MyToJSONSelf::TO_JSON { $_[0] }
my @tests = (
undef, 'null',
true, 'true',
false, 'false',
0, '0',
1, '1',
-1, '-1',
-9223372036854775808, '-9223372036854775808',
9223372036854775807, '9223372036854775807',
18446744073709551615, '18446744073709551615',
(map +($_, $_),
-1000..1000,
12345, 123456, 1234567,
98765, 987654, 9876543,
-12345, -123456, -1234567,
-98765, -987654, -9876543,
-9223372036854775808,
9223372036854775807,
18446744073709551615,
),
0.1, '0.1',
0.000123, '0.000123',
-1e100, '-1e+100',
@ -42,6 +47,9 @@ my @tests = (
do { tie my %h, 'Tie::StdHash'; %h = ('a',1); \%h }, '{"a":1}',
do { tie my %h, 'MyOrderedHash', one => 1, two => undef, three => []; \%h }, '{"one":1,"two":null,"three":[]}',
do { my $o = [true]; bless \$o, 'MyToJSON' }, '[1,"MyToJSON",[true]]',
do { my $x = [true]; my $o = [bless \$x, 'MyToJSON']; bless \$o, 'MyToJSON' }, '[1,"MyToJSON",[[1,"MyToJSON",[true]]]]',
# from http://e-choroba.eu/18-yapc
$$, $$,
''.$$, '"'.$$.'"',
@ -56,6 +64,8 @@ my @errors = (
'NaN'+0, qr/unable to format floating point NaN or Inf as JSON/,
'Inf'+0, qr/unable to format floating point NaN or Inf as JSON/,
do { no warnings 'portable'; "\x{ffffffff}" }, qr/invalid codepoint encountered in string/,
do { my $o = {}; bless $o, 'FU::Whatever' }, qr/unable to format 'FU::Whatever' object as JSON/,
do { my $o = {}; bless $o, 'MyToJSONSelf' }, qr/MyToJSONSelf::TO_JSON method returned same object as was passed instead of a new one/,
);
plan tests => @tests*2 + @errors/2 + 6;