[go: up one dir, main page]

File: More.pm

package info (click to toggle)
libcarp-assert-more-perl 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 312 kB
  • sloc: perl: 1,918; makefile: 2
file content (1307 lines) | stat: -rw-r--r-- 29,200 bytes parent folder | download
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
package Carp::Assert::More;

use 5.010;
use strict;
use warnings;

use Exporter;
use Scalar::Util qw( looks_like_number );;

use vars qw( $VERSION @ISA @EXPORT );

=head1 NAME

Carp::Assert::More - Convenience assertions for common situations

=head1 VERSION

Version 2.2.0

=cut

BEGIN {
    $VERSION = '2.2.0';
    @ISA = qw(Exporter);
    @EXPORT = qw(
        assert_all_keys_in
        assert_aoh
        assert_arrayref
        assert_arrayref_nonempty
        assert_cmp
        assert_coderef
        assert_context_nonvoid
        assert_context_scalar
        assert_datetime
        assert_defined
        assert_empty
        assert_exists
        assert_fail
        assert_hashref
        assert_hashref_nonempty
        assert_in
        assert_integer
        assert_is
        assert_isa
        assert_isa_in
        assert_isnt
        assert_keys_are
        assert_lacks
        assert_like
        assert_listref
        assert_negative
        assert_negative_integer
        assert_nonblank
        assert_nonempty
        assert_nonnegative
        assert_nonnegative_integer
        assert_nonref
        assert_nonzero
        assert_nonzero_integer
        assert_numeric
        assert_positive
        assert_positive_integer
        assert_undefined
        assert_unlike
    );
}

my $INTEGER = qr/^-?\d+$/;

=head1 SYNOPSIS

A set of convenience functions for common assertions.

    use Carp::Assert::More;

    my $obj = My::Object;
    assert_isa( $obj, 'My::Object', 'Got back a correct object' );

=head1 DESCRIPTION

Carp::Assert::More is a convenient set of assertions to make the habit
of writing assertions even easier.

Everything in here is effectively syntactic sugar.  There's no technical
difference between calling one of these functions:

    assert_datetime( $foo );
    assert_isa( $foo, 'DateTime' );

that are provided by Carp::Assert::More and calling these assertions
from Carp::Assert

    assert( defined $foo );
    assert( ref($foo) eq 'DateTime' );

My intent here is to make common assertions easy so that we as programmers
have no excuse to not use them.

=head1 SIMPLE ASSERTIONS

=head2 assert_is( $string, $match [,$name] )

Asserts that I<$string> matches I<$match>.

=cut

sub assert_is($$;$) {
    my $string = shift;
    my $match = shift;
    my $name = shift;

    if ( defined($string) ) {
        return if defined($match) && ($string eq $match);
    }
    else {
        return if !defined($match);
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_isnt( $string, $unmatch [,$name] )

Asserts that I<$string> does NOT match I<$unmatch>.

=cut

sub assert_isnt($$;$) {
    my $string = shift;
    my $unmatch = shift;
    my $name = shift;

    # undef only matches undef
    return if defined($string) xor defined($unmatch);

    return if defined($string) && defined($unmatch) && ($string ne $unmatch);

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_cmp( $x, $op, $y [,$name] )

Asserts that the relation C<$x $op $y> is true. For example:

    assert_cmp( $divisor, '!=', 0, 'Divisor must not be zero' );

is the same as:

    assert( $divisor != 0, 'Divisor must not be zero' );

but with better error reporting.

The following operators are supported:

=over 4

=item * == numeric equal

=item * != numeric not equal

=item * > numeric greater than

=item * >= numeric greater than or equal

=item * < numeric less than

=item * <= numeric less than or equal

=item * lt string less than

=item * le string less than or equal

=item * gt string less than

=item * ge string less than or equal

=back

There is no support for C<eq> or C<ne> because those already have
C<assert_is> and C<assert_isnt>, respectively.

If either C<$x> or C<$y> is undef, the assertion will fail.

If the operator is numeric, and C<$x> or C<$y> are not numbers, the assertion will fail.

=cut

sub assert_cmp($$$;$) {
    my $x    = shift;
    my $op   = shift;
    my $y    = shift;
    my $name = shift;

    my $why;

    if ( !defined($op) ) {
        $why = 'Invalid operator <undef>';
    }
    elsif ( $op eq '==' ) {
        return if looks_like_number($x) && looks_like_number($y) && ($x == $y);
    }
    elsif ( $op eq '!=' ) {
        return if looks_like_number($x) && looks_like_number($y) && ($x != $y);
    }
    elsif ( $op eq '<' ) {
        return if looks_like_number($x) && looks_like_number($y) && ($x < $y);
    }
    elsif ( $op eq '<=' ) {
        return if looks_like_number($x) && looks_like_number($y) && ($x <= $y);
    }
    elsif ( $op eq '>' ) {
        return if looks_like_number($x) && looks_like_number($y) && ($x > $y);
    }
    elsif ( $op eq '>=' ) {
        return if looks_like_number($x) && looks_like_number($y) && ($x >= $y);
    }
    elsif ( $op eq 'lt' ) {
        return if defined($x) && defined($y) && ($x lt $y);
    }
    elsif ( $op eq 'le' ) {
        return if defined($x) && defined($y) && ($x le $y);
    }
    elsif ( $op eq 'gt' ) {
        return if defined($x) && defined($y) && ($x gt $y);
    }
    elsif ( $op eq 'ge' ) {
        return if defined($x) && defined($y) && ($x ge $y);
    }
    else {
        $why = qq{Invalid operator "$op"};
    }

    $why //= "Failed: " . ($x // 'undef') . ' ' . $op . ' ' . ($y // 'undef');

    require Carp;
    &Carp::confess( _failure_msg($name, $why) );
}


=head2 assert_like( $string, qr/regex/ [,$name] )

Asserts that I<$string> matches I<qr/regex/>.

The assertion fails either the string or the regex are undef.

=cut

sub assert_like($$;$) {
    my $string = shift;
    my $regex = shift;
    my $name = shift;

    if ( defined($string) && !ref($string) ) {
        if ( ref($regex) ) {
            return if $string =~ $regex;
        }
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_unlike( $string, qr/regex/ [,$name] )

Asserts that I<$string> matches I<qr/regex/>.

The assertion fails if the regex is undef.

=cut

sub assert_unlike($$;$) {
    my $string = shift;
    my $regex  = shift;
    my $name   = shift;

    return if !defined($string);

    if ( ref($regex) eq 'Regexp' ) {
        return if $string !~ $regex;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_defined( $this [, $name] )

Asserts that I<$this> is defined.

=cut

sub assert_defined($;$) {
    return if defined( $_[0] );

    require Carp;
    &Carp::confess( _failure_msg($_[1]) );
}


=head2 assert_undefined( $this [, $name] )

Asserts that I<$this> is not defined.

=cut

sub assert_undefined($;$) {
    return unless defined( $_[0] );

    require Carp;
    &Carp::confess( _failure_msg($_[1]) );
}

=head2 assert_nonblank( $this [, $name] )

Asserts that I<$this> is not a reference and is not an empty string.

=cut

sub assert_nonblank($;$) {
    my $this = shift;
    my $name = shift;

    my $why;
    if ( !defined($this) ) {
        $why = 'Value is undef.';
    }
    else {
        if ( ref($this) ) {
            $why = 'Value is a reference to ' . ref($this) . '.';
        }
        else {
            return if $this ne '';
            $why = 'Value is blank.';
        }
    }

    require Carp;
    &Carp::confess( _failure_msg($name, $why) );
}


=head1 NUMERIC ASSERTIONS

=head2 assert_numeric( $n [, $name] )

Asserts that C<$n> looks like a number, according to C<Scalar::Util::looks_like_number>.
C<undef> will always fail.

=cut

sub assert_numeric {
    my $n    = shift;
    my $name = shift;

    return if Scalar::Util::looks_like_number( $n );

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_integer( $this [, $name ] )

Asserts that I<$this> is an integer, which may be zero or negative.

    assert_integer( 0 );      # pass
    assert_integer( 14 );     # pass
    assert_integer( -14 );    # pass
    assert_integer( '14.' );  # FAIL

=cut

sub assert_integer($;$) {
    my $this = shift;
    my $name = shift;

    if ( defined($this) ) {
        return if $this =~ $INTEGER;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_nonzero( $this [, $name ] )

Asserts that the numeric value of I<$this> is defined and is not zero.

    assert_nonzero( 0 );    # FAIL
    assert_nonzero( -14 );  # pass
    assert_nonzero( '14.' );  # pass

=cut

sub assert_nonzero($;$) {
    my $this = shift;
    my $name = shift;

    if ( Scalar::Util::looks_like_number($this) ) {
        return if $this != 0;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_positive( $this [, $name ] )

Asserts that I<$this> is defined, numeric and greater than zero.

    assert_positive( 0 );    # FAIL
    assert_positive( -14 );  # FAIL
    assert_positive( '14.' );  # pass

=cut

sub assert_positive($;$) {
    my $this = shift;
    my $name = shift;

    if ( Scalar::Util::looks_like_number($this) ) {
        return if ($this+0 > 0);
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_nonnegative( $this [, $name ] )

Asserts that I<$this> is defined, numeric and greater than or equal
to zero.

    assert_nonnegative( 0 );      # pass
    assert_nonnegative( -14 );    # FAIL
    assert_nonnegative( '14.' );  # pass
    assert_nonnegative( 'dog' );  # pass

=cut

sub assert_nonnegative($;$) {
    my $this = shift;
    my $name = shift;

    if ( Scalar::Util::looks_like_number( $this ) ) {
        return if $this >= 0;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_negative( $this [, $name ] )

Asserts that the numeric value of I<$this> is defined and less than zero.

    assert_negative( 0 );       # FAIL
    assert_negative( -14 );     # pass
    assert_negative( '14.' );   # FAIL

=cut

sub assert_negative($;$) {
    my $this = shift;
    my $name = shift;

    no warnings;
    return if defined($this) && ($this+0 < 0);

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_nonzero_integer( $this [, $name ] )

Asserts that the numeric value of I<$this> is defined, an integer, and not zero.

    assert_nonzero_integer( 0 );      # FAIL
    assert_nonzero_integer( -14 );    # pass
    assert_nonzero_integer( '14.' );  # FAIL

=cut

sub assert_nonzero_integer($;$) {
    my $this = shift;
    my $name = shift;

    if ( defined($this) && ($this =~ $INTEGER) ) {
        return if $this != 0;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_positive_integer( $this [, $name ] )

Asserts that the numeric value of I<$this> is defined, an integer and greater than zero.

    assert_positive_integer( 0 );     # FAIL
    assert_positive_integer( -14 );   # FAIL
    assert_positive_integer( '14.' ); # FAIL
    assert_positive_integer( '14' );  # pass

=cut

sub assert_positive_integer($;$) {
    my $this = shift;
    my $name = shift;

    if ( defined($this) && ($this =~ $INTEGER) ) {
        return if $this > 0;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_nonnegative_integer( $this [, $name ] )

Asserts that the numeric value of I<$this> is defined, an integer, and not less than zero.

    assert_nonnegative_integer( 0 );      # pass
    assert_nonnegative_integer( -14 );    # FAIL
    assert_nonnegative_integer( '14.' );  # FAIL

=cut

sub assert_nonnegative_integer($;$) {
    my $this = shift;
    my $name = shift;

    if ( defined($this) && ($this =~ $INTEGER) ) {
        return if $this >= 0;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_negative_integer( $this [, $name ] )

Asserts that the numeric value of I<$this> is defined, an integer, and less than zero.

    assert_negative_integer( 0 );      # FAIL
    assert_negative_integer( -14 );    # pass
    assert_negative_integer( '14.' );  # FAIL

=cut

sub assert_negative_integer($;$) {
    my $this = shift;
    my $name = shift;

    if ( defined($this) && ($this =~ $INTEGER) ) {
        return if $this < 0;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head1 REFERENCE ASSERTIONS

=head2 assert_isa( $this, $type [, $name ] )

Asserts that I<$this> is an object of type I<$type>.

=cut

sub assert_isa($$;$) {
    my $this = shift;
    my $type = shift;
    my $name = shift;

    # The assertion is true if
    # 1) For objects, $this is of class $type or of a subclass of $type
    # 2) For non-objects, $this is a reference to a HASH, SCALAR, ARRAY, etc.

    return if Scalar::Util::blessed( $this ) && $this->isa( $type );
    return if ref($this) eq $type;

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_isa_in( $obj, \@types [, $description] )

Assert that the blessed C<$obj> isa one of the types in C<\@types>.

    assert_isa_in( $obj, [ 'My::Foo', 'My::Bar' ], 'Must pass either a Foo or Bar object' );

=cut

sub assert_isa_in($$;$) {
    my $obj   = shift;
    my $types = shift;
    my $name  = shift;

    if ( Scalar::Util::blessed($obj) ) {
        for ( @{$types} ) {
            return if $obj->isa($_);
        }
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_empty( $this [, $name ] )

I<$this> must be a ref to either a hash or an array.  Asserts that that
collection contains no elements.  Will assert (with its own message,
not I<$name>) unless given a hash or array ref.   It is OK if I<$this> has
been blessed into objecthood, but the semantics of checking an object to see
if it does not have keys (for a hashref) or returns 0 in scalar context (for
an array ref) may not be what you want.

    assert_empty( 0 );       # FAIL
    assert_empty( 'foo' );   # FAIL
    assert_empty( undef );   # FAIL
    assert_empty( {} );      # pass
    assert_empty( [] );      # pass
    assert_empty( {foo=>1} );# FAIL
    assert_empty( [1,2,3] ); # FAIL

=cut

sub assert_empty($;$) {
    my $ref = shift;
    my $name = shift;

    my $underlying_type;
    if ( Scalar::Util::blessed( $ref ) ) {
        $underlying_type = Scalar::Util::reftype( $ref );
    }
    else {
        $underlying_type = ref( $ref );
    }

    my $why;
    my $n;
    if ( $underlying_type eq 'HASH' ) {
        return if scalar keys %{$ref} == 0;
        $n = scalar keys %{$ref};
        $why = "Hash contains $n key";
    }
    elsif ( $underlying_type eq 'ARRAY' ) {
        return if @{$ref} == 0;
        $n = scalar @{$ref};
        $why = "Array contains $n element";
    }
    else {
        $why = 'Argument is not a hash or array.';
    }

    $why .= 's' if $n && ($n>1);
    $why .= '.';

    require Carp;
    &Carp::confess( _failure_msg($name, $why) );
}


=head2 assert_nonempty( $this [, $name ] )

I<$this> must be a ref to either a hash or an array.  Asserts that that
collection contains at least 1 element.  Will assert (with its own message,
not I<$name>) unless given a hash or array ref.   It is OK if I<$this> has
been blessed into objecthood, but the semantics of checking an object to see
if it has keys (for a hashref) or returns >0 in scalar context (for an array
ref) may not be what you want.

    assert_nonempty( 0 );       # FAIL
    assert_nonempty( 'foo' );   # FAIL
    assert_nonempty( undef );   # FAIL
    assert_nonempty( {} );      # FAIL
    assert_nonempty( [] );      # FAIL
    assert_nonempty( {foo=>1} );# pass
    assert_nonempty( [1,2,3] ); # pass

=cut

sub assert_nonempty($;$) {
    my $ref = shift;
    my $name = shift;

    my $underlying_type;
    if ( Scalar::Util::blessed( $ref ) ) {
        $underlying_type = Scalar::Util::reftype( $ref );
    }
    else {
        $underlying_type = ref( $ref );
    }

    my $why;
    my $n;
    if ( $underlying_type eq 'HASH' ) {
        return if scalar keys %{$ref} > 0;
        $why = "Hash contains 0 keys.";
    }
    elsif ( $underlying_type eq 'ARRAY' ) {
        return if scalar @{$ref} > 0;
        $why = "Array contains 0 elements.";
    }
    else {
        $why = 'Argument is not a hash or array.';
    }

    require Carp;
    &Carp::confess( _failure_msg($name, $why) );
}


=head2 assert_nonref( $this [, $name ] )

Asserts that I<$this> is not undef and not a reference.

=cut

sub assert_nonref($;$) {
    my $this = shift;
    my $name = shift;

    assert_defined( $this, $name );
    return unless ref( $this );

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_hashref( $ref [,$name] )

Asserts that I<$ref> is defined, and is a reference to a (possibly empty) hash.

B<NB:> This method returns I<false> for objects, even those whose underlying
data is a hashref. This is as it should be, under the assumptions that:

=over 4

=item (a)

you shouldn't rely on the underlying data structure of a particular class, and

=item (b)

you should use C<assert_isa> instead.

=back

=cut

sub assert_hashref($;$) {
    my $ref = shift;
    my $name = shift;

    if ( ref($ref) eq 'HASH' || (Scalar::Util::blessed( $ref ) && $ref->isa( 'HASH' )) ) {
        return;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_hashref_nonempty( $ref [,$name] )

Asserts that I<$ref> is defined and is a reference to a hash with at
least one key/value pair.

=cut

sub assert_hashref_nonempty($;$) {
    my $ref = shift;
    my $name = shift;

    if ( ref($ref) eq 'HASH' || (Scalar::Util::blessed( $ref ) && $ref->isa( 'HASH' )) ) {
        return if scalar keys %{$ref} > 0;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_arrayref( $ref [, $name] )

=head2 assert_listref( $ref [,$name] )

Asserts that I<$ref> is defined, and is a reference to an array, which
may or may not be empty.

B<NB:> The same caveat about objects whose underlying structure is a
hash (see C<assert_hashref>) applies here; this method returns false
even for objects whose underlying structure is an array.

C<assert_listref> is an alias for C<assert_arrayref> and may go away in
the future.  Use C<assert_arrayref> instead.

=cut

sub assert_arrayref($;$) {
    my $ref  = shift;
    my $name = shift;

    if ( ref($ref) eq 'ARRAY' || (Scalar::Util::blessed( $ref ) && $ref->isa( 'ARRAY' )) ) {
        return;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}
*assert_listref = *assert_arrayref;


=head2 assert_arrayref_nonempty( $ref [, $name] )

Asserts that I<$ref> is reference to an array that has at least one element in it.

=cut

sub assert_arrayref_nonempty($;$) {
    my $ref  = shift;
    my $name = shift;

    if ( ref($ref) eq 'ARRAY' || (Scalar::Util::blessed( $ref ) && $ref->isa( 'ARRAY' )) ) {
        return if scalar @{$ref} > 0;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_aoh( $ref [, $name ] )

Verifies that C<$array> is an arrayref, and that every element is a hashref.

The array C<$array> can be an empty arraref and the assertion will pass.

=cut

sub assert_aoh {
    my $ref  = shift;
    my $name = shift;

    my $ok = 0;
    if ( ref($ref) eq 'ARRAY' || (Scalar::Util::blessed( $ref ) && $ref->isa( 'ARRAY' )) ) {
        $ok = 1;
        for my $val ( @{$ref} ) {
            if ( not ( ref($val) eq 'HASH' || (Scalar::Util::blessed( $val) && $val->isa( 'HASH' )) ) ) {
                $ok = 0;
                last;
            }
        }
    }

    return if $ok;

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_coderef( $ref [,$name] )

Asserts that I<$ref> is defined, and is a reference to a closure.

=cut

sub assert_coderef($;$) {
    my $ref = shift;
    my $name = shift;

    if ( ref($ref) eq 'CODE' || (Scalar::Util::blessed( $ref ) && $ref->isa( 'CODE' )) ) {
        return;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head1 TYPE-SPECIFIC ASSERTIONS

=head2 assert_datetime( $date )

Asserts that C<$date> is a DateTime object.

=cut

sub assert_datetime($;$) {
    my $ref  = shift;
    my $name = shift;

    if ( ref($ref) eq 'DateTime' || (Scalar::Util::blessed( $ref ) && $ref->isa( 'DateTime' )) ) {
        return;
    }

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head1 SET AND HASH MEMBERSHIP

=head2 assert_in( $string, \@inlist [,$name] );

Asserts that I<$string> matches one of the elements of I<\@inlist>.
I<$string> may be undef.

I<\@inlist> must be an array reference of non-ref strings.  If any
element is a reference, the assertion fails.

=cut

sub assert_in($$;$) {
    my $needle = shift;
    my $haystack = shift;
    my $name = shift;

    my $found = 0;

    # String has to be a non-ref scalar, or undef.
    if ( !ref($needle) ) {

        # Target list has to be an array...
        if ( ref($haystack) eq 'ARRAY' || (Scalar::Util::blessed( $haystack ) && $haystack->isa( 'ARRAY' )) ) {

            # ... and all elements have to be non-refs.
            my $elements_ok = 1;
            foreach my $element (@{$haystack}) {
                if ( ref($element) ) {
                    $elements_ok = 0;
                    last;
                }
            }

            # Now we can actually do the search.
            if ( $elements_ok ) {
                if ( defined($needle) ) {
                    foreach my $element (@{$haystack}) {
                        if ( $needle eq $element ) {
                            $found = 1;
                            last;
                        }
                    }
                }
                else {
                    foreach my $element (@{$haystack}) {
                        if ( !defined($element) ) {
                            $found = 1;
                            last;
                        }
                    }
                }
            }
        }
    }

    return if $found;

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_exists( \%hash, $key [,$name] )

=head2 assert_exists( \%hash, \@keylist [,$name] )

Asserts that I<%hash> is indeed a hash, and that I<$key> exists in
I<%hash>, or that all of the keys in I<@keylist> exist in I<%hash>.

    assert_exists( \%custinfo, 'name', 'Customer has a name field' );

    assert_exists( \%custinfo, [qw( name addr phone )],
                            'Customer has name, address and phone' );

=cut

sub assert_exists($$;$) {
    my $hash = shift;
    my $key = shift;
    my $name = shift;

    my $ok = 0;

    if ( ref($hash) eq 'HASH' || (Scalar::Util::blessed( $hash ) && $hash->isa( 'HASH' )) ) {
        if ( defined($key) ) {
            if ( ref($key) eq 'ARRAY' ) {
                $ok = (@{$key} > 0);
                for ( @{$key} ) {
                    if ( !exists( $hash->{$_} ) ) {
                        $ok = 0;
                        last;
                    }
                }
            }
            elsif ( !ref($key) ) {
                $ok = exists( $hash->{$key} );
            }
            else {
                $ok = 0;
            }
        }
    }

    return if $ok;

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_lacks( \%hash, $key [,$name] )

=head2 assert_lacks( \%hash, \@keylist [,$name] )

Asserts that I<%hash> is indeed a hash, and that I<$key> does NOT exist
in I<%hash>, or that none of the keys in I<@keylist> exist in I<%hash>.
The list C<@keylist> cannot be empty.

    assert_lacks( \%users, 'root', 'Root is not in the user table' );

    assert_lacks( \%users, [qw( root admin nobody )], 'No bad usernames found' );

=cut

sub assert_lacks($$;$) {
    my $hash = shift;
    my $key = shift;
    my $name = shift;

    my $ok = 0;

    if ( ref($hash) eq 'HASH' || (Scalar::Util::blessed( $hash ) && $hash->isa( 'HASH' )) ) {
        if ( defined($key) ) {
            if ( ref($key) eq 'ARRAY' ) {
                $ok = (@{$key} > 0);
                for ( @{$key} ) {
                    if ( exists( $hash->{$_} ) ) {
                        $ok = 0;
                        last;
                    }
                }
            }
            elsif ( !ref($key) ) {
                $ok = !exists( $hash->{$key} );
            }
            else {
                $ok = 0;
            }
        }
    }

    return if $ok;

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_all_keys_in( \%hash, \@names [, $name ] )

Asserts that each key in C<%hash> is in the list of C<@names>.

This is used to ensure that there are no extra keys in a given hash.

    assert_all_keys_in( $obj, [qw( height width depth )], '$obj can only contain height, width and depth keys' );

You can pass an empty list of C<@names>.

=cut

sub assert_all_keys_in($$;$) {
    my $hash = shift;
    my $keys = shift;
    my $name = shift;

    my @why;
    my $ok = 0;
    if ( ref($hash) eq 'HASH' || (Scalar::Util::blessed( $hash ) && $hash->isa( 'HASH' )) ) {
        if ( ref($keys) eq 'ARRAY' ) {
            $ok = 1;
            my %keys = map { $_ => 1 } @{$keys};
            for my $key ( keys %{$hash} ) {
                if ( !exists $keys{$key} ) {
                    $ok = 0;
                    push @why, qq{Key "$key" is not a valid key.};
                }
            }
        }
        else {
            push @why, 'Argument for array of keys is not an arrayref.';
        }
    }
    else {
        push @why, 'Argument for hash is not a hashref.';
    }

    return if $ok;

    require Carp;
    &Carp::confess( _failure_msg($name, @why) );
}


=head2 assert_keys_are( \%hash, \@keys [, $name ] )

Asserts that the keys for C<%hash> are exactly C<@keys>, no more and no less.

=cut

sub assert_keys_are($$;$) {
    my $hash = shift;
    my $keys = shift;
    my $name = shift;

    my @why;
    my $ok = 0;
    if ( ref($hash) eq 'HASH' || (Scalar::Util::blessed( $hash ) && $hash->isa( 'HASH' )) ) {
        if ( ref($keys) eq 'ARRAY' ) {
            my %keys = map { $_ => 1 } @{$keys};

            # First check all the keys are allowed.
            $ok = 1;
            for my $key ( keys %{$hash} ) {
                if ( !exists $keys{$key} ) {
                    $ok = 0;
                    push @why, qq{Key "$key" is not a valid key.};
                }
            }

            # Now check that all the valid keys are represented.
            for my $key ( @{$keys} ) {
                if ( !exists $hash->{$key} ) {
                    $ok = 0;
                    push @why, qq{Key "$key" is not in the hash.};
                }
            }
        }
        else {
            push @why, 'Argument for array of keys is not an arrayref.';
        }
    }
    else {
        push @why, 'Argument for hash is not a hashref.';
    }

    return if $ok;

    require Carp;
    &Carp::confess( _failure_msg($name, @why) );
}


=head1 CONTEXT ASSERTIONS

=head2 assert_context_nonvoid( [$name] )

Verifies that the function currently being executed has not been called
in void context.  This is to ensure the calling function is not ignoring
the return value of the executing function.

Given this function:

    sub something {
        ...

        assert_context_scalar();

        return $important_value;
    }

These calls to C<something> will pass:

    my $val = something();
    my @things = something();

but this will fail:

    something();

=cut

sub assert_context_nonvoid(;$) {
    my $name = shift;

    my $wantarray = (caller(1))[5];

    return if defined($wantarray);

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head2 assert_context_scalar( [$name] )

Verifies that the function currently being executed has been called in
scalar context.  This is to ensure the calling function is not ignoring
the return value of the executing function.

Given this function:

    sub something {
        ...

        assert_context_scalar();

        return $important_value;
    }

This call to C<something> will pass:

    my $val = something();

but these will fail:

    something();
    my @things = something();

=cut

sub assert_context_scalar(;$) {
    my $name = shift;

    my $wantarray = (caller(1))[5];

    return if defined($wantarray) && !$wantarray;

    require Carp;
    &Carp::confess( _failure_msg($name) );
}


=head1 UTILITY ASSERTIONS

=head2 assert_fail( [$name] )

Assertion that always fails.  C<assert_fail($msg)> is exactly the same
as calling C<assert(0,$msg)>, but it eliminates that case where you
accidentally use C<assert($msg)>, which of course never fires.

=cut

sub assert_fail(;$) {
    require Carp;
    &Carp::confess( _failure_msg($_[0]) );
}


# Can't call confess() here or the stack trace will be wrong.
sub _failure_msg {
    my ($name, @why) = @_;

    my $msg = 'Assertion';
    $msg   .= " ($name)" if defined $name;
    $msg   .= " failed!\n";
    $msg   .= "$_\n" for @why;

    return $msg;
}


=head1 COPYRIGHT & LICENSE

Copyright 2005-2023 Andy Lester

This program is free software; you can redistribute it and/or modify
it under the terms of the Artistic License version 2.0.

=head1 ACKNOWLEDGEMENTS

Thanks to
Eric A. Zarko,
Bob Diss,
Pete Krawczyk,
David Storrs,
Dan Friedman,
Allard Hoeve,
Thomas L. Shinnick,
and Leland Johnson
for code and fixes.

=cut

1;