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