Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^3: Brannigan: hash validation

by henzen (Acolyte)
on Feb 15, 2018 at 10:03 UTC ( [id://1209198]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Brannigan: hash validation
in thread Brannigan: hash validation

Thanks 1nickt,

This looks like it will work - I've been able to figure out most from the docs (I really wish module creators would have real-life examples, but anyway).

Is there a way to do an array count validation?:
use strict; use warnings; package JSONTypes { use parent 'Type::Library'; use Type::Utils; use Types::Standard qw/ Dict Enum Str Tuple ArrayRef Optional Rege +xpRef Int /; declare JSONType => as Dict[ method => Enum[qw(xxx yyy)], backend => Dict[ num => Int, other => Optional[Str], StrMatch[qr/^[a-z0-9]+$/] ], # following works, but how to check that the array has at least + (say) 2 elements - {2,} clientArr => ArrayRef[ Dict[ num => Int, ], ] ]; }; package main { use JSON; JSONTypes->import(qw/ +JSONType /); my $data = from_json q|{ "method": "xxx", "backend": { "num": 1, "client": "mytest009b" }, "clientArr": [{ "num": "1" }, { "num": "2" }] }|; my $ret = eval { assert_JSONType( $data ); }; if ($@) { print "ERROR\n$@\n"; } else { print "OK\n"; } };

I'd appreciate any pointers.

Thanks

Edit: Figured out regex - use StrMatch[]
Edit 2: Validating array count can be done with an anon sub, but it then kills the other check:
clientArr => ArrayRef[ Dict[ num => Int, ], ], clientArr => sub { if (scalar @$_ < 2) { print "ERROR: clientArr too small\n"; exit 1; } else { } return 1; }

So I guess the question is how to combine those two checks (without having to hand code the num=>Int checks in pure Perl of course).

Replies are listed 'Best First'.
Re^4: Brannigan: hash validation
by 1nickt (Canon) on Feb 15, 2018 at 13:47 UTC

    Hi again,

    First, be sure to check Type::Params for a more user-friendly way to use the types and type libraries you create (and the standard ones) in validating parameters to a function. Second, be sure to review all the docs, including the cookbooks. There's actually quite a lot, just not well collated centrally. You'll also find good examples in the archives of the Perl Advent Calendar.

    Type RegexpRef tests only whether it is passed a compiled regexp, i.e. with qr//, not the content of the regexp. Use StrMatch for that.

    You can always declare your own types, as well as your own type library. Here I declare a type that requires an array ref, and that it be of a certain length.

    # ~/monks/1209129.t package MyTypes { use parent 'Type::Library'; use Type::Utils; use Types::Standard qw/ ArrayRef Dict Enum Str StrMatch /; my $MyArray = Type::Tiny->new( as => 'ArrayRef', name => 'ClientArray', constraint => sub { scalar @{ $_ } == 2 }, ); declare MyType => as Dict[ method => Enum['xxx'], backend => Dict[ client => StrMatch[qr/\d{3}/], pw => Str, ], clientArr => $MyArray, ]; # If you want to be able to use the new type independently by name +: __PACKAGE__->meta->add_type($MyArray); __PACKAGE__->meta->make_immutable; }; package main { use Test::Most; use JSON; # normally, load as normal with `use MyTypes '+MyType'` MyTypes->import(qw/ +MyType /); while ( <DATA> ) { my ( $label, $json ) = split / => /; chomp $json; my $data = from_json $json; if ( $. == 1 ) { ok eval { assert_MyType( $data ); 1 }, $label; } else { ok ! eval { assert_MyType( $data ); 1 }, $label; } } done_testing; }; __END__ Valid data => {"method":"xxx","backend":{"client":"mytest009","pw":"sd +kjfhsfjhKJH87"},"clientArr":[{"num":"1"},{"num":"2"}]} Unknown key => {"method":"xxx","backend":{"client":"mytest009","pw":"s +dkjfhsfjhKJH87"},"clientArr":[{"num":"1"},{"num":"2"}],"blah":"123"} Failed regexp => {"method":"xxx","backend":{"client":"mytest09","pw":" +sdkjfhsfjhKJH87"},"clientArr":[{"num":"1"},{"num":"2"}]} Not an array => {"method":"xxx","backend":{"client":"mytest009","pw":" +sdkjfhsfjhKJH87"},"clientArr":{"foo":{"num":"1"},"bar":{"num":"2"}}} Array too long => {"method":"xxx","backend":{"client":"mytest009","pw" +:"sdkjfhsfjhKJH87"},"clientArr":[{"num":"1"},{"num":"2"},{"num":"3"}] +}
    Output:
    $ prove -v ~/monks/1209129.t ok 1 - Valid data ok 2 - Unknown key ok 3 - Failed regexp ok 4 - Not an array ok 5 - Array too long 1..5 ok All tests successful. Files=1, Tests=5, 1 wallclock secs ( 0.03 usr 0.00 sys + 0.13 cusr + 0.02 csys = 0.18 CPU) Result: PASS

    Hope this helps!


    The way forward always starts with a minimal test.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1209198]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-04-20 04:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found