Bug 29857: (follow-up) Fix t/db_dependent/Koha/Plugins/Plugins.t
[srvgit] / 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 => 61;
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/plugins';
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     use_ok('Koha::Plugin::TestItemBarcodeTransform');
47 }
48
49 my $schema = Koha::Database->new->schema;
50
51 subtest 'call() tests' => sub {
52
53     plan tests => 4;
54
55     $schema->storage->txn_begin;
56     # Temporarily remove any installed plugins data
57     Koha::Plugins::Methods->delete;
58
59     t::lib::Mocks::mock_config('enable_plugins', 1);
60     my $plugins = Koha::Plugins->new({ enable_plugins => 1 });
61
62     my @plugins;
63
64     warning_is { @plugins = $plugins->InstallPlugins; } undef;
65
66     foreach my $plugin (@plugins) {
67         $plugin->enable();
68     }
69
70     my @responses = Koha::Plugins->call('check_password', { password => 'foo' });
71
72     my $expected = [ { error => 1, msg => 'PIN should be four digits' } ];
73     is_deeply(\@responses, $expected, 'call() should return all responses from plugins');
74
75     # Make sure parameters are correctly passed to the plugin method
76     @responses = Koha::Plugins->call('check_password', { password => '1234' });
77
78     $expected = [ { error => 0 } ];
79     is_deeply(\@responses, $expected, 'call() should return all responses from plugins');
80
81     t::lib::Mocks::mock_config('enable_plugins', 0);
82     @responses = Koha::Plugins->call('check_password', { password => '1234' });
83     is_deeply(\@responses, [], 'call() should return an empty array if plugins are disabled');
84
85     $schema->storage->txn_rollback;
86 };
87
88 subtest 'more call() tests' => sub {
89
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;
99
100     warning_is { @plugins = $plugins->InstallPlugins; } undef;
101
102     foreach my $plugin (@plugins) {
103         $plugin->enable();
104     }
105
106     # Barcode is multiplied by 2 by Koha::Plugin::Test, and again by 4 by Koha::Plugin::TestItemBarcodeTransform
107     # showing that call has passed the same ref to multiple plugins to operate on
108     my $bc = 1;
109     warnings_are
110         { Koha::Plugins->call('item_barcode_transform', \$bc); }
111         [ qq{Plugin error (Test Plugin): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 1'\n},
112           qq{Plugin error (Test Plugin for item_barcode_transform): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 2'\n} ];
113     is( $bc, 8, "Got expected response" );
114
115     my $cn = 'abcd';
116     warnings_are
117         { Koha::Plugins->call('item_barcode_transform', \$bc); }
118         [ qq{Plugin error (Test Plugin): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 8'\n},
119           qq{Plugin error (Test Plugin for item_barcode_transform): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 16'\n} ];
120     is( $cn, 'abcd', "Got expected response" );
121
122     t::lib::Mocks::mock_config('enable_plugins', 0);
123     $bc = 1;
124     Koha::Plugins->call('item_barcode_transform', \$bc);
125     is( $bc, 1, "call should return the original arguments if plugins are disabled" );
126
127     $schema->storage->txn_rollback;
128 };
129
130 subtest 'GetPlugins() tests' => sub {
131
132     plan tests => 3;
133
134     $schema->storage->txn_begin;
135     # Temporarily remove any installed plugins data
136     Koha::Plugins::Methods->delete;
137
138     my $plugins = Koha::Plugins->new({ enable_plugins => 1 });
139
140     warning_is { $plugins->InstallPlugins; } undef;
141
142     my @plugins = $plugins->GetPlugins({ method => 'report', all => 1 });
143
144     my @names = map { $_->get_metadata()->{'name'} } @plugins;
145     is( scalar grep( /^Test Plugin$/, @names), 1, "Koha::Plugins::GetPlugins functions correctly" );
146
147     @plugins = $plugins->GetPlugins({ metadata => { my_example_tag  => 'find_me' }, all => 1 });
148     @names = map { $_->get_metadata()->{'name'} } @plugins;
149     is( scalar @names, 2, "Only two plugins found via a metadata tag" );
150
151     $schema->storage->txn_rollback;
152 };
153
154 subtest 'Version upgrade tests' => sub {
155
156     plan tests => 1;
157
158     $schema->storage->txn_begin;
159
160     my $plugin = Koha::Plugin::Test->new( { enable_plugins => 1, cgi => CGI->new } );
161
162     # make sure there's no version on the DB
163     $schema->resultset('PluginData')
164         ->search( { plugin_class => $plugin->{class}, plugin_key => '__INSTALLED_VERSION__' } )
165         ->delete;
166
167     $plugin = Koha::Plugin::Test->new( { enable_plugins => 1, cgi => CGI->new } );
168     my $version = $plugin->retrieve_data('__INSTALLED_VERSION__');
169
170     is( $version, $plugin->get_metadata->{version}, 'Version has been populated correctly' );
171
172     $schema->storage->txn_rollback;
173 };
174
175 subtest 'is_enabled() tests' => sub {
176
177     plan tests => 3;
178     $schema->storage->txn_begin;
179
180     # Make sure there's no previous installs or leftovers on DB
181     Koha::Plugins::Methods->delete;
182     $schema->resultset('PluginData')->delete;
183
184     my $plugin = Koha::Plugin::Test->new({ enable_plugins => 1, cgi => CGI->new });
185     ok( $plugin->is_enabled, 'Plugins enabled by default' );
186
187     # disable
188     $plugin->disable;
189     ok( !$plugin->is_enabled, 'Calling ->disable disables the plugin' );
190
191     # enable
192     $plugin->enable;
193     ok( $plugin->is_enabled, 'Calling ->enable enabled the plugin' );
194
195     $schema->storage->txn_rollback;
196 };
197
198 $schema->storage->txn_begin;
199 Koha::Plugins::Methods->delete;
200
201 warning_is { Koha::Plugins->new( { enable_plugins => 1 } )->InstallPlugins(); } undef;
202
203 ok( Koha::Plugins::Methods->search( { plugin_class => 'Koha::Plugin::Test' } )->count, 'Test plugin methods added to database' );
204 is( Koha::Plugins::Methods->search({ plugin_class => 'Koha::Plugin::Test', plugin_method => '_private_sub' })->count, 0, 'Private methods are skipped' );
205
206 my $mock_plugin = Test::MockModule->new( 'Koha::Plugin::Test' );
207 $mock_plugin->mock( 'test_template', sub {
208     my ( $self, $file ) = @_;
209     my $template = $self->get_template({ file => $file });
210     $template->param( filename => $file );
211     return $template->output;
212 });
213
214 ok( can_load( modules => { "Koha::Plugin::Test" => undef } ), 'Test can_load' );
215
216 my $plugin = Koha::Plugin::Test->new({ enable_plugins => 1, cgi => CGI->new });
217
218 isa_ok( $plugin, "Koha::Plugin::Test", 'Test plugin class' );
219 isa_ok( $plugin, "Koha::Plugins::Base", 'Test plugin parent class' );
220
221 ok( $plugin->can('report'), 'Test plugin can report' );
222 ok( $plugin->can('tool'), 'Test plugin can tool' );
223 ok( $plugin->can('to_marc'), 'Test plugin can to_marc' );
224 ok( $plugin->can('intranet_catalog_biblio_enhancements'), 'Test plugin can intranet_catalog_biblio_enhancements');
225 ok( $plugin->can('intranet_catalog_biblio_enhancements_toolbar_button'), 'Test plugin can intranet_catalog_biblio_enhancements_toolbar_button' );
226 ok( $plugin->can('opac_online_payment'), 'Test plugin can opac_online_payment' );
227 ok( $plugin->can('after_hold_create'), 'Test plugin can after_hold_create' );
228 ok( $plugin->can('opac_online_payment_begin'), 'Test plugin can opac_online_payment_begin' );
229 ok( $plugin->can('opac_online_payment_end'), 'Test plugin can opac_online_payment_end' );
230 ok( $plugin->can('opac_head'), 'Test plugin can opac_head' );
231 ok( $plugin->can('opac_js'), 'Test plugin can opac_js' );
232 ok( $plugin->can('intranet_head'), 'Test plugin can intranet_head' );
233 ok( $plugin->can('intranet_js'), 'Test plugin can intranet_js' );
234 ok( $plugin->can('item_barcode_transform'), 'Test plugin can barcode_transform' );
235 ok( $plugin->can('configure'), 'Test plugin can configure' );
236 ok( $plugin->can('install'), 'Test plugin can install' );
237 ok( $plugin->can('upgrade'), 'Test plugin can upgrade' );
238 ok( $plugin->can('uninstall'), 'Test plugin can install' );
239
240 is( Koha::Plugins::Handler->run({ class => "Koha::Plugin::Test", method => 'report', enable_plugins => 1 }), "Koha::Plugin::Test::report", 'Test run plugin report method' );
241
242 my $metadata = $plugin->get_metadata();
243 is( $metadata->{'name'}, 'Test Plugin', 'Test $plugin->get_metadata()' );
244
245 is( $plugin->get_qualified_table_name('mytable'), 'koha_plugin_test_mytable', 'Test $plugin->get_qualified_table_name()' );
246 is( $plugin->get_plugin_http_path(), '/plugin/Koha/Plugin/Test', 'Test $plugin->get_plugin_http_path()' );
247
248 # test absolute path change in get_template with Koha::Plugin::Test
249 # using the mock set before
250 # we also add tmpdir as an approved template dir
251 t::lib::Mocks::mock_config( 'pluginsdir', [ C4::Context->temporary_directory ] );
252 my ( $fh, $fn ) = tempfile( SUFFIX => '.tt', UNLINK => 1, DIR => C4::Context->temporary_directory );
253 print $fh 'I am [% filename %]';
254 close $fh;
255 my $classname = ref($plugin);
256 like( $plugin->test_template($fn), qr/^I am $fn/, 'Template works' );
257
258 my $result = $plugin->enable;
259 is( ref($result), 'Koha::Plugin::Test' );
260
261 # testing GetPlugins
262 my @plugins = Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins({
263     method => 'report'
264 });
265
266 my @names = map { $_->get_metadata()->{'name'} } @plugins;
267 is( scalar grep( /^Test Plugin$/, @names), 1, "Koha::Plugins::GetPlugins functions correctly" );
268 @plugins =  Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins({
269     metadata => { my_example_tag  => 'find_me' },
270 });
271
272 @names = map { $_->get_metadata()->{'name'} } @plugins;
273 is( scalar grep( /^Test Plugin$/, @names), 1, "GetPlugins also found Test Plugin via a metadata tag" );
274
275 $result = $plugin->disable;
276 is( ref($result), 'Koha::Plugin::Test' );
277
278 @plugins = Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins();
279 @names = map { $_->get_metadata()->{'name'} } @plugins;
280 is( scalar grep( /^Test Plugin$/, @names), 0, "GetPlugins does not found disabled Test Plugin" );
281
282 @plugins = Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins({ all => 1 });
283 @names = map { $_->get_metadata()->{'name'} } @plugins;
284 is( scalar grep( /^Test Plugin$/, @names), 1, "With all param, GetPlugins found disabled Test Plugin" );
285
286 for my $pass ( 1 .. 2 ) {
287     my $plugins_dir;
288     my $module_name = 'Koha::Plugin::Com::ByWaterSolutions::KitchenSink';
289     my $pm_path = 'Koha/Plugin/Com/ByWaterSolutions/KitchenSink.pm';
290     if ( $pass == 1 ) {
291         my $plugins_dir1 = tempdir( CLEANUP => 1 );
292         t::lib::Mocks::mock_config('pluginsdir', $plugins_dir1);
293         $plugins_dir = $plugins_dir1;
294         push @INC, $plugins_dir1;
295     } else {
296         my $plugins_dir1 = tempdir( CLEANUP => 1 );
297         my $plugins_dir2 = tempdir( CLEANUP => 1 );
298         t::lib::Mocks::mock_config('pluginsdir', [ $plugins_dir2, $plugins_dir1 ]);
299         $plugins_dir = $plugins_dir2;
300         pop @INC;
301         push @INC, $plugins_dir2;
302         push @INC, $plugins_dir1;
303     }
304     my $full_pm_path = $plugins_dir . '/' . $pm_path;
305
306     my $ae = Archive::Extract->new( archive => "$Bin/KitchenSinkPlugin.kpz", type => 'zip' );
307     unless ( $ae->extract( to => $plugins_dir ) ) {
308         warn "ERROR: " . $ae->error;
309     }
310     use_ok('Koha::Plugin::Com::ByWaterSolutions::KitchenSink');
311     $plugin = Koha::Plugin::Com::ByWaterSolutions::KitchenSink->new({ enable_plugins => 1});
312     my $table = $plugin->get_qualified_table_name( 'mytable' );
313
314     ok( -f $plugins_dir . "/Koha/Plugin/Com/ByWaterSolutions/KitchenSink.pm", "KitchenSink plugin installed successfully" );
315     $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"
316     warning_is { Koha::Plugins->new( { enable_plugins => 1 } )->InstallPlugins(); } undef;
317     ok( -f $full_pm_path, "Koha::Plugins::Handler::delete works correctly (pass $pass)" );
318     Koha::Plugins::Handler->delete({ class => "Koha::Plugin::Com::ByWaterSolutions::KitchenSink", enable_plugins => 1 });
319     my $sth = C4::Context->dbh->table_info( undef, undef, $table, 'TABLE' );
320     my $info = $sth->fetchall_arrayref;
321     is( @$info, 0, "Table $table does no longer exist" );
322     ok( !( -f $full_pm_path ), "Koha::Plugins::Handler::delete works correctly (pass $pass)" );
323 }
324
325 subtest 'output and output_html tests' => sub {
326
327     plan tests => 6;
328
329     # Trick stdout to be able to test
330     local *STDOUT;
331     my $stdout;
332     open STDOUT, '>', \$stdout;
333
334     my $plugin = Koha::Plugin::Test->new({ enable_plugins => 1, cgi => CGI->new });
335     $plugin->test_output;
336
337     like($stdout, qr/Cache-control: no-cache/, 'force_no_caching sets Cache-control as desired');
338     like($stdout, qr{Content-Type: application/json; charset=UTF-8}, 'Correct content-type');
339     like($stdout, qr{¡Hola output!}, 'Correct data');
340
341     # reset the stdout buffer
342     $stdout = '';
343     close STDOUT;
344     open STDOUT, '>', \$stdout;
345
346     $plugin->test_output_html;
347
348     like($stdout, qr/Cache-control: no-cache/, 'force_no_caching sets Cache-control as desired');
349     like($stdout, qr{Content-Type: text/html; charset=UTF-8}, 'Correct content-type');
350     like($stdout, qr{¡Hola output_html!}, 'Correct data');
351 };
352
353 subtest 'Test _version_compare' => sub {
354
355     plan tests => 12;
356
357     t::lib::Mocks::mock_config( 'enable_plugins', 1 );
358
359     is( Koha::Plugins::Base::_version_compare( '1.1.1',    '2.2.2' ), -1, "1.1.1 is less then 2.2.2" );
360     is( Koha::Plugins::Base::_version_compare( '2.2.2',    '1.1.1' ),  1, "1.1.1 is greater then 2.2.2" );
361     is( Koha::Plugins::Base::_version_compare( '1.1.1',    '1.1.1' ),  0, "1.1.1 is equal to 1.1.1" );
362     is( Koha::Plugins::Base::_version_compare( '1.01.001', '1.1.1' ),  0, "1.01.001 is equal to 1.1.1" );
363     is( Koha::Plugins::Base::_version_compare( '1',        '1.0.0' ),  0, "1 is equal to 1.0.0" );
364     is( Koha::Plugins::Base::_version_compare( '1.0',      '1.0.0' ),  0, "1.0 is equal to 1.0.0" );
365
366     # OO tests
367     my $plugin = Koha::Plugin::Test->new;
368     is( $plugin->_version_compare( '1.1.1',    '2.2.2' ), -1, "1.1.1 is less then 2.2.2" );
369     is( $plugin->_version_compare( '2.2.2',    '1.1.1' ),  1, "1.1.1 is greater then 2.2.2" );
370     is( $plugin->_version_compare( '1.1.1',    '1.1.1' ),  0, "1.1.1 is equal to 1.1.1" );
371     is( $plugin->_version_compare( '1.01.001', '1.1.1' ),  0, "1.01.001 is equal to 1.1.1" );
372     is( $plugin->_version_compare( '1',        '1.0.0' ),  0, "1 is equal to 1.0.0" );
373     is( $plugin->_version_compare( '1.0',      '1.0.0' ),  0, "1.0 is equal to 1.0.0" );
374 };
375
376 subtest 'bundle_path() tests' => sub {
377
378     plan tests => 1;
379
380     t::lib::Mocks::mock_config( 'enable_plugins', 1 );
381
382     my @current_dir = File::Spec->splitdir(abs_path(__FILE__));
383     # remote Plugins.t
384     pop @current_dir;
385     # remove /Plugins
386     pop @current_dir;
387     # remove /Koha
388     pop @current_dir;
389     # remove db_dependent
390     pop @current_dir;
391
392     my $plugin = Koha::Plugin::Test->new;
393
394     is( $plugin->bundle_path, File::Spec->catdir(@current_dir) . '/lib/plugins/Koha/Plugin/Test' );
395
396 };
397
398 subtest 'new() tests' => sub {
399
400     plan tests => 2;
401
402     t::lib::Mocks::mock_config( 'pluginsdir', [ C4::Context->temporary_directory ] );
403     t::lib::Mocks::mock_config( 'enable_plugins', 0 );
404
405     my $result = Koha::Plugins->new();
406     is( $result, undef, 'calling new() on disabled plugins returns undef' );
407
408     $result = Koha::Plugins->new({ enable_plugins => 1 });
409     is( ref($result), 'Koha::Plugins', 'calling new with enable_plugins makes it override the config' );
410 };
411
412 Koha::Plugins::Methods->delete;