File: utils.t

package info (click to toggle)
libbadger-perl 0.16-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,400 kB
  • sloc: perl: 11,004; makefile: 9
file content (520 lines) | stat: -rw-r--r-- 15,504 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
#============================================================= -*-perl-*-
#
# t/core/utils.t
#
# Test the Badger::Utils module.
#
# Written by Andy Wardley <abw@wardley.org>.
#
# This is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
#
#========================================================================

use strict;
use warnings;

use lib qw( t/core/lib ./lib ../lib ../../lib );
use Badger::Debug modules => 'Badger::Utils';
use Badger::Utils 'UTILS blessed xprintf reftype textlike plural permute_fragments';
use Badger::Test
    tests => 118,
    debug => 'Badger::Utils',
    args  => \@ARGV;

is( UTILS, 'Badger::Utils', 'got UTILS defined' );
ok( blessed bless([], 'Wibble'), 'got blessed' );


#-----------------------------------------------------------------------
# test is_object()
#-----------------------------------------------------------------------

package My::Base;
use base 'Badger::Base';

package My::Sub;
use base 'My::Base';

package main;
use Badger::Utils 'is_object';

my $obj = My::Sub->new;
ok(   is_object( 'My::Sub'   => $obj ), 'object is a My::Sub' );
ok(   is_object( 'My::Base'  => $obj ), 'object is a My::Base' );
ok( ! is_object( 'My::Other' => $obj ), 'object is not My::Other' );


#-----------------------------------------------------------------------
# test params() and self_params()
#-----------------------------------------------------------------------

use Badger::Utils 'params';

my $hash = {
    a => 10,
    b => 20,
};
is( params($hash), $hash, 'params returns hash ref' );
is( params(%$hash)->{ a }, 10, 'params merged named param list' );


package Selfish;

use Badger::Class
    base    => 'Badger::Base',
    as_text => 'text',                  # for testing textlike()
    utils   => 'self_params';

sub test1 {
    my ($self, $params) = self_params(@_);
    return ($self, $params);
}

sub text {                              # for testing textlike()
    return 'Hello World';
}

package main;
my $selfish = Selfish->new();
my ($s, $p) = $selfish->test1($hash);
is( $s, $selfish, 'self_params returns self' );
is( $p, $hash, 'self_params returns params' );
($s, $p) = $selfish->test1(%$hash);
is( $s, $selfish, 'self_params returns self again' );
is( $p->{a}, 10, 'self_params returns params again' );

# test warnings generated by add number of arguments - this is invaluable
# for debugging


sub foo { bar(@_) }
sub bar { baz(@_) }
sub baz { params(@_) }

{
    my @warnings;
    local $Badger::Utils::WARN = sub {
        push(@warnings, join('', @_));
    };
    foo(1, 2, 3);
    is(
        $warnings[0],
        "Badger::Utils::params() called with an odd number of arguments: 1, 2, 3\n",
        'got odd number of arguments warning'
    );
    like(
        $warnings[1],
        qr/#1: Called from main::baz/,
        'got baz() in stack trace'
    );
    like(
        $warnings[2],
        qr/#2: Called from main::bar/,
        'got bar() in stack trace'
    );
    like(
        $warnings[3],
        qr/#3: Called from main::foo/,
        'got foo() in stack trace'
    );
}


#-----------------------------------------------------------------------
# test textlike
#-----------------------------------------------------------------------

ok( textlike 'hello', 'string is textlike' );
ok( textlike $selfish, 'selfish object is textlike' );
ok( ! textlike $obj, 'object is not textlike' );
ok( ! textlike [10], 'list is not textlike' );
ok( ! textlike sub { 'foo' }, 'sub is not textlike' );


#-----------------------------------------------------------------------
# test xprintf()
#-----------------------------------------------------------------------

is( xprintf('The %s sat on the %s', 'cat', 'mat'),
    'The cat sat on the mat', 'xprintf s s' );

is( xprintf('The %1$s sat on the %2$s', 'cat', 'mat'),
    'The cat sat on the mat', 'xprintf 1 2' );

is( xprintf('The %2$s sat on the %1$s', 'cat', 'mat'),
    'The mat sat on the cat', 'xprintf 2 1' );

