gitweb/lib - Cache captured output (using get/set)
[git/jnareb-git.git] / t / t9505 / test_cache_output.pl
blob167bb36bb1fd6349e92615bd7937c2006f04cf28
1 #!/usr/bin/perl
2 use lib (split(/:/, $ENV{GITPERLLIB}));
4 use warnings;
5 use strict;
7 use Test::More;
8 use Capture::Tiny qw(capture);
10 # test source version
11 use lib $ENV{GITWEBLIBDIR} || "$ENV{GIT_BUILD_DIR}/gitweb/lib";
13 # ....................................................................
15 # prototypes must be known at compile time, otherwise they do not work
16 BEGIN { use_ok('GitwebCache::CacheOutput'); }
18 require_ok('GitwebCache::SimpleFileCache');
19 require_ok('GitwebCache::Capture::Simple');
21 diag("Using lib '$INC[0]'");
22 diag("Testing '$INC{'GitwebCache/CacheOutput.pm'}'");
23 diag("Testing '$INC{'GitwebCache/SimpleFileCache.pm'}'");
24 diag("Testing '$INC{'GitwebCache/Capture/Simple.pm'}'");
27 # Test setting up $cache and $capture
28 my $cache = new_ok('GitwebCache::SimpleFileCache' => [], 'The $cache ');
29 my $capture = new_ok('GitwebCache::Capture::Simple' => [], 'The $capture');
31 # ......................................................................
33 # Prepare for testing cache_output
34 my $key = 'Key';
35 my $action_output = <<'EOF';
36 # This is data to be cached and shown
37 EOF
38 my $cached_output = <<"EOF";
39 $action_output# (version recovered from cache)
40 EOF
41 sub action {
42 print $action_output;
45 my $no_capture_output = <<"EOF";
46 $action_output# (no capture)
47 EOF
48 sub no_capture {
49 capture_stop($cache, $capture);
50 print $no_capture_output;
53 # Catch output printed by cache_fetch
54 # (only for 'print <sth>' and 'printf <sth>')
55 sub capture_output_of_cache_output {
56 my $code = shift;
58 my ($stdout, $stderr) = capture {
59 cache_output($cache, $capture, $key, $code);
61 print STDERR $stderr;
62 return $stdout;
65 # clean state
66 $cache->set_expires_in(-1);
67 $cache->remove($key);
68 my $test_data;
70 # first time (if there is no cache) generates cache entry
71 $test_data = capture_output_of_cache_output(\&action);
72 is($test_data, $action_output, 'action output is printed (generated)');
73 is($cache->get($key), $action_output, 'action output is saved in cache (generated)');
75 # second time (if cache is set/valid) reads from cache
76 $cache->set($key, $cached_output);
77 $test_data = capture_output_of_cache_output(\&action);
78 is($test_data, $cached_output, 'action output is printed (from cache)');
80 # test using capture_stop
81 $cache->remove($key);
82 $test_data = capture_output_of_cache_output(\&no_capture);
83 is($test_data, $no_capture_output, 'no_capture output is printed (generated)');
84 ok(! $cache->get($key), 'no_capture output is not captured and not cached');
86 done_testing();