Bug 28026: Add call_recursive() as a supplement for call()
[koha.git] / t / db_dependent / Koha / Plugins / Plugins.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, see <http://www.gnu.org/licenses>.
16
17 use Modern::Perl;
18
19 use Archive::Extract;
20 use CGI;
21 use Cwd qw(abs_path);
22 use File::Basename;
23 use File::Spec;
24 use File::Temp qw( tempdir tempfile );
25 use FindBin qw($Bin);
26 use Module::Load::Conditional qw(can_load);
27 use Test::MockModule;
28 use Test::More tests => 59;
29 use Test::Warn;
30
31 use C4::Context;
32 use Koha::Database;
33 use Koha::Plugins::Methods;
34
35 use t::lib::Mocks;
36
37 BEGIN {
38     # Mock pluginsdir before loading Plugins module
39     my $path = dirname(__FILE__) . '/../../../lib';
40     t::lib::Mocks::mock_config( 'pluginsdir', $path );
41
42     use_ok('Koha::Plugins');
43     use_ok('Koha::Plugins::Handler');
44     use_ok('Koha::Plugins::Base');
45     use_ok('Koha::Plugin::Test');
46 }
47
48 my $schema = Koha::Database->new->schema;
49
50 subtest 'call() tests' => sub {
51
52     plan tests => 4;
53
54     $schema->storage->txn_begin;
55     # Temporarily remove any installed plugins data
56     Koha::Plugins::Methods->delete;
57
58     t::lib::Mocks::mock_config('enable_plugins', 1);
59     my $plugins = Koha::Plugins->new({ enable_plugins => 1 });
60
61     my @plugins;
62
63     warnings_are
64      { @plugins = $plugins->InstallPlugins; }
65      [ "Calling 'install' died for plugin Koha::Plugin::BrokenInstall", "Calling 'upgrade' died for plugin Koha::Plugin::BrokenUpgrade" ];
66
67     foreach my $plugin (@plugins) {
68         $plugin->enable();
69     }
70
71     my @responses = Koha::Plugins->call('check_password', { password => 'foo' });
72
73     my $expected = [ { error => 1, msg => 'PIN should be four digits' } ];
74     is_deeply(\@responses, $expected, 'call() should return all responses from plugins');
75
76     # Make sure parameters are correctly passed to the plugin method
77     @responses = Koha::Plugins->call('check_password', { password => '1234' });
78
79     $expected = [ { error => 0 } ];
80     is_deeply(\@responses, $expected, 'call() should return all responses from plugins');
81
82     t::lib::Mocks::mock_config('enable_plugins', 0);
83     @responses = Koha::Plugins->call('check_password', { password => '1234' });
84     is_deeply(\@responses, [], 'call() should return an empty array if plugins are disabled');
85
86     $schema->storage->txn_rollback;
87 };
88
89 subtest 'call_recursive() tests' => sub {
90     plan tests => 6;
91
92     $schema->storage->txn_begin;
93     # Temporarily remove any installed plugins data
94     Koha::Plugins::Methods->delete;
95
96     t::lib::Mocks::mock_config('enable_plugins', 1);
97     my $plugins = Koha::Plugins->new({ enable_plugins => 1 });
98     my @plugins = $plugins->InstallPlugins;
99     foreach my $plugin (@plugins) {
100         $plugin->enable();
101     }
102
103     my (@responses) = Koha::Plugins->call_recursive('test_call_recursive', 1);
104     is( scalar @responses, 1, "Got back one element" );
105     is( $responses[0], 11, "Got expected response" );
106
107     (@responses) = Koha::Plugins->call_recursive('test_call_recursive', 'abcd');
108     is( scalar @responses, 1, "Got back one element" );
109     is( $responses[0], 'abcdabcd', "Got expected response" );
110
111     t::lib::Mocks::mock_config('enable_plugins', 0);
112     (@responses) = Koha::Plugins->call_recursive('test_call_recursive', 1);
113     is( scalar @responses, 1, "Got back one element" );
114     is( $responses[0], 1, "call_recursive should return the original arguments if plugins are disabled" );
115
116     $schema->storage->txn_rollback;
117 };
118
119 subtest 'GetPlugins() tests' => sub {
120
121     plan tests => 3;
122
123     $schema->storage->txn_begin;
124     # Temporarily remove any installed plugins data
125     Koha::Plugins::Methods->delete;
126
127     my $plugins = Koha::Plugins->new({ enable_plugins => 1 });
128
129     warnings_are { $plugins->InstallPlugins; }
130     [ "Calling 'install' died for plugin Koha::Plugin::BrokenInstall", "Calling 'upgrade' died for plugin Koha::Plugin::BrokenUpgrade" ];
131
132     my @plugins = $plugins->GetPlugins({ method => 'report', all => 1 });
133
134     my @names = map { $_->get_metadata()->{'name'} } @plugins;
135     is( scalar grep( /^Test Plugin$/, @names), 1, "Koha::Plugins::GetPlugins functions correctly" );
136
137     @plugins = $plugins->GetPlugins({ metadata => { my_example_tag  => 'find_me' }, all => 1 });
138     @names = map { $_->get_metadata()->{'name'} } @plugins;
139     is( scalar @names, 2, "Only two plugins found via a metadata tag" );
140
141     $schema->storage->txn_rollback;
142 };
143
144 subtest 'Version upgrade tests' => sub {
145
146     plan tests => 1;
147
148     $schema->storage->txn_begin;
149
150     my $plugin = Koha::Plugin::Test->new( { enable_plugins => 1, cgi => CGI->new } );
151
152     # make sure there's no version on the DB
153     $schema->resultset('PluginData')
154         ->search( { plugin_class => $plugin->{class}, plugin_key => '__INSTALLED_VERSION__' } )
155         ->delete;
156
157     $plugin = Koha::Plugin::Test->new( { enable_plugins => 1, cgi => CGI->new } );
158     my $version = $plugin->retrieve_data('__INSTALLED_VERSION__');
159
160     is( $version, $plugin->get_metadata->{version}, 'Version has been populated correctly' );
161
162     $schema->storage->txn_rollback;
163 };
164
165 subtest 'is_enabled() tests' => sub {
166
167     plan tests => 3;
168     $schema->storage->txn_begin;
169
170     # Make sure there's no previous installs or leftovers on DB
171     Koha::Plugins::Methods->delete;
172     $schema->resultset('PluginData')->delete;
173
174     my $plugin = Koha::Plugin::Test->new({ enable_plugins => 1, cgi => CGI->new });
175     ok( $plugin->is_enabled, 'Plugins enabled by default' );
176
177     # disable
178     $plugin->disable;
179     ok( !$plugin->is_enabled, 'Calling ->disable disables the plugin' );
180
181     # enable
182     $plugin->enable;
183     ok( $plugin->is_enabled, 'Calling ->enable enabled the plugin' );
184
185     $schema->storage->txn_rollback;
186 };
187
188 $schema->storage->txn_begin;
189 Koha::Plugins::Methods->delete;
190
191 warnings_are { Koha::Plugins->new( { enable_plugins => 1 } )->InstallPlugins(); }
192 [ "Calling 'install' died for plugin Koha::Plugin::BrokenInstall", "Calling 'upgrade' died for plugin Koha::Plugin::BrokenUpgrade" ];
193
194 ok( Koha::Plugins::Methods->search( { plugin_class => 'Koha::Plugin::Test' } )->count, 'Test plugin methods added to database' );
195 is( Koha::Plugins::Methods->search({ plugin_class => 'Koha::Plugin::Test', plugin_method => '_private_sub' })->count, 0, 'Private methods are skipped' );
196
197 my $mock_plugin = Test::MockModule->new( 'Koha::Plugin::Test' );
198 $mock_plugin->mock( 'test_template', sub {
199     my ( $self, $file ) = @_;
200     my $template = $self->get_template({ file => $file });
201     $template->param( filename => $file );
202     return $template->output;
203 });
204
205 ok( can_load( modules => { "Koha::Plugin::Test" => undef } ), 'Test can_load' );
206
207 my $plugin = Koha::Plugin::Test->new({ enable_plugins => 1, cgi => CGI->new });
208
209 isa_ok( $plugin, "Koha::Plugin::Test", 'Test plugin class' );
210 isa_ok( $plugin, "Koha::Plugins::Base", 'Test plugin parent class' );
211
212 ok( $plugin->can('report'), 'Test plugin can report' );
213 ok( $plugin->can('tool'), 'Test plugin can tool' );
214 ok( $plugin->can('to_marc'), 'Test plugin can to_marc' );
215 ok( $plugin->can('intranet_catalog_biblio_enhancements'), 'Test plugin can intranet_catalog_biblio_enhancements');
216 ok( $plugin->can('intranet_catalog_biblio_enhancements_toolbar_button'), 'Test plugin can intranet_catalog_biblio_enhancements_toolbar_button' );
217 ok( $plugin->can('opac_online_payment'), 'Test plugin can opac_online_payment' );
218 ok( $plugin->can('after_hold_create'), 'Test plugin can after_hold_create' );
219 ok( $plugin->can('opac_online_payment_begin'), 'Test plugin can opac_online_payment_begin' );
220 ok( $plugin->can('opac_online_payment_end'), 'Test plugin can opac_online_payment_end' );
221 ok( $plugin->can('opac_head'), 'Test plugin can opac_head' );
222 ok( $plugin->can('opac_js'), 'Test plugin can opac_js' );
223 ok( $plugin->can('intranet_head'), 'Test plugin can intranet_head' );
224 ok( $plugin->can('intranet_js'), 'Test plugin can intranet_js' );
225 ok( $plugin->can('configure'), 'Test plugin can configure' );
226 ok( $plugin->can('install'), 'Test plugin can install' );
227 ok( $plugin->can('upgrade'), 'Test plugin can upgrade' );
228 ok( $plugin->can('uninstall'), 'Test plugin can install' );
229
230 is( Koha::Plugins::Handler->run({ class => "Koha::Plugin::Test", method => 'report', enable_plugins => 1 }), "Koha::Plugin::Test::report", 'Test run plugin report method' );
231
232 my $metadata = $plugin->get_metadata();
233 is( $metadata->{'name'}, 'Test Plugin', 'Test $plugin->get_metadata()' );
234
235 is( $plugin->get_qualified_table_name('mytable'), 'koha_plugin_test_mytable', 'Test $plugin->get_qualified_table_name()' );
236 is( $plugin->get_plugin_http_path(), '/plugin/Koha/Plugin/Test', 'Test $plugin->get_plugin_http_path()' );
237
238 # test absolute path change in get_template with Koha::Plugin::Test
239 # using the mock set before
240 # we also add tmpdir as an approved template dir
241 t::lib::Mocks::mock_config( 'pluginsdir', [ C4::Context->temporary_directory ] );
242 my ( $fh, $fn ) = tempfile( SUFFIX => '.tt', UNLINK => 1, DIR => C4::Context->temporary_directory );
243 print $fh 'I am [% filename %]';
244 close $fh;
245 my $classname = ref($plugin);
246 like( $plugin->test_template($fn), qr/^I am $fn/, 'Template works' );
247
248 my $result = $plugin->enable;
249 is( ref($result), 'Koha::Plugin::Test' );
250
251 # testing GetPlugins
252 my @plugins = Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins({
253     method => 'report'
254 });
255
256 my @names = map { $_->get_metadata()->{'name'} } @plugins;
257 is( scalar grep( /^Test Plugin$/, @names), 1, "Koha::Plugins::GetPlugins functions correctly" );
258 @plugins =  Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins({
259     metadata => { my_example_tag  => 'find_me' },
260 });
261
262 @names = map { $_->get_metadata()->{'name'} } @plugins;
263 is( scalar grep( /^Test Plugin$/, @names), 1, "GetPlugins also found Test Plugin via a metadata tag" );
264
265 $result = $plugin->disable;
266 is( ref($result), 'Koha::Plugin::Test' );
267
268 @plugins = Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins();
269 @names = map { $_->get_metadata()->{'name'} } @plugins;
270 is( scalar grep( /^Test Plugin$/, @names), 0, "GetPlugins does not found disabled Test Plugin" );
271
272 @plugins = Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins({ all => 1 });
273 @names = map { $_->get_metadata()->{'name'} } @plugins;
274 is( scalar grep( /^Test Plugin$/, @names), 1, "With all param, GetPlugins found disabled Test Plugin" );
275
276 for my $pass ( 1 .. 2 ) {
277     my $plugins_dir;
278     my $module_name = 'Koha::Plugin::Com::ByWaterSolutions::KitchenSink';
279     my $pm_path = 'Koha/Plugin/Com/ByWaterSolutions/KitchenSink.pm';
280     if ( $pass == 1 ) {
281         my $plugins_dir1 = tempdir( CLEANUP => 1 );
282         t::lib::Mocks::mock_config('pluginsdir', $plugins_dir1);
283         $plugins_dir = $plugins_dir1;
284         push @INC, $plugins_dir1;
285     } else {
286         my $plugins_dir1 = tempdir( CLEANUP => 1 );
287         my $plugins_dir2 = tempdir( CLEANUP => 1 );
288         t::lib::Mocks::mock_config('pluginsdir', [ $plugins_dir2, $plugins_dir1 ]);
289         $plugins_dir = $plugins_dir2;
290         pop @INC;
291         push @INC, $plugins_dir2;
292         push @INC, $plugins_dir1;
293     }
294     my $full_pm_path = $plugins_dir . '/' . $pm_path;
295
296     my $ae = Archive::Extract->new( archive => "$Bin/KitchenSinkPlugin.kpz", type => 'zip' );
297     unless ( $ae->extract( to => $plugins_dir ) ) {
298         warn "ERROR: " . $ae->error;
299     }
300     use_ok('Koha::Plugin::Com::ByWaterSolutions::KitchenSink');
301     $plugin = Koha::Plugin::Com::ByWaterSolutions::KitchenSink->new({ enable_plugins => 1});
302     my $table = $plugin->get_qualified_table_name( 'mytable' );
303
304     ok( -f $plugins_dir . "/Koha/Plugin/Com/ByWaterSolutions/KitchenSink.pm", "KitchenSink plugin installed successfully" );
305     $INC{$pm_path} = $full_pm_path; # FIXME I do not really know why, but if this is moved before the $plugin constructor, it will fail with Can't locate object method "new" via package "Koha::Plugin::Com::ByWaterSolutions::KitchenSink"
306     warnings_are
307         { Koha::Plugins->new( { enable_plugins => 1 } )->InstallPlugins(); }
308         [ "Calling 'install' died for plugin Koha::Plugin::BrokenInstall", "Calling 'upgrade' died for plugin Koha::Plugin::BrokenUpgrade" ];
309     ok( -f $full_pm_path, "Koha::Plugins::Handler::delete works correctly (pass $pass)" );
310     Koha::Plugins::Handler->delete({ class => "Koha::Plugin::Com::ByWaterSolutions::KitchenSink", enable_plugins => 1 });
311     my $sth = C4::Context->dbh->table_info( undef, undef, $table, 'TABLE' );
312     my $info = $sth->fetchall_arrayref;
313     is( @$info, 0, "Table $table does no longer exist" );
314     ok( !( -f $full_pm_path ), "Koha::Plugins::Handler::delete works correctly (pass $pass)" );
315 }
316
317 subtest 'output and output_html tests' => sub {
318
319     plan tests => 6;
320
321     # Trick stdout to be able to test
322     local *STDOUT;
323     my $stdout;
324     open STDOUT, '>', \$stdout;
325
326     my $plugin = Koha::Plugin::Test->new({ enable_plugins => 1, cgi => CGI->new });
327     $plugin->test_output;
328
329     like($stdout, qr/Cache-control: no-cache/, 'force_no_caching sets Cache-control as desired');
330     like($stdout, qr{Content-Type: application/json; charset=UTF-8}, 'Correct content-type');
331     like($stdout, qr{¡Hola output!}, 'Correct data');
332
333     # reset the stdout buffer
334     $stdout = '';
335     close STDOUT;
336     open STDOUT, '>', \$stdout;
337
338     $plugin->test_output_html;
339
340     like($stdout, qr/Cache-control: no-cache/, 'force_no_caching sets Cache-control as desired');
341     like($stdout, qr{Content-Type: text/html; charset=UTF-8}, 'Correct content-type');
342     like($stdout, qr{¡Hola output_html!}, 'Correct data');
343 };
344
345 subtest 'Test _version_compare' => sub {
346
347     plan tests => 12;
348
349     t::lib::Mocks::mock_config( 'enable_plugins', 1 );
350
351     is( Koha::Plugins::Base::_version_compare( '1.1.1',    '2.2.2' ), -1, "1.1.1 is less then 2.2.2" );
352     is( Koha::Plugins::Base::_version_compare( '2.2.2',    '1.1.1' ),  1, "1.1.1 is greater then 2.2.2" );
353     is( Koha::Plugins::Base::_version_compare( '1.1.1',    '1.1.1' ),  0, "1.1.1 is equal to 1.1.1" );
354     is( Koha::Plugins::Base::_version_compare( '1.01.001', '1.1.1' ),  0, "1.01.001 is equal to 1.1.1" );
355     is( Koha::Plugins::Base::_version_compare( '1',        '1.0.0' ),  0, "1 is equal to 1.0.0" );
356     is( Koha::Plugins::Base::_version_compare( '1.0',      '1.0.0' ),  0, "1.0 is equal to 1.0.0" );
357
358     # OO tests
359     my $plugin = Koha::Plugin::Test->new;
360     is( $plugin->_version_compare( '1.1.1',    '2.2.2' ), -1, "1.1.1 is less then 2.2.2" );
361     is( $plugin->_version_compare( '2.2.2',    '1.1.1' ),  1, "1.1.1 is greater then 2.2.2" );
362     is( $plugin->_version_compare( '1.1.1',    '1.1.1' ),  0, "1.1.1 is equal to 1.1.1" );
363     is( $plugin->_version_compare( '1.01.001', '1.1.1' ),  0, "1.01.001 is equal to 1.1.1" );
364     is( $plugin->_version_compare( '1',        '1.0.0' ),  0, "1 is equal to 1.0.0" );
365     is( $plugin->_version_compare( '1.0',      '1.0.0' ),  0, "1.0 is equal to 1.0.0" );
366 };
367
368 subtest 'bundle_path() tests' => sub {
369
370     plan tests => 1;
371
372     t::lib::Mocks::mock_config( 'enable_plugins', 1 );
373
374     my @current_dir = File::Spec->splitdir(abs_path(__FILE__));
375     # remote Plugins.t
376     pop @current_dir;
377     # remove /Plugins
378     pop @current_dir;
379     # remove /Koha
380     pop @current_dir;
381     # remove db_dependent
382     pop @current_dir;
383
384     my $plugin = Koha::Plugin::Test->new;
385
386     is( $plugin->bundle_path, File::Spec->catdir(@current_dir) . '/lib/Koha/Plugin/Test' );
387
388 };
389
390 subtest 'new() tests' => sub {
391
392     plan tests => 2;
393
394     t::lib::Mocks::mock_config( 'pluginsdir', [ C4::Context->temporary_directory ] );
395     t::lib::Mocks::mock_config( 'enable_plugins', 0 );
396
397     my $result = Koha::Plugins->new();
398     is( $result, undef, 'calling new() on disabled plugins returns undef' );
399
400     $result = Koha::Plugins->new({ enable_plugins => 1 });
401     is( ref($result), 'Koha::Plugins', 'calling new with enable_plugins makes it override the config' );
402 };
403
404 Koha::Plugins::Methods->delete;