1
2#########################
3
4use Test::More tests => 8;
5BEGIN { use_ok('Cache::FastMmap') };
6use strict;
7
8#########################
9
10# Insert your test code below, the Test::More module is use()ed here so read
11# its man page ( perldoc Test::More ) for help writing this test script.
12
13my $FC = Cache::FastMmap->new(init_file => 1, serializer => '');
14ok( defined $FC );
15
16my (@Keys, $HitRate);
17$HitRate = RepeatMixTest($FC, 1000, 0.0, \@Keys);
18ok( $HitRate == 0.0, "hit rate 1");
19
20$HitRate = RepeatMixTest($FC, 1000, 0.5, \@Keys);
21ok( $HitRate == 1.0, "hit rate 2");
22
23$HitRate = RepeatMixTest($FC, 1000, 0.8, \@Keys);
24ok( $HitRate == 1.0, "hit rate 3");
25
26$FC = undef;
27@Keys = ();
28
29# Should be repeatable
30srand(123456);
31
32$FC = Cache::FastMmap->new(
33  init_file => 1,
34  page_size => 8192,
35  serializer => ''
36);
37ok( defined $FC );
38
39$HitRate = RepeatMixTest($FC, 1000, 0.0, \@Keys);
40ok( $HitRate == 0.0, "hit rate 1");
41$HitRate = RepeatMixTest($FC, 10000, 0.5, \@Keys);
42ok( $HitRate > 0.8 && $HitRate < 0.95, "hit rate 4 - $HitRate");
43
44
45sub RepeatMixTest {
46  my ($FC, $NItems, $Ratio, $WroteKeys) = @_;
47
48  my ($Read, $ReadHit);
49
50  # Lots of random tests
51  for (1 .. $NItems) {
52
53    # Read/write ratio
54    if (rand() < $Ratio) {
55
56      # Pick a key from known written ones
57      my $K = $WroteKeys->[ rand(@$WroteKeys) ];
58      my $V = $FC->get($K);
59      $Read++;
60
61      # Skip if not found in cache
62      next if !defined $V;
63      $ReadHit++;
64
65      # Offset of 10 past first chars of value are key
66      substr($V, 10, length($K)) eq $K
67        || die "Cache/key not equal: $K, $V";
68
69    } else {
70
71      my $K = RandStr(16);
72      my $V = RandStr(10) . $K . RandStr(int(rand(200)));
73      push @$WroteKeys, $K;
74      $FC->set($K, $V);
75
76    }
77  }
78
79  return $Read ? ($ReadHit/$Read) : 0.0;
80}
81
82sub RandStr {
83  return join '', map { chr(ord('a') + rand(26)) } (1 .. $_[0]);
84}
85
86