Expect 21st access to have value 21, not 20!
[perl-indexdata-utils.git] / t / 02-IndexData-Utils-PersistentCounter.t
1 use strict;
2 use warnings;
3
4 use Test::More tests => 17;
5 BEGIN { use_ok('IndexData::Utils::PersistentCounter') };
6
7 my $file = "/tmp/id-u-pc-$$";
8 my $counter = new IndexData::Utils::PersistentCounter($file);
9 ok(!defined $counter, "can't open non-existent counter");
10
11 $counter = new IndexData::Utils::PersistentCounter("/x/$file", 1);
12 ok(!defined $counter, "can't create counter in silly place");
13
14 $counter = new IndexData::Utils::PersistentCounter($file, 1);
15 my $detail = defined $counter ? '' : ": $!@";
16 ok(defined $counter, "created new counter$detail");
17
18 foreach my $i (1..5) {
19     my $n = $counter->next();
20     ok(defined $n, "n is defined");
21     ok($n == $i, "n has correct value $i");
22 }
23
24 # Three processes making five accesses each
25 for (my $i = 0; $i < 3; $i ++) {
26     my $pid = fork();
27     if ($pid == 0) {
28         # child
29         foreach my $j (1..5) {
30             my $n = $counter->next();
31             print "# child ", $i+1, ", access ", $j+1, ": value is $n\n";
32         }
33         exit 0;
34     } else {
35         print "# process $pid started\n";
36     }
37 }
38
39 while ((my $pid = wait()) > 0) {
40     print "# process $pid completed\n";
41 }
42
43 my $n = $counter->next();
44 ok($n == 21, "n == 21 on 21 total access (n=$n)");
45
46 my $ok = $counter->delete();
47 ok($ok, "deleted counter file");
48 $counter = new IndexData::Utils::PersistentCounter($file);
49 ok(!defined $counter, "can't open deleted counter");