DB_File-1.79
[p5sagit/p5-mst-13.2.git] / ext / DB_File / t / db-recno.t
1 #!./perl -w
2
3 BEGIN {
4     chdir 't' if -d 't';
5     @INC = '../lib';
6     require Config; import Config;
7     if ($Config{'extensions'} !~ /\bDB_File\b/) {
8         print "1..0 # Skip: DB_File was not built\n";
9         exit 0;
10     }
11 }
12
13 use DB_File; 
14 use Fcntl;
15 use strict ;
16 use warnings;
17 use vars qw($dbh $Dfile $bad_ones $FA) ;
18
19 # full tied array support started in Perl 5.004_57
20 # Double check to see if it is available.
21
22 {
23     sub try::TIEARRAY { bless [], "try" }
24     sub try::FETCHSIZE { $FA = 1 }
25     $FA = 0 ;
26     my @a ; 
27     tie @a, 'try' ;
28     my $a = @a ;
29 }
30
31
32 sub ok
33 {
34     my $no = shift ;
35     my $result = shift ;
36
37     print "not " unless $result ;
38     print "ok $no\n" ;
39
40     return $result ;
41 }
42
43 {
44     package Redirect ;
45     use Symbol ;
46
47     sub new
48     {
49         my $class = shift ;
50         my $filename = shift ;
51         my $fh = gensym ;
52         open ($fh, ">$filename") || die "Cannot open $filename: $!" ;
53         my $real_stdout = select($fh) ;
54         return bless [$fh, $real_stdout ] ;
55
56     }
57     sub DESTROY
58     {
59         my $self = shift ;
60         close $self->[0] ;
61         select($self->[1]) ;
62     }
63 }
64
65 sub docat
66 {
67     my $file = shift;
68     local $/ = undef;
69     open(CAT,$file) || die "Cannot open $file:$!";
70     my $result = <CAT>;
71     close(CAT);
72     return $result;
73 }
74
75 sub docat_del
76
77     my $file = shift;
78     local $/ = undef;
79     open(CAT,$file) || die "Cannot open $file: $!";
80     my $result = <CAT>;
81     close(CAT);
82     unlink $file ;
83     return $result;
84 }   
85
86 sub bad_one
87 {
88     print STDERR <<EOM unless $bad_ones++ ;
89 #
90 # Some older versions of Berkeley DB version 1 will fail tests 51,
91 # 53 and 55.
92 #
93 # You can safely ignore the errors if you're never going to use the
94 # broken functionality (recno databases with a modified bval). 
95 # Otherwise you'll have to upgrade your DB library.
96 #
97 # If you want to use Berkeley DB version 1, then 1.85 and 1.86 are the
98 # last versions that were released. Berkeley DB version 2 is continually
99 # being updated -- Check out http://www.sleepycat.com/ for more details.
100 #
101 EOM
102 }
103
104 my $splice_tests = 10 + 1; # ten regressions, plus the randoms
105 my $total_tests = 138 ;
106 $total_tests += $splice_tests if $FA ;
107 print "1..$total_tests\n";   
108
109 my $Dfile = "recno.tmp";
110 unlink $Dfile ;
111
112 umask(0);
113
114 # Check the interface to RECNOINFO
115
116 my $dbh = new DB_File::RECNOINFO ;
117 ok(1, ! defined $dbh->{bval}) ;
118 ok(2, ! defined $dbh->{cachesize}) ;
119 ok(3, ! defined $dbh->{psize}) ;
120 ok(4, ! defined $dbh->{flags}) ;
121 ok(5, ! defined $dbh->{lorder}) ;
122 ok(6, ! defined $dbh->{reclen}) ;
123 ok(7, ! defined $dbh->{bfname}) ;
124
125 $dbh->{bval} = 3000 ;
126 ok(8, $dbh->{bval} == 3000 );
127
128 $dbh->{cachesize} = 9000 ;
129 ok(9, $dbh->{cachesize} == 9000 );
130
131 $dbh->{psize} = 400 ;
132 ok(10, $dbh->{psize} == 400 );
133
134 $dbh->{flags} = 65 ;
135 ok(11, $dbh->{flags} == 65 );
136
137 $dbh->{lorder} = 123 ;
138 ok(12, $dbh->{lorder} == 123 );
139
140 $dbh->{reclen} = 1234 ;
141 ok(13, $dbh->{reclen} == 1234 );
142
143 $dbh->{bfname} = 1234 ;
144 ok(14, $dbh->{bfname} == 1234 );
145
146
147 # Check that an invalid entry is caught both for store & fetch
148 eval '$dbh->{fred} = 1234' ;
149 ok(15, $@ =~ /^DB_File::RECNOINFO::STORE - Unknown element 'fred' at/ );
150 eval 'my $q = $dbh->{fred}' ;
151 ok(16, $@ =~ /^DB_File::RECNOINFO::FETCH - Unknown element 'fred' at/ );
152
153 # Now check the interface to RECNOINFO
154
155 my $X  ;
156 my @h ;
157 ok(17, $X = tie @h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0640, $DB_RECNO ) ;
158
159 ok(18, ((stat($Dfile))[2] & 0777) == (($^O eq 'os2' || $^O eq 'MacOS') ? 0666 : 0640)
160         ||  $^O eq 'MSWin32' ||  $^O eq 'NetWare' || $^O eq 'amigaos') ;
161
162 #my $l = @h ;
163 my $l = $X->length ;
164 ok(19, ($FA ? @h == 0 : !$l) );
165
166 my @data = qw( a b c d ever f g h  i j k longername m n o p) ;
167
168 $h[0] = shift @data ;
169 ok(20, $h[0] eq 'a' );
170
171 my $ i;
172 foreach (@data)
173   { $h[++$i] = $_ }
174
175 unshift (@data, 'a') ;
176
177 ok(21, defined $h[1] );
178 ok(22, ! defined $h[16] );
179 ok(23, $FA ? @h == @data : $X->length == @data );
180
181
182 # Overwrite an entry & check fetch it
183 $h[3] = 'replaced' ;
184 $data[3] = 'replaced' ;
185 ok(24, $h[3] eq 'replaced' );
186
187 #PUSH
188 my @push_data = qw(added to the end) ;
189 ($FA ? push(@h, @push_data) : $X->push(@push_data)) ;
190 push (@data, @push_data) ;
191 ok(25, $h[++$i] eq 'added' );
192 ok(26, $h[++$i] eq 'to' );
193 ok(27, $h[++$i] eq 'the' );
194 ok(28, $h[++$i] eq 'end' );
195
196 # POP
197 my $popped = pop (@data) ;
198 my $value = ($FA ? pop @h : $X->pop) ;
199 ok(29, $value eq $popped) ;
200
201 # SHIFT
202 $value = ($FA ? shift @h : $X->shift) ;
203 my $shifted = shift @data ;
204 ok(30, $value eq $shifted );
205
206 # UNSHIFT
207
208 # empty list
209 ($FA ? unshift @h,() : $X->unshift) ;
210 ok(31, ($FA ? @h == @data : $X->length == @data ));
211
212 my @new_data = qw(add this to the start of the array) ;
213 $FA ? unshift (@h, @new_data) : $X->unshift (@new_data) ;
214 unshift (@data, @new_data) ;
215 ok(32, $FA ? @h == @data : $X->length == @data );
216 ok(33, $h[0] eq "add") ;
217 ok(34, $h[1] eq "this") ;
218 ok(35, $h[2] eq "to") ;
219 ok(36, $h[3] eq "the") ;
220 ok(37, $h[4] eq "start") ;
221 ok(38, $h[5] eq "of") ;
222 ok(39, $h[6] eq "the") ;
223 ok(40, $h[7] eq "array") ;
224 ok(41, $h[8] eq $data[8]) ;
225
226 # Brief test for SPLICE - more thorough 'soak test' is later.
227 my @old;
228 if ($FA) {
229     @old = splice(@h, 1, 2, qw(bananas just before));
230 }
231 else {
232     @old = $X->splice(1, 2, qw(bananas just before));
233 }
234 ok(42, $h[0] eq "add") ;
235 ok(43, $h[1] eq "bananas") ;
236 ok(44, $h[2] eq "just") ;
237 ok(45, $h[3] eq "before") ;
238 ok(46, $h[4] eq "the") ;
239 ok(47, $h[5] eq "start") ;
240 ok(48, $h[6] eq "of") ;
241 ok(49, $h[7] eq "the") ;
242 ok(50, $h[8] eq "array") ;
243 ok(51, $h[9] eq $data[8]) ;
244 $FA ? splice(@h, 1, 3, @old) : $X->splice(1, 3, @old);
245
246 # Now both arrays should be identical
247
248 my $ok = 1 ;
249 my $j = 0 ;
250 foreach (@data)
251 {
252    $ok = 0, last if $_ ne $h[$j ++] ; 
253 }
254 ok(52, $ok );
255
256 # Neagtive subscripts
257
258 # get the last element of the array
259 ok(53, $h[-1] eq $data[-1] );
260 ok(54, $h[-1] eq $h[ ($FA ? @h : $X->length) -1] );
261
262 # get the first element using a negative subscript
263 eval '$h[ - ( $FA ? @h : $X->length)] = "abcd"' ;
264 ok(55, $@ eq "" );
265 ok(56, $h[0] eq "abcd" );
266
267 # now try to read before the start of the array
268 eval '$h[ - (1 + ($FA ? @h : $X->length))] = 1234' ;
269 ok(57, $@ =~ '^Modification of non-creatable array value attempted' );
270
271 # IMPORTANT - $X must be undefined before the untie otherwise the
272 #             underlying DB close routine will not get called.
273 undef $X ;
274 untie(@h);
275
276 unlink $Dfile;
277
278
279 {
280     # Check bval defaults to \n
281
282     my @h = () ;
283     my $dbh = new DB_File::RECNOINFO ;
284     ok(58, tie @h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0640, $dbh ) ;
285     $h[0] = "abc" ;
286     $h[1] = "def" ;
287     $h[3] = "ghi" ;
288     untie @h ;
289     my $x = docat($Dfile) ;
290     unlink $Dfile;
291     ok(59, $x eq "abc\ndef\n\nghi\n") ;
292 }
293
294 {
295     # Change bval
296
297     my @h = () ;
298     my $dbh = new DB_File::RECNOINFO ;
299     $dbh->{bval} = "-" ;
300     ok(60, tie @h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0640, $dbh ) ;
301     $h[0] = "abc" ;
302     $h[1] = "def" ;
303     $h[3] = "ghi" ;
304     untie @h ;
305     my $x = docat($Dfile) ;
306     unlink $Dfile;
307     my $ok = ($x eq "abc-def--ghi-") ;
308     bad_one() unless $ok ;
309     ok(61, $ok) ;
310 }
311
312 {
313     # Check R_FIXEDLEN with default bval (space)
314
315     my @h = () ;
316     my $dbh = new DB_File::RECNOINFO ;
317     $dbh->{flags} = R_FIXEDLEN ;
318     $dbh->{reclen} = 5 ;
319     ok(62, tie @h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0640, $dbh ) ;
320     $h[0] = "abc" ;
321     $h[1] = "def" ;
322     $h[3] = "ghi" ;
323     untie @h ;
324     my $x = docat($Dfile) ;
325     unlink $Dfile;
326     my $ok = ($x eq "abc  def       ghi  ") ;
327     bad_one() unless $ok ;
328     ok(63, $ok) ;
329 }
330
331 {
332     # Check R_FIXEDLEN with user-defined bval
333
334     my @h = () ;
335     my $dbh = new DB_File::RECNOINFO ;
336     $dbh->{flags} = R_FIXEDLEN ;
337     $dbh->{bval} = "-" ;
338     $dbh->{reclen} = 5 ;
339     ok(64, tie @h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0640, $dbh ) ;
340     $h[0] = "abc" ;
341     $h[1] = "def" ;
342     $h[3] = "ghi" ;
343     untie @h ;
344     my $x = docat($Dfile) ;
345     unlink $Dfile;
346     my $ok = ($x eq "abc--def-------ghi--") ;
347     bad_one() unless $ok ;
348     ok(65, $ok) ;
349 }
350
351 {
352     # check that attempting to tie an associative array to a DB_RECNO will fail
353
354     my $filename = "xyz" ;
355     my %x ;
356     eval { tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0640, $DB_RECNO ; } ;
357     ok(66, $@ =~ /^DB_File can only tie an array to a DB_RECNO database/) ;
358     unlink $filename ;
359 }
360
361 {
362    # sub-class test
363
364    package Another ;
365
366    use warnings ;
367    use strict ;
368
369    open(FILE, ">SubDB.pm") or die "Cannot open SubDB.pm: $!\n" ;
370    print FILE <<'EOM' ;
371
372    package SubDB ;
373
374    use warnings ;
375    use strict ;
376    use vars qw( @ISA @EXPORT) ;
377
378    require Exporter ;
379    use DB_File;
380    @ISA=qw(DB_File);
381    @EXPORT = @DB_File::EXPORT ;
382
383    sub STORE { 
384         my $self = shift ;
385         my $key = shift ;
386         my $value = shift ;
387         $self->SUPER::STORE($key, $value * 2) ;
388    }
389
390    sub FETCH { 
391         my $self = shift ;
392         my $key = shift ;
393         $self->SUPER::FETCH($key) - 1 ;
394    }
395
396    sub put { 
397         my $self = shift ;
398         my $key = shift ;
399         my $value = shift ;
400         $self->SUPER::put($key, $value * 3) ;
401    }
402
403    sub get { 
404         my $self = shift ;
405         $self->SUPER::get($_[0], $_[1]) ;
406         $_[1] -= 2 ;
407    }
408
409    sub A_new_method
410    {
411         my $self = shift ;
412         my $key = shift ;
413         my $value = $self->FETCH($key) ;
414         return "[[$value]]" ;
415    }
416
417    1 ;
418 EOM
419
420     close FILE ;
421
422     BEGIN { push @INC, '.'; } 
423     eval 'use SubDB ; ';
424     main::ok(67, $@ eq "") ;
425     my @h ;
426     my $X ;
427     eval '
428         $X = tie(@h, "SubDB","recno.tmp", O_RDWR|O_CREAT, 0640, $DB_RECNO );
429         ' ;
430
431     main::ok(68, $@ eq "") ;
432
433     my $ret = eval '$h[3] = 3 ; return $h[3] ' ;
434     main::ok(69, $@ eq "") ;
435     main::ok(70, $ret == 5) ;
436
437     my $value = 0;
438     $ret = eval '$X->put(1, 4) ; $X->get(1, $value) ; return $value' ;
439     main::ok(71, $@ eq "") ;
440     main::ok(72, $ret == 10) ;
441
442     $ret = eval ' R_NEXT eq main::R_NEXT ' ;
443     main::ok(73, $@ eq "" ) ;
444     main::ok(74, $ret == 1) ;
445
446     $ret = eval '$X->A_new_method(1) ' ;
447     main::ok(75, $@ eq "") ;
448     main::ok(76, $ret eq "[[11]]") ;
449
450     undef $X;
451     untie(@h);
452     unlink "SubDB.pm", "recno.tmp" ;
453
454 }
455
456 {
457
458     # test $#
459     my $self ;
460     unlink $Dfile;
461     ok(77, $self = tie @h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0640, $DB_RECNO ) ;
462     $h[0] = "abc" ;
463     $h[1] = "def" ;
464     $h[2] = "ghi" ;
465     $h[3] = "jkl" ;
466     ok(78, $FA ? $#h == 3 : $self->length() == 4) ;
467     undef $self ;
468     untie @h ;
469     my $x = docat($Dfile) ;
470     ok(79, $x eq "abc\ndef\nghi\njkl\n") ;
471
472     # $# sets array to same length
473     ok(80, $self = tie @h, 'DB_File', $Dfile, O_RDWR, 0640, $DB_RECNO ) ;
474     if ($FA)
475       { $#h = 3 }
476     else 
477       { $self->STORESIZE(4) }
478     ok(81, $FA ? $#h == 3 : $self->length() == 4) ;
479     undef $self ;
480     untie @h ;
481     $x = docat($Dfile) ;
482     ok(82, $x eq "abc\ndef\nghi\njkl\n") ;
483
484     # $# sets array to bigger
485     ok(83, $self = tie @h, 'DB_File', $Dfile, O_RDWR, 0640, $DB_RECNO ) ;
486     if ($FA)
487       { $#h = 6 }
488     else 
489       { $self->STORESIZE(7) }
490     ok(84, $FA ? $#h == 6 : $self->length() == 7) ;
491     undef $self ;
492     untie @h ;
493     $x = docat($Dfile) ;
494     ok(85, $x eq "abc\ndef\nghi\njkl\n\n\n\n") ;
495
496     # $# sets array smaller
497     ok(86, $self = tie @h, 'DB_File', $Dfile, O_RDWR, 0640, $DB_RECNO ) ;
498     if ($FA)
499       { $#h = 2 }
500     else 
501       { $self->STORESIZE(3) }
502     ok(87, $FA ? $#h == 2 : $self->length() == 3) ;
503     undef $self ;
504     untie @h ;
505     $x = docat($Dfile) ;
506     ok(88, $x eq "abc\ndef\nghi\n") ;
507
508     unlink $Dfile;
509
510
511 }
512
513 {
514    # DBM Filter tests
515    use warnings ;
516    use strict ;
517    my (@h, $db) ;
518    my ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
519    unlink $Dfile;
520
521    sub checkOutput
522    {
523        my($fk, $sk, $fv, $sv) = @_ ;
524        return
525            $fetch_key eq $fk && $store_key eq $sk && 
526            $fetch_value eq $fv && $store_value eq $sv &&
527            $_ eq 'original' ;
528    }
529    
530    ok(89, $db = tie(@h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0640, $DB_RECNO ) );
531
532    $db->filter_fetch_key   (sub { $fetch_key = $_ }) ;
533    $db->filter_store_key   (sub { $store_key = $_ }) ;
534    $db->filter_fetch_value (sub { $fetch_value = $_}) ;
535    $db->filter_store_value (sub { $store_value = $_ }) ;
536
537    $_ = "original" ;
538
539    $h[0] = "joe" ;
540    #                   fk   sk     fv   sv
541    ok(90, checkOutput( "", 0, "", "joe")) ;
542
543    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
544    ok(91, $h[0] eq "joe");
545    #                   fk  sk  fv    sv
546    ok(92, checkOutput( "", 0, "joe", "")) ;
547
548    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
549    ok(93, $db->FIRSTKEY() == 0) ;
550    #                    fk     sk  fv  sv
551    ok(94, checkOutput( 0, "", "", "")) ;
552
553    # replace the filters, but remember the previous set
554    my ($old_fk) = $db->filter_fetch_key   
555                         (sub { ++ $_ ; $fetch_key = $_ }) ;
556    my ($old_sk) = $db->filter_store_key   
557                         (sub { $_ *= 2 ; $store_key = $_ }) ;
558    my ($old_fv) = $db->filter_fetch_value 
559                         (sub { $_ = "[$_]"; $fetch_value = $_ }) ;
560    my ($old_sv) = $db->filter_store_value 
561                         (sub { s/o/x/g; $store_value = $_ }) ;
562    
563    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
564    $h[1] = "Joe" ;
565    #                   fk   sk     fv    sv
566    ok(95, checkOutput( "", 2, "", "Jxe")) ;
567
568    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
569    ok(96, $h[1] eq "[Jxe]");
570    #                   fk   sk     fv    sv
571    ok(97, checkOutput( "", 2, "[Jxe]", "")) ;
572
573    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
574    ok(98, $db->FIRSTKEY() == 1) ;
575    #                   fk   sk     fv    sv
576    ok(99, checkOutput( 1, "", "", "")) ;
577    
578    # put the original filters back
579    $db->filter_fetch_key   ($old_fk);
580    $db->filter_store_key   ($old_sk);
581    $db->filter_fetch_value ($old_fv);
582    $db->filter_store_value ($old_sv);
583
584    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
585    $h[0] = "joe" ;
586    ok(100, checkOutput( "", 0, "", "joe")) ;
587
588    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
589    ok(101, $h[0] eq "joe");
590    ok(102, checkOutput( "", 0, "joe", "")) ;
591
592    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
593    ok(103, $db->FIRSTKEY() == 0) ;
594    ok(104, checkOutput( 0, "", "", "")) ;
595
596    # delete the filters
597    $db->filter_fetch_key   (undef);
598    $db->filter_store_key   (undef);
599    $db->filter_fetch_value (undef);
600    $db->filter_store_value (undef);
601
602    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
603    $h[0] = "joe" ;
604    ok(105, checkOutput( "", "", "", "")) ;
605
606    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
607    ok(106, $h[0] eq "joe");
608    ok(107, checkOutput( "", "", "", "")) ;
609
610    ($fetch_key, $store_key, $fetch_value, $store_value) = ("") x 4 ;
611    ok(108, $db->FIRSTKEY() == 0) ;
612    ok(109, checkOutput( "", "", "", "")) ;
613
614    undef $db ;
615    untie @h;
616    unlink $Dfile;
617 }
618
619 {    
620     # DBM Filter with a closure
621
622     use warnings ;
623     use strict ;
624     my (@h, $db) ;
625
626     unlink $Dfile;
627     ok(110, $db = tie(@h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0640, $DB_RECNO ) );
628
629     my %result = () ;
630
631     sub Closure
632     {
633         my ($name) = @_ ;
634         my $count = 0 ;
635         my @kept = () ;
636
637         return sub { ++$count ; 
638                      push @kept, $_ ; 
639                      $result{$name} = "$name - $count: [@kept]" ;
640                    }
641     }
642
643     $db->filter_store_key(Closure("store key")) ;
644     $db->filter_store_value(Closure("store value")) ;
645     $db->filter_fetch_key(Closure("fetch key")) ;
646     $db->filter_fetch_value(Closure("fetch value")) ;
647
648     $_ = "original" ;
649
650     $h[0] = "joe" ;
651     ok(111, $result{"store key"} eq "store key - 1: [0]");
652     ok(112, $result{"store value"} eq "store value - 1: [joe]");
653     ok(113, ! defined $result{"fetch key"} );
654     ok(114, ! defined $result{"fetch value"} );
655     ok(115, $_ eq "original") ;
656
657     ok(116, $db->FIRSTKEY() == 0 ) ;
658     ok(117, $result{"store key"} eq "store key - 1: [0]");
659     ok(118, $result{"store value"} eq "store value - 1: [joe]");
660     ok(119, $result{"fetch key"} eq "fetch key - 1: [0]");
661     ok(120, ! defined $result{"fetch value"} );
662     ok(121, $_ eq "original") ;
663
664     $h[7]  = "john" ;
665     ok(122, $result{"store key"} eq "store key - 2: [0 7]");
666     ok(123, $result{"store value"} eq "store value - 2: [joe john]");
667     ok(124, $result{"fetch key"} eq "fetch key - 1: [0]");
668     ok(125, ! defined $result{"fetch value"} );
669     ok(126, $_ eq "original") ;
670
671     ok(127, $h[0] eq "joe");
672     ok(128, $result{"store key"} eq "store key - 3: [0 7 0]");
673     ok(129, $result{"store value"} eq "store value - 2: [joe john]");
674     ok(130, $result{"fetch key"} eq "fetch key - 1: [0]");
675     ok(131, $result{"fetch value"} eq "fetch value - 1: [joe]");
676     ok(132, $_ eq "original") ;
677
678     undef $db ;
679     untie @h;
680     unlink $Dfile;
681 }               
682
683 {
684    # DBM Filter recursion detection
685    use warnings ;
686    use strict ;
687    my (@h, $db) ;
688    unlink $Dfile;
689
690    ok(133, $db = tie(@h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0640, $DB_RECNO ) );
691
692    $db->filter_store_key (sub { $_ = $h[0] }) ;
693
694    eval '$h[1] = 1234' ;
695    ok(134, $@ =~ /^recursion detected in filter_store_key at/ );
696    
697    undef $db ;
698    untie @h;
699    unlink $Dfile;
700 }
701
702
703 {
704    # Examples from the POD
705
706   my $file = "xyzt" ;
707   {
708     my $redirect = new Redirect $file ;
709
710     use warnings FATAL => qw(all);
711     use strict ;
712     use DB_File ;
713
714     my $filename = "text" ;
715     unlink $filename ;
716
717     my @h ;
718     my $x = tie @h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_RECNO 
719         or die "Cannot open file 'text': $!\n" ;
720
721     # Add a few key/value pairs to the file
722     $h[0] = "orange" ;
723     $h[1] = "blue" ;
724     $h[2] = "yellow" ;
725
726     $FA ? push @h, "green", "black" 
727         : $x->push("green", "black") ;
728
729     my $elements = $FA ? scalar @h : $x->length ;
730     print "The array contains $elements entries\n" ;
731
732     my $last = $FA ? pop @h : $x->pop ;
733     print "popped $last\n" ;
734
735     $FA ? unshift @h, "white" 
736         : $x->unshift("white") ;
737     my $first = $FA ? shift @h : $x->shift ;
738     print "shifted $first\n" ;
739
740     # Check for existence of a key
741     print "Element 1 Exists with value $h[1]\n" if $h[1] ;
742
743     # use a negative index
744     print "The last element is $h[-1]\n" ;
745     print "The 2nd last element is $h[-2]\n" ;
746
747     undef $x ;
748     untie @h ;
749
750     unlink $filename ;
751   }  
752
753   ok(135, docat_del($file) eq <<'EOM') ;
754 The array contains 5 entries
755 popped black
756 shifted white
757 Element 1 Exists with value blue
758 The last element is green
759 The 2nd last element is yellow
760 EOM
761
762   my $save_output = "xyzt" ;
763   {
764     my $redirect = new Redirect $save_output ;
765
766     use warnings FATAL => qw(all);
767     use strict ;
768     use vars qw(@h $H $file $i) ;
769     use DB_File ;
770     use Fcntl ;
771     
772     $file = "text" ;
773
774     unlink $file ;
775
776     $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0640, $DB_RECNO 
777         or die "Cannot open file $file: $!\n" ;
778     
779     # first create a text file to play with
780     $h[0] = "zero" ;
781     $h[1] = "one" ;
782     $h[2] = "two" ;
783     $h[3] = "three" ;
784     $h[4] = "four" ;
785
786     
787     # Print the records in order.
788     #
789     # The length method is needed here because evaluating a tied
790     # array in a scalar context does not return the number of
791     # elements in the array.  
792
793     print "\nORIGINAL\n" ;
794     foreach $i (0 .. $H->length - 1) {
795         print "$i: $h[$i]\n" ;
796     }
797
798     # use the push & pop methods
799     $a = $H->pop ;
800     $H->push("last") ;
801     print "\nThe last record was [$a]\n" ;
802
803     # and the shift & unshift methods
804     $a = $H->shift ;
805     $H->unshift("first") ;
806     print "The first record was [$a]\n" ;
807
808     # Use the API to add a new record after record 2.
809     $i = 2 ;
810     $H->put($i, "Newbie", R_IAFTER) ;
811
812     # and a new record before record 1.
813     $i = 1 ;
814     $H->put($i, "New One", R_IBEFORE) ;
815
816     # delete record 3
817     $H->del(3) ;
818
819     # now print the records in reverse order
820     print "\nREVERSE\n" ;
821     for ($i = $H->length - 1 ; $i >= 0 ; -- $i)
822       { print "$i: $h[$i]\n" }
823
824     # same again, but use the API functions instead
825     print "\nREVERSE again\n" ;
826     my ($s, $k, $v)  = (0, 0, 0) ;
827     for ($s = $H->seq($k, $v, R_LAST) ; 
828              $s == 0 ; 
829              $s = $H->seq($k, $v, R_PREV))
830       { print "$k: $v\n" }
831
832     undef $H ;
833     untie @h ;    
834
835     unlink $file ;
836   }  
837
838   ok(136, docat_del($save_output) eq <<'EOM') ;
839
840 ORIGINAL
841 0: zero
842 1: one
843 2: two
844 3: three
845 4: four
846
847 The last record was [four]
848 The first record was [zero]
849
850 REVERSE
851 5: last
852 4: three
853 3: Newbie
854 2: one
855 1: New One
856 0: first
857
858 REVERSE again
859 5: last
860 4: three
861 3: Newbie
862 2: one
863 1: New One
864 0: first
865 EOM
866    
867 }
868
869 {
870     # Bug ID 20001013.009
871     #
872     # test that $hash{KEY} = undef doesn't produce the warning
873     #     Use of uninitialized value in null operation 
874     use warnings ;
875     use strict ;
876     use DB_File ;
877
878     unlink $Dfile;
879     my @h ;
880     my $a = "";
881     local $SIG{__WARN__} = sub {$a = $_[0]} ;
882     
883     tie @h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0664, $DB_RECNO 
884         or die "Can't open file: $!\n" ;
885     $h[0] = undef;
886     ok(137, $a eq "") ;
887     untie @h ;
888     unlink $Dfile;
889 }
890
891 {
892     # test that %hash = () doesn't produce the warning
893     #     Argument "" isn't numeric in entersub
894     use warnings ;
895     use strict ;
896     use DB_File ;
897     my $a = "";
898     local $SIG{__WARN__} = sub {$a = $_[0]} ;
899
900     unlink $Dfile;
901     my @h ;
902     
903     tie @h, 'DB_File', $Dfile, O_RDWR|O_CREAT, 0664, $DB_RECNO 
904         or die "Can't open file: $!\n" ;
905     @h = (); ;
906     ok(138, $a eq "") ;
907     untie @h ;
908     unlink $Dfile;
909 }
910
911 # Only test splice if this is a newish version of Perl
912 exit unless $FA ;
913
914 # Test SPLICE
915
916 # These are a few regression tests: bundles of five arguments to pass
917 # to test_splice().  The first four arguments correspond to those
918 # given to splice(), and the last says which context to call it in
919 # (scalar, list or void).
920
921 # The expected result is not needed because we get that by running
922 # Perl's built-in splice().
923
924 my @tests = ([ [ 'falsely', 'dinosaur', 'remedy', 'commotion',
925                  'rarely', 'paleness' ],
926                -4, -2,
927                [ 'redoubled', 'Taylorize', 'Zoe', 'halogen' ],
928                'void' ],
929
930              [ [ 'a' ], -2, 1, [ 'B' ], 'void' ],
931
932              [ [ 'Hartley', 'Islandia', 'assents', 'wishful' ],
933                0, -4,
934                [ 'maids' ],
935                'void' ],
936
937              [ [ 'visibility', 'pocketful', 'rectangles' ],
938                -10, 0,
939                [ 'garbages' ],
940                'void' ],
941
942              [ [ 'sleeplessly' ],
943                8, -4,
944                [ 'Margery', 'clearing', 'repercussion', 'clubs',
945                  'arise' ],
946                'void' ],
947
948              [ [ 'chastises', 'recalculates' ],
949                0, 0,
950                [ 'momentariness', 'mediates', 'accents', 'toils',
951                  'regaled' ],
952                'void' ],
953
954              [ [ 'b', '' ],
955                9, 8,
956                [ 'otrb', 'stje', 'ixrpw', 'vxfx', 'lhhf' ],
957                'scalar' ],
958
959              [ [ 'b', '' ],
960                undef, undef,
961                [ 'otrb', 'stje', 'ixrpw', 'vxfx', 'lhhf' ],
962                'scalar' ],
963              
964              [ [ 'riheb' ], -8, undef, [], 'void' ],
965
966              [ [ 'uft', 'qnxs', '' ],
967                6, -2,
968                [ 'znp', 'mhnkh', 'bn' ],
969                'void' ],
970             );
971
972 my $testnum = 139;
973 my $failed = 0;
974 require POSIX; my $tmp = POSIX::tmpnam();
975 foreach my $test (@tests) {
976     my $err = test_splice(@$test);
977     if (defined $err) {
978         require Data::Dumper;
979         print STDERR "failed: ", Data::Dumper::Dumper($test);
980         print STDERR "error: $err\n";
981         $failed = 1;
982         ok($testnum++, 0);
983     }
984     else { ok($testnum++, 1) }
985 }
986
987 if ($failed) {
988     # Not worth running the random ones
989     print STDERR 'skipping ', $testnum++, "\n";
990 }
991 else {
992     # A thousand randomly-generated tests
993     $failed = 0;
994     srand(0);
995     foreach (0 .. 1000 - 1) {
996         my $test = rand_test();
997         my $err = test_splice(@$test);
998         if (defined $err) {
999             require Data::Dumper;
1000             print STDERR "failed: ", Data::Dumper::Dumper($test);
1001             print STDERR "error: $err\n";
1002             $failed = 1;
1003             print STDERR "skipping any remaining random tests\n";
1004             last;
1005         }
1006     }
1007
1008     ok($testnum++, not $failed);
1009 }
1010
1011 die if $testnum != $total_tests + 1;
1012
1013 exit ;
1014
1015 # Subroutines for SPLICE testing
1016
1017 # test_splice()
1018
1019 # Test the new splice() against Perl's built-in one.  The first four
1020 # parameters are those passed to splice(), except that the lists must
1021 # be (explicitly) passed by reference, and are not actually modified.
1022 # (It's just a test!)  The last argument specifies the context in
1023 # which to call the functions: 'list', 'scalar', or 'void'.
1024
1025 # Returns:
1026 #   undef, if the two splices give the same results for the given
1027 #     arguments and context;
1028
1029 #   an error message showing the difference, otherwise.
1030
1031 # Reads global variable $tmp.
1032
1033 sub test_splice {
1034     die 'usage: test_splice(array, offset, length, list, context)' if @_ != 5;
1035     my ($array, $offset, $length, $list, $context) = @_;
1036     my @array = @$array;
1037     my @list = @$list;
1038
1039     open(TEXT, ">$tmp") or die "cannot write to $tmp: $!";
1040     foreach (@array) { print TEXT "$_\n" }
1041     close TEXT or die "cannot close $tmp: $!";
1042     
1043     my @h;
1044     my $H = tie @h, 'DB_File', $tmp, O_RDWR, 0644, $DB_RECNO
1045       or die "cannot open $tmp: $!";
1046     
1047     return "basic DB_File sanity check failed"
1048       if list_diff(\@array, \@h);
1049
1050     # Output from splice():
1051     # Returned value (munged a bit), error msg, warnings
1052     # 
1053     my ($s_r, $s_error, @s_warnings);
1054
1055     my $gather_warning = sub { push @s_warnings, $_[0] };
1056     if ($context eq 'list') {
1057         my @r;
1058         eval {
1059             local $SIG{__WARN__} = $gather_warning;
1060             @r = splice @array, $offset, $length, @list;
1061         };
1062         $s_error = $@;
1063         $s_r = \@r;
1064     }
1065     elsif ($context eq 'scalar') {
1066         my $r;
1067         eval {
1068             local $SIG{__WARN__} = $gather_warning;
1069             $r = splice @array, $offset, $length, @list;
1070         };
1071         $s_error = $@;
1072         $s_r = [ $r ];
1073     }
1074     elsif ($context eq 'void') {
1075         eval {
1076             local $SIG{__WARN__} = $gather_warning;
1077             splice @array, $offset, $length, @list;
1078         };
1079         $s_error = $@;
1080         $s_r = [];
1081     }
1082     else {
1083         die "bad context $context";
1084     }
1085
1086     foreach ($s_error, @s_warnings) {
1087         chomp;
1088         s/ at \S+ line \d+\.$//;
1089     }
1090
1091     # Now do the same for DB_File's version of splice
1092     my ($ms_r, $ms_error, @ms_warnings);
1093     $gather_warning = sub { push @ms_warnings, $_[0] };
1094     if ($context eq 'list') {
1095         my @r;
1096         eval {
1097             local $SIG{__WARN__} = $gather_warning;
1098             @r = splice @h, $offset, $length, @list;
1099         };
1100         $ms_error = $@;
1101         $ms_r = \@r;
1102     }
1103     elsif ($context eq 'scalar') {
1104         my $r;
1105         eval {
1106             local $SIG{__WARN__} = $gather_warning;
1107             $r = splice @h, $offset, $length, @list;
1108         };
1109         $ms_error = $@;
1110         $ms_r = [ $r ];
1111     }
1112     elsif ($context eq 'void') {
1113         eval {
1114             local $SIG{__WARN__} = $gather_warning;
1115             splice @h, $offset, $length, @list;
1116         };
1117         $ms_error = $@;
1118         $ms_r = [];
1119     }
1120     else {
1121         die "bad context $context";
1122     }
1123
1124     foreach ($ms_error, @ms_warnings) {
1125         chomp;
1126         s/ at \S+ line \d+\.?$//;
1127     }
1128
1129     return "different errors: '$s_error' vs '$ms_error'"
1130       if $s_error ne $ms_error;
1131     return('different return values: ' . Dumper($s_r) . ' vs ' . Dumper($ms_r))
1132       if list_diff($s_r, $ms_r);
1133     return('different changed list: ' . Dumper(\@array) . ' vs ' . Dumper(\@h))
1134       if list_diff(\@array, \@h);
1135
1136     if ((scalar @s_warnings) != (scalar @ms_warnings)) {
1137         return 'different number of warnings';
1138     }
1139
1140     while (@s_warnings) {
1141         my $sw  = shift @s_warnings;
1142         my $msw = shift @ms_warnings;
1143         
1144         if (defined $sw and defined $msw) {
1145             $msw =~ s/ \(.+\)$//;
1146             $msw =~ s/ in splice$// if $] < 5.006;
1147             if ($sw ne $msw) {
1148                 return "different warning: '$sw' vs '$msw'";
1149             }
1150         }
1151         elsif (not defined $sw and not defined $msw) {
1152             # Okay.
1153         }
1154         else {
1155             return "one warning defined, another undef";
1156         }
1157     }
1158     
1159     undef $H;
1160     untie @h;
1161     
1162     open(TEXT, $tmp) or die "cannot open $tmp: $!";
1163     @h = <TEXT>; chomp @h;
1164     close TEXT or die "cannot close $tmp: $!";
1165     return('list is different when re-read from disk: '
1166            . Dumper(\@array) . ' vs ' . Dumper(\@h))
1167       if list_diff(\@array, \@h);
1168
1169     return undef; # success
1170 }
1171
1172
1173 # list_diff()
1174 #
1175 # Do two lists differ?
1176 #
1177 # Parameters:
1178 #   reference to first list
1179 #   reference to second list
1180 #
1181 # Returns true iff they differ.  Only works for lists of (string or
1182 # undef). 
1183
1184 # Surely there is a better way to do this?
1185
1186 sub list_diff {
1187     die 'usage: list_diff(ref to first list, ref to second list)'
1188       if @_ != 2;
1189     my ($a, $b) = @_;
1190     my @a = @$a; my @b = @$b;
1191     return 1 if (scalar @a) != (scalar @b);
1192     for (my $i = 0; $i < @a; $i++) {
1193         my ($ae, $be) = ($a[$i], $b[$i]);
1194         if (defined $ae and defined $be) {
1195             return 1 if $ae ne $be;
1196         }
1197         elsif (not defined $ae and not defined $be) {
1198             # Two undefined values are 'equal'
1199         }
1200         else {
1201             return 1;
1202         }
1203     }
1204     return 0;
1205
1206
1207
1208 # rand_test()
1209
1210 # Think up a random ARRAY, OFFSET, LENGTH, LIST, and context.
1211 # ARRAY or LIST might be empty, and OFFSET or LENGTH might be
1212 # undefined.  Return a 'test' - a listref of these five things.
1213
1214 sub rand_test {
1215     die 'usage: rand_test()' if @_;
1216     my @contexts = qw<list scalar void>;
1217     my $context = $contexts[int(rand @contexts)];
1218     return [ rand_list(),
1219              (rand() < 0.5) ? (int(rand(20)) - 10) : undef,
1220              (rand() < 0.5) ? (int(rand(20)) - 10) : undef,
1221              rand_list(),
1222              $context ];
1223 }
1224
1225
1226 sub rand_list {
1227     die 'usage: rand_list()' if @_;
1228     my @r;
1229
1230     while (rand() > 0.1 * (scalar @r + 1)) {
1231         push @r, rand_word();
1232     }
1233     return \@r;
1234 }
1235
1236
1237 sub rand_word {
1238     die 'usage: rand_word()' if @_;
1239     my $r = '';
1240     my @chars = qw<a b c d e f g h i j k l m n o p q r s t u v w x y z>;
1241     while (rand() > 0.1 * (length($r) + 1)) {
1242         $r .= $chars[int(rand(scalar @chars))];
1243     }
1244     return $r;
1245 }