is( xprintf('The <2> sat on the <1>', 'cat', 'mat'),
    'The mat sat on the cat', 'xprintf <2> <1>' );

is( xprintf('The <1:s> sat on the <2:s>', 'cat', 'mat'),
    'The cat sat on the mat', 'xprintf <1:s> <2:s>' );

is( xprintf('The <1:5s> sat on the <2:5s>', 'cat', 'mat'),
    'The   cat sat on the   mat', 'xprintf <1:5s> <2:5s>' );

is( xprintf('The <1:-5s> sat on the <2:-5s>', 'cat', 'mat'),
    'The cat   sat on the mat  ', 'xprintf <1:-5s> <2:-5s>' );

is( xprintf('<1> is <2:4.3f>', pi => 3.1415926),
    'pi is 3.142', 'pi is 3.142' );

is( xprintf('<1> is <2:4.3f>', e => 2.71828),
    'e is 2.718', 'pi is 2.718' );

is( xprintf("<1><2| by ?>", 'one'),
    'one', 'one' );

is( xprintf("<1><2| by ?>", 'one', 'two'),
    'one by two', 'one by two' );

is( xprintf("<1><2| by ? by ?>", 'one', 'two'),
    'one by two by two', 'one by two by two' );


#-----------------------------------------------------------------------
# test we can import utility functions from Scalar::Util, List::Util,
# List::MoreUtils and Hash::Util.
#-----------------------------------------------------------------------

use Badger::Utils 'reftype looks_like_number numlike first max lock_hash';

my $object = bless [ ], 'Badger::Test::Object';
is( reftype $object, 'ARRAY', 'reftype imported' );

ok( looks_like_number 23, 'looks_like_number imported' );
ok( numlike 42, 'numlike imported' );

my @items = (10, 22, 33, 42);
my $first = first { $_ > 25 } @items;
is( $first, 33, 'list first imported' );

my $max = max 2.718, 3.14, 1.618;
is( $max, 3.14, 'list max imported' );

my %hash = (x => 10);
lock_hash(%hash);
ok( ! eval { $hash{x} = 20 }, 'could not modify read-only hash' );
like( $@, qr/Modification of a read-only value attempted/, 'got read-only error' );


#-----------------------------------------------------------------------
# Import from Badger::Timestamp
#-----------------------------------------------------------------------

use Badger::Utils 'Timestamp Now';

my $ts = Now;
is( ref $ts, 'Badger::Timestamp', 'Now is a Badger::Timestamp' );

$ts = Timestamp('2009/05/25 11:31:00');
is( ref $ts, 'Badger::Timestamp', 'Timestamp returned a Badger::Timestamp' );
is( $ts->year, 2009, 'got timestamp year' );
is( $ts->month, 5, 'got timestamp month' );
is( $ts->day, 25, 'got timestamp day' );

#-----------------------------------------------------------------------
# Import from Badger::Date
#-----------------------------------------------------------------------

use Badger::Utils 'Date Today';

my $date = Today;
is( ref $date, 'Badger::Date', 'Today is a Badger::Date' );

$date = Date('2015/04/05');
is( ref $date, 'Badger::Date', 'Date returned a Badger::Date' );
is( $date->year, 2015, 'got date year' );
is( $date->month, 4, 'got date month' );
is( $date->day, 5, 'got date day' );


#-----------------------------------------------------------------------
# Import from Badger::Logic
#-----------------------------------------------------------------------

use Badger::Utils 'Logic';

my $logic = Logic('cheese and biscuits');
ok( blessed $logic && $logic->isa('Badger::Logic'), 'Logic returned a Badger::Logic object' );


#-----------------------------------------------------------------------
# Import from Badger::Filesystem
#-----------------------------------------------------------------------

use Badger::Utils 'Bin';

my $bin = Bin;
ok( blessed $bin && $bin->isa('Badger::Filesystem::Directory'), "Bin is $bin" );



#-----------------------------------------------------------------------
# test plural()
#-----------------------------------------------------------------------

is( plural('gateway'), 'gateways', 'pluralised gateway/gateways' );
is( plural('fairy'), 'fairies', 'pluralised fairy/fairies' );


#-----------------------------------------------------------------------
# test random_name()
#-----------------------------------------------------------------------

