Cn-Util
view release on metacpan or search on metacpan
#!/usr/bin/env perl
# json_file_to_ref() / ref_to_json_file(): JSON round-trip, plus the
# NaN/Infinity -> null rewrite that json_file_to_ref performs for
# Python/NumPy-emitted files.
require 5.010001;
use strict;
use warnings FATAL => 'all';
use Test::More;
use Test::Exception;
use Capture::Tiny 'capture';
use File::Temp qw(tempfile tempdir);
use File::Spec;
use Cn::Util;
my $dir = tempdir( CLEANUP => 1 );
# --- round trip through both functions ---
# NB: no JSON booleans (\1) here -- those decode to JSON::PP::Boolean objects,
# not back to \1, so is_deeply would (correctly) report them as unequal.
my $data = { name => 'x', nums => [1, 2, 3], nested => { ok => 'yes' } };
my $out = File::Spec->catfile($dir, 'rt.json');
my $returned;
capture { $returned = ref_to_json_file($data, $out) }; # prints "Wrote ..."
is( $returned, $out, 'ref_to_json_file returns the filename it wrote' );
ok( -s $out, 'ref_to_json_file created a non-empty file' );
# Captured output is not a terminal, so the name is not colored unless
# CLICOLOR_FORCE asks for it. Up to 0.024 it always was.
{
local $ENV{NO_COLOR};
local $ENV{CLICOLOR_FORCE};
my ($said) = capture { ref_to_json_file($data, $out) };
is( $said, "Wrote $out\n", 'ref_to_json_file prints no color codes into a pipe' );
$ENV{CLICOLOR_FORCE} = 1;
($said) = capture { ref_to_json_file($data, $out) };
like( $said, qr/\AWrote \e\[/, '...unless CLICOLOR_FORCE is set' );
$ENV{NO_COLOR} = 1;
($said) = capture { ref_to_json_file($data, $out) };
is( $said, "Wrote $out\n", '...and NO_COLOR outranks CLICOLOR_FORCE' );
}
my $back = json_file_to_ref($out);
is_deeply( $back, $data, 'data survives a write/read round trip' );
# --- NaN / Infinity handling ---
my $nan = File::Spec->catfile($dir, 'nan.json');
open my $nfh, '>', $nan or die $!;
print $nfh '{"a": NaN, "b": [1, Infinity, -Infinity], "c": "NaN in string"}';
close $nfh;
my $ref = json_file_to_ref($nan);
ok( !defined $ref->{a}, 'bare NaN becomes undef' );
is( $ref->{b}[0], 1, 'real numbers next to Infinity are preserved' );
ok( !defined $ref->{b}[1], 'bare Infinity becomes undef' );
ok( !defined $ref->{b}[2], 'bare -Infinity becomes undef' );
is( "$ref->{c}", 'NaN in string',
'the literal text "NaN" inside a string is NOT rewritten' );
# Inside a string, NaN after '[', ',' or ':' looks like a value to a pattern
# that does not know where strings begin and end; these used to be rewritten.
my $instr = File::Spec->catfile($dir, 'instr.json');
open my $ifh, '>', $instr or die $!;
print $ifh '{"msg": "values: [1, NaN, 2]", "esc": "q\\": NaN}", "x": [1, NaN], "k:NaN,": -Infinity}';
close $ifh;
$ref = json_file_to_ref($instr);
is( $ref->{msg}, 'values: [1, NaN, 2]', 'NaN in value position inside a string is left alone' );
is( $ref->{esc}, 'q": NaN}', 'an escaped quote does not end the string early' );
ok( !defined $ref->{x}[1], 'a bare NaN after the strings is still rewritten' );
ok( exists $ref->{'k:NaN,'} && !defined $ref->{'k:NaN,'},
'a key holding ":NaN," is left alone, and its -Infinity value is rewritten' );
# A bare NaN or -Infinity as the whole document, as Python's
# json.dumps(float('nan')) writes it. Up to 0.0242 it reached decode_json
# unchanged and died. A backend that refuses a top-level scalar refuses the
# null it becomes, too, so the test skips there.
SKIP: {
require JSON::MaybeXS;
skip 'this JSON backend refuses a top-level scalar', 2
unless eval { JSON::MaybeXS::decode_json('null'); 1 };
for my $text ("NaN", " -Infinity\n") {
my $top = File::Spec->catfile($dir, 'top.json');
open my $tfh, '>', $top or die $!;
print $tfh $text;
close $tfh;
my $got = eval { json_file_to_ref($top) };
(my $shown = $text) =~ s/\s+//g;
ok( !$@ && !defined $got, "a document of only $shown, whitespace around it or not, is read as undef" );
}
}
# A structure encode_json refuses dies before the file is opened, so the file
# keeps what it held. Up to 0.0242 it was opened, and so emptied, first.
{
my $keep = File::Spec->catfile($dir, 'keep.json');
capture { ref_to_json_file({ kept => 1 }, $keep) };
my $size = -s $keep;
my $loop = [];
push @$loop, $loop;
for my $bad ([ 'a reference to itself', $loop ], [ 'a code reference', { f => sub { 1 } } ]) {
my ($what, $ref) = @$bad;
dies_ok { capture { ref_to_json_file($ref, $keep) } } "a structure holding $what dies";
is( -s $keep, $size, "...and the existing file is untouched" );
}
is_deeply( json_file_to_ref($keep), { kept => 1 }, 'the file still decodes to what it held' );
}
# --- error handling ---
throws_ok { json_file_to_ref(File::Spec->catfile($dir, 'missing.json')) }
qr/doesn't exist/, 'missing file is rejected';
my $empty = File::Spec->catfile($dir, 'empty.json');
open my $efh, '>', $empty or die $!; close $efh;
throws_ok { json_file_to_ref($empty) } qr/0 size/, 'zero-size file is rejected';
throws_ok { ref_to_json_file($data, [] ) }
qr/isn't a scalar/, 'ref_to_json_file rejects a non-scalar filename';
SKIP: {
# An absolute path, against the rule for t/: /dev/full, whose every write
# fails with ENOSPC, is the only way to make close() fail here, and it
# exists only on Linux, so the test skips everywhere else.
skip '/dev/full is Linux-only', 1 unless $^O eq 'linux' && -c '/dev/full' && -w _;
throws_ok { capture { ref_to_json_file($data, '/dev/full') } }
qr/can't write/, 'ref_to_json_file dies when the write fails at close';
}
done_testing;
( run in 0.657 second using v1.01-cache-2.11-cpan-60884a8df76 )