Bug 33584: Fix failures for Commenter.t on MySQL8
[koha.git] / t / db_dependent / Koha / BackgroundJob.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
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use utf8;
20 use Encode;
21
22 use Test::More tests => 5;
23 use Test::MockModule;
24 use Test::Exception;
25
26 use Koha::Database;
27 use Koha::BackgroundJobs;
28 use Koha::BackgroundJob::BatchUpdateItem;
29
30 use t::lib::Mocks;
31 use t::lib::Mocks::Logger;
32 use t::lib::TestBuilder;
33 use t::lib::Koha::BackgroundJob::BatchTest;
34
35 my $logger  = t::lib::Mocks::Logger->new;
36 my $schema  = Koha::Database->new->schema;
37 my $builder = t::lib::TestBuilder->new;
38
39 subtest '_derived_class() tests' => sub {
40
41     plan tests => 3;
42
43     $schema->storage->txn_begin;
44
45     my $job_object = Koha::BackgroundJob->new();
46     my $mapping = $job_object->type_to_class_mapping;
47
48     # pick the first
49     my $type = ( keys %{$mapping} )[0];
50
51     my $job = $builder->build_object(
52         {   class => 'Koha::BackgroundJobs',
53             value => { type => $type, data => 'Foo' }
54         }
55     );
56
57     my $derived = $job->_derived_class;
58
59     is( ref($derived), $mapping->{$type}, 'Job object class is correct' );
60     ok( $derived->in_storage, 'The object is correctly marked as in storage' );
61
62     $derived->data('Bar')->store->discard_changes;
63     $job->discard_changes;
64
65     is_deeply( $job->unblessed, $derived->unblessed, '_derived_class object refers to the same DB object and can be manipulated as expected' );
66
67     $schema->storage->txn_rollback;
68 };
69
70 subtest 'enqueue() tests' => sub {
71
72     plan tests => 8;
73
74     $schema->storage->txn_begin;
75
76     # FIXME: This all feels we need to do it better...
77     my $job_id = Koha::BackgroundJob::BatchUpdateItem->new->enqueue( { record_ids => [ 1, 2 ] } );
78     my $job    = Koha::BackgroundJobs->find($job_id)->_derived_class;
79
80     is( $job->size,           2,     'Two steps' );
81     is( $job->status,         'new', 'Initial status set correctly' );
82     is( $job->borrowernumber, undef, 'No userenv, borrowernumber undef' );
83
84     my $interface = C4::Context->interface;
85     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
86     t::lib::Mocks::mock_userenv( { patron => $patron } );
87     my $job_context = {
88         number        => $patron->borrowernumber,
89         id            => $patron->userid,
90         cardnumber    => $patron->cardnumber,
91         firstname     => $patron->firstname,
92         surname       => $patron->surname,
93         branch        => $patron->library->branchcode,
94         branchname    => $patron->library->branchname,
95         flags         => $patron->flags,
96         emailaddress  => $patron->email,
97         register_id   => undef,
98         register_name => undef,
99         shibboleth    => undef,
100         desk_id       => undef,
101         desk_name     => undef,
102         interface     => $interface
103     };
104
105     $job_id = Koha::BackgroundJob::BatchUpdateItem->new->enqueue( { record_ids => [ 1, 2, 3 ] } );
106     $job    = Koha::BackgroundJobs->find($job_id)->_derived_class;
107
108     is( $job->size,           3,           'Three steps' );
109     is( $job->status,         'new',       'Initial status set correctly' );
110     is( $job->borrowernumber, $patron->id, 'Borrowernumber set from userenv' );
111     is( $job->queue,          'long_tasks', 'BatchUpdateItem should use the long_tasks queue' );
112     is_deeply( $job->json->decode( $job->context ), $job_context, 'Context set from userenv + interface' );
113
114     $schema->storage->txn_rollback;
115 };
116
117 subtest 'start(), step() and finish() tests' => sub {
118
119     plan tests => 19;
120
121     $schema->storage->txn_begin;
122
123     # FIXME: This all feels we need to do it better...
124     my $job_id = Koha::BackgroundJob::BatchUpdateItem->new->enqueue( { record_ids => [ 1, 2 ] } );
125     my $job    = Koha::BackgroundJobs->find($job_id)->_derived_class;
126
127     is( $job->started_on, undef, 'started_on not set yet' );
128     is( $job->size, 2, 'Two steps' );
129
130     $job->start;
131
132     isnt( $job->started_on, undef, 'started_on set' );
133     is( $job->status, 'started' );
134     is( $job->progress, 0, 'No progress yet' );
135
136     $job->step;
137     is( $job->progress, 1, 'First step' );
138     $job->step;
139     is( $job->progress, 2, 'Second step' );
140     throws_ok
141         { $job->step; }
142         'Koha::Exceptions::BackgroundJob::StepOutOfBounds',
143         'Tried to make a forbidden extra step';
144
145     is( $job->progress, 2, 'progress remains unchanged' );
146
147     my $data = { some => 'data' };
148
149     $job->status('cancelled')->store;
150     $job->finish( $data );
151
152     is( $job->status, 'cancelled', "'finish' leaves 'cancelled' untouched" );
153     isnt( $job->ended_on, undef, 'ended_on set' );
154     is_deeply( $job->json->decode( $job->data ), $data );
155
156     $job->status('started')->store;
157     $job->finish( $data );
158
159     is( $job->status, 'finished' );
160     isnt( $job->ended_on, undef, 'ended_on set' );
161     is_deeply( $job->json->decode( $job->data ), $data );
162
163     throws_ok
164         { $job->start; }
165         'Koha::Exceptions::BackgroundJob::InconsistentStatus',
166         'Exception thrown trying to start a finished job';
167
168     is( $@->expected_status, 'new' );
169
170     throws_ok
171         { $job->step; }
172         'Koha::Exceptions::BackgroundJob::InconsistentStatus',
173         'Exception thrown trying to start a finished job';
174
175     is( $@->expected_status, 'started' );
176
177     $schema->storage->txn_rollback;
178 };
179
180 subtest 'process tests' => sub {
181
182     plan tests => 5;
183
184     $schema->storage->txn_begin;
185
186     C4::Context->interface('intranet');
187     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
188     t::lib::Mocks::mock_userenv( { patron => $patron } );
189     my $job_context = {
190         number        => $patron->borrowernumber,
191         id            => $patron->userid,
192         cardnumber    => $patron->cardnumber,
193         firstname     => $patron->firstname,
194         surname       => $patron->surname,
195         branch        => $patron->library->branchcode,
196         branchname    => $patron->library->branchname,
197         flags         => $patron->flags,
198         emailaddress  => $patron->email,
199         register_id   => undef,
200         register_name => undef,
201         shibboleth    => undef,
202         desk_id       => undef,
203         desk_name     => undef,
204     };
205
206     my $background_job_module = Test::MockModule->new('Koha::BackgroundJob');
207     $background_job_module->mock(
208         'type_to_class_mapping',
209         sub {
210             return { batch_test => 't::lib::Koha::BackgroundJob::BatchTest' };
211         }
212     );
213
214     my $job_id = t::lib::Koha::BackgroundJob::BatchTest->new->enqueue(
215         { size => 10, a => 'aaa', b => 'bbb' } );
216     my $job    = Koha::BackgroundJobs->find($job_id);
217
218     C4::Context->_new_userenv(-1);
219     C4::Context->interface('opac');
220     is( C4::Context->userenv, undef, "Userenv unset prior to calling process");
221     is( C4::Context->interface, 'opac', "Interface set to opac prior to calling process");
222
223     $job->process();
224     is_deeply( C4::Context->userenv, $job_context, "Userenv set from job context on process" );
225     is_deeply( C4::Context->interface, 'intranet', "Interface set from job context on process" );
226
227     # Manually add a job (->new->store) without context
228     my $json = $job->json; # sorry, quickly borrowing your json object
229     my $data = $json->encode({ a => 'a', b => 'b' });
230     my $incomplete_job = t::lib::Koha::BackgroundJob::BatchTest->new(
231         {   status         => 'new',
232             size           => 1,
233             borrowernumber => $patron->borrowernumber,
234             type           => 'batch_test',
235             data           => $data,
236         }
237     )->store;
238
239     $incomplete_job = Koha::BackgroundJobs->find( $incomplete_job->id );
240     $incomplete_job->process();
241     $logger->warn_is( "A background job didn't have context defined (" . $incomplete_job->id . ")" );
242
243     $schema->storage->txn_rollback;
244 };
245
246 subtest 'decoded_data() and set_encoded_data() tests' => sub {
247
248     plan tests => 8;
249     $schema->storage->txn_begin;
250
251     my $job = Koha::BackgroundJob::BatchUpdateItem->new->set_encoded_data( undef );
252     is( $job->decoded_data, undef, 'undef is undef' );
253
254     my $data = { some => 'data' };
255
256     $job->set_encoded_data( $data );
257
258     is_deeply( $job->json->decode($job->data), $data, 'decode what we sent' );
259     is_deeply( $job->decoded_data, $data, 'check with decoded_data' );
260
261     # Let's get some Unicode stuff into the game
262     $data = { favorite_Chinese => [ '葑', '癱' ], latin_dancing => [ '¢', '¥', 'á', 'û' ] };
263     $job->set_encoded_data( $data )->store;
264
265     $job->discard_changes; # refresh
266     is_deeply( $job->decoded_data, $data, 'Deep compare with Unicode data' );
267     # To convince you even more
268     is( ord( $job->decoded_data->{favorite_Chinese}->[0] ), 33873, 'We still found Unicode \x8451' );
269     is( ord( $job->decoded_data->{latin_dancing}->[0] ), 162, 'We still found the equivalent of Unicode \x00A2' );
270
271     # Testing with sending encoded data (which we normally shouldn't do)
272     my $utf8_data;
273     foreach my $k ( 'favorite_Chinese', 'latin_dancing' ) {
274         foreach my $c ( @{$data->{$k}} ) {
275             push @{$utf8_data->{$k}}, Encode::encode('UTF-8', $c);
276         }
277     }
278     $job->set_encoded_data( $utf8_data )->store;
279     $job->discard_changes; # refresh
280     is_deeply( $job->decoded_data, $utf8_data, 'Deep compare with utf8_data' );
281     # Need more evidence?
282     is( ord( $job->decoded_data->{favorite_Chinese}->[0] ), 232, 'We still found a UTF8 encoded byte' ); # ord does not need substr here
283
284     $schema->storage->txn_rollback;
285 };