### ----------------------------------------------------
### -- JSON::Hjson
### -- Licenses: Artistic-2.0
### -- Authors: Takumi Akiyama
### -- File: t/02-testcases.t
### ----------------------------------------------------
use v6;
use Test;
use JSON::Hjson;
use JSON::Fast;

my @files = dir('t/testCases').grep: /_test\.h?json$/;
for @files -> $f {
    my $text = slurp($f);
    my $name = $f.basename;
    if ($f.basename ~~ /^fail/) {
        dies-ok { from-hjson($text) }, $name;
    } else {
        my $got = coerce-numeric(from-hjson($text));
        my $result = $f.subst(/_test.h?json$/, '_result.json');
        my $expected = from-json(slurp($result));
        # XXX Prefer not to use `is-deeply` due to rational number comparison
        #     (See also t/testCases/pass1_test.json)
        # is-deeply $got, $expected, $name;
        cmp-ok $got.raku, 'eq', $expected.raku, $name;
    }
}

sub coerce-numeric($a) {
    given $a.WHAT {
        when Numeric {
            my $retval = $a;
            if $retval.WHAT === Num && $retval.raku ~~ /e0$/ {
                $retval = $retval.Rat;
            }
            if $retval.WHAT === Rat && $retval.raku ~~ /\.0$/ {
                $retval = $retval.Int;
            }
            return $retval;
        }
        when Array {
            return [$a.map: { coerce-numeric($_) }];
        }
        when Hash {
            return ($a.pairs.map: { .key => coerce-numeric(.value) }).hash;
        }
    }
    return $a;
}

done-testing;