use Badger::Utils 'random_name';

is( length random_name(), $Badger::Utils::RANDOM_NAME_LENGTH,
    "default random_name() length is $Badger::Utils::RANDOM_NAME_LENGTH" );
is( length random_name(16), 16, 'random_name(16) length is 16');
is( length random_name(32), 32, 'random_name(16) length is 32');
is( length random_name(48), 48, 'random_name(16) length is 48');
is( length random_name(64), 64, 'random_name(16) length is 64');


#-----------------------------------------------------------------------
# test camel_case() and CamelCase
#-----------------------------------------------------------------------

use Badger::Utils 'camel_case CamelCase';

is( camel_case('hello_world'), 'HelloWorld',
   "camel_case('hello_world') => 'HelloWorld'"
);
is( camel_case('FOO_bar'), 'FOOBar',
   "camel_case('FOO_bar') => 'FOOBar'"
);

is( CamelCase('hello_world'), 'HelloWorld',
   "CamelCase('hello_world') => 'HelloWorld'"
);



#-----------------------------------------------------------------------
# test permute_fragments()
#-----------------------------------------------------------------------

test_permute('foo', 'foo');
test_permute('Template(X)', 'Template', 'TemplateX');
test_permute('Template(X|)', 'TemplateX', 'Template');
test_permute(
    'Template(X)::(XS::TT3|TT3)::Foo',
    'Template::XS::TT3::Foo',
    'Template::TT3::Foo',
    'TemplateX::XS::TT3::Foo',
    'TemplateX::TT3::Foo',
);

sub test_permute {
    my $input   = shift;
    my @outputs = permute_fragments($input);
#    print("  INPUT: $input\n");
#    print("OUTPUTS: ", join(', ', @outputs), "\n");

    foreach my $output (@outputs) {
        if (@_) {
            my $expect = shift;
            is( $output, $expect, "$input => $expect" );
        }
        else {
            fail("$input permuted unexpected value: $output");
        }
    }
    foreach my $expect (@_) {
        fail("$input did not permute expected value: $expect");
    }
}


#-----------------------------------------------------------------------------
# test hash_each() and list_each
#-----------------------------------------------------------------------------

my @each;

use Badger::Utils 'hash_each list_each';

hash_each(
    { a => 10, b => 20 },
    sub {
        my ($hash, $key, $value) = @_;
        push(@each, "$key:$value");
    }
);
is( join(', ', sort @each), "a:10, b:20", 'hash_each()' );

@each = ();

list_each(
    [ 30, 40, 50 ],
    sub {
        my ($list, $index, $value) = @_;
        push(@each, "$index:$value");
    }
);
is( join(', ', sort @each), "0:30, 1:40, 2:50", 'list_each()' );

#-----------------------------------------------------------------------------
# test split_to_list()
#-----------------------------------------------------------------------------

use Badger::Utils 'split_to_list';

is(
    join(', ', @{ split_to_list('a b c') }),
    'a, b, c',
    'split_to_list("a b c")'
);

is(
    join(' + ', @{ split_to_list('a, b,c') }),
    'a + b + c',
    'split_to_list("a, b,c")'
);

is(
    join(', ', @{ split_to_list([qw(a b c)]) }),
    'a, b, c',
    'split_to_list([qw(a b c)])'
);

#-----------------------------------------------------------------------------
# test extend()
#-----------------------------------------------------------------------------

use Badger::Utils 'extend';

my $one = { a => 10 };
my $two = { b => 20 };
extend($one, $two);

is( $one->{ b }, 20, 'extend($one, $two)');

my $combo = extend(
    { },
    $one,
    $two,
    { c => 30 }
);
is( $combo->{ a }, 10, 'extend(...) a=10');
is( $combo->{ b }, 20, 'extend(...) b=20');
is( $combo->{ c }, 30, 'extend(...) c=30');

#-----------------------------------------------------------------------------
# test merge()
#-----------------------------------------------------------------------------

use Badger::Utils 'merge';

my $merge_one = { a => 10, b => { c => 30, d => 31 }, e => 40 };
my $merge_two = { b => { d => 40, e => 50 } };
my $merge_tre = { f => { g => 60 }, h => 70 };
merge($merge_one, $merge_two, $merge_tre);

is( $merge_one->{ a },        10, 'merge a' );
is( $merge_one->{ b }->{ c }, 30, 'merge b.c' );
is( $merge_one->{ b }->{ d }, 40, 'merge b.d' );
is( $merge_one->{ b }->{ e }, 50, 'merge b.e' );
is( $merge_one->{ e },        40, 'merge e' );
is( $merge_one->{ f }->{ g }, 60, 'merge f.g' );
is( $merge_one->{ h },        70, 'merge h' );

# example from the docs
my $m2_one = {
    a => 10,
    b => {
        c => 20,
        d => {
            e => 30,
        }
    },
};
my $m2_two = {
    b => {
        d => {
            f => 40
        },
        g => 50,
    },
    h => 60
};
merge($m2_one, $m2_two);
is( join(',', sort keys %{$m2_one}), 'a,b,h', 'merge level 0');
is( join(',', sort keys %{$m2_one->{b}}), 'c,d,g', 'merge level 1');
is( join(',', sort keys %{$m2_one->{b}->{d}}), 'e,f', 'merge level 2');


#-----------------------------------------------------------------------------
# uri methods
#-----------------------------------------------------------------------------

use Badger::Utils 'join_uri resolve_uri';

is( join_uri('foo',   'bar'), 'foo/bar', 'join_uri("foo", "bar")');
is( join_uri('foo/',  'bar'), 'foo/bar', 'join_uri("foo/", "bar")');
is( join_uri('foo',  '/bar'), 'foo/bar', 'join_uri("foo", "/bar")');
is( join_uri('foo/', '/bar'), 'foo/bar', 'join_uri("foo/", "/bar")');
is( join_uri('http://foo//bar/', '/baz'), 'http://foo/bar/baz', 'join_uri("http://foo//bar/", "/baz")');

is( resolve_uri('foo',  'bar'), 'foo/bar', 'resolve_uri("foo", "bar")');
is( resolve_uri('foo', '/bar'), '/bar',    'resolve_uri("foo", "/bar")');


#-----------------------------------------------------------------------------
# truelike/falselike
#-----------------------------------------------------------------------------

use Badger::Utils 'truelike falselike';

ok(   truelike(1),        '1 is truelike'            );
ok(   truelike('1'),      "'1' is truelike"          );
ok(   truelike('on'),     'on is truelike'           );
ok(   truelike('yes'),    'yes is truelike'          );
ok(   truelike('true'),   'true is truelike'         );
ok( ! truelike(undef),    'undef is not truelike'    );
ok( ! truelike(0),        '0 is not truelike'        );
ok( ! truelike('0'),      "'0' is not truelike"      );
ok( ! truelike('off'),    "off is not truelike"      );
ok( ! truelike('no'),     "'no' is not truelike"     );
ok( ! truelike('false'),  "'false' is not truelike"  );

ok(   falselike(undef),   'undef is falselike'       );
ok(   falselike(0),       '0 is falselike'           );
ok(   falselike('0'),     "'0' is falselike"         );
ok(   falselike('off'),   "off is falselike"         );
ok(   falselike('no'),    "'no' is falselike"        );
ok(   falselike('false'), "'false' is falselike"     );
ok( ! falselike(1),       '1 is not falselike'       );
ok( ! falselike('1'),     "'1' is not falselike"     );
ok( ! falselike('on'),    'on is not falselike'      );
ok( ! falselike('yes'),   'yes is not falselike'     );
ok( ! falselike('true'),  'true is not falselike'    );


__END__

# Hmmm... I didn't realise that List::MoreUtils wasn't a core Perl module.

use Badger::Utils 'any all';

my $any = any { $_ % 11 == 0 } @items;      # divisible by 11
ok( $any, 'any list imported' );

my $all = all { $_ % 11 == 0 } @items;      # divisible by 11
ok( ! $all, 'all list imported' );

my $true = true { $_ % 11 == 0 } @items;    # divisible by 11
is( $true, 2, 'true list imported' );


__END__

# Local Variables:
# mode: perl
# perl-indent-level: 4
# indent-tabs-mode: nil
# End:
#
# vim: expandtab shiftwidth=4: