Bug 27993: Add unit tests
[koha.git] / t / db_dependent / Illrequests.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
20 use File::Basename qw/basename/;
21
22 use C4::Circulation qw(AddIssue AddReturn);
23
24 use Koha::Database;
25 use Koha::Illrequestattributes;
26 use Koha::Illrequest::Config;
27 use Koha::Biblios;
28 use Koha::Patrons;
29 use Koha::ItemTypes;
30 use Koha::Items;
31 use Koha::Libraries;
32 use Koha::MessageAttributes;
33 use Koha::Notice::Templates;
34 use Koha::AuthorisedValueCategories;
35 use Koha::AuthorisedValues;
36 use t::lib::Mocks;
37 use t::lib::TestBuilder;
38 use Test::MockObject;
39 use Test::MockModule;
40 use Test::Exception;
41 use Test::Deep qw/ cmp_deeply ignore /;
42 use Test::Warn;
43
44 use Test::More tests => 13;
45
46 my $schema = Koha::Database->new->schema;
47 my $builder = t::lib::TestBuilder->new;
48 use_ok('Koha::Illrequest');
49 use_ok('Koha::Illrequests');
50
51 subtest 'Basic object tests' => sub {
52
53     plan tests => 24;
54
55     $schema->storage->txn_begin;
56
57     Koha::Illrequests->search->delete;
58     my $illrq = $builder->build({ source => 'Illrequest' });
59     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
60
61     isa_ok($illrq_obj, 'Koha::Illrequest',
62            "Correctly create and load an illrequest object.");
63     isa_ok($illrq_obj->_config, 'Koha::Illrequest::Config',
64            "Created a config object as part of Illrequest creation.");
65
66     is($illrq_obj->illrequest_id, $illrq->{illrequest_id},
67        "Illrequest_id getter works.");
68     is($illrq_obj->borrowernumber, $illrq->{borrowernumber},
69        "Borrowernumber getter works.");
70     is($illrq_obj->biblio_id, $illrq->{biblio_id},
71        "Biblio_Id getter works.");
72     is($illrq_obj->branchcode, $illrq->{branchcode},
73        "Branchcode getter works.");
74     is($illrq_obj->status, $illrq->{status},
75        "Status getter works.");
76     is($illrq_obj->placed, $illrq->{placed},
77        "Placed getter works.");
78     is($illrq_obj->replied, $illrq->{replied},
79        "Replied getter works.");
80     is($illrq_obj->updated, $illrq->{updated},
81        "Updated getter works.");
82     is($illrq_obj->completed, $illrq->{completed},
83        "Completed getter works.");
84     is($illrq_obj->medium, $illrq->{medium},
85        "Medium getter works.");
86     is($illrq_obj->accessurl, $illrq->{accessurl},
87        "Accessurl getter works.");
88     is($illrq_obj->cost, $illrq->{cost},
89        "Cost getter works.");
90     is($illrq_obj->price_paid, $illrq->{price_paid},
91        "Price_paid getter works.");
92     is($illrq_obj->notesopac, $illrq->{notesopac},
93        "Notesopac getter works.");
94     is($illrq_obj->notesstaff, $illrq->{notesstaff},
95        "Notesstaff getter works.");
96     is($illrq_obj->orderid, $illrq->{orderid},
97        "Orderid getter works.");
98     is($illrq_obj->backend, $illrq->{backend},
99        "Backend getter works.");
100
101     is($illrq_obj->get_type, undef,
102         'get_type() returns undef if no type is set');
103     $builder->build({
104         source => 'Illrequestattribute',
105         value  => {
106             illrequest_id => $illrq_obj->illrequest_id,
107             type => 'type',
108             value => 'book'
109         }
110     });
111     is($illrq_obj->get_type, 'book',
112         'get_type() returns correct type if set');
113
114     isnt($illrq_obj->status, 'COMP',
115          "ILL is not currently marked complete.");
116     $illrq_obj->mark_completed;
117     is($illrq_obj->status, 'COMP',
118        "ILL is now marked complete.");
119
120     $illrq_obj->delete;
121
122     is(Koha::Illrequests->search->count, 0,
123        "No illrequest found after delete.");
124
125     $schema->storage->txn_rollback;
126 };
127
128 subtest 'Working with related objects' => sub {
129
130     plan tests => 7;
131
132     $schema->storage->txn_begin;
133
134     Koha::Illrequests->search->delete;
135
136     my $patron = $builder->build({ source => 'Borrower' });
137     my $illrq = $builder->build({
138         source => 'Illrequest',
139         value => { borrowernumber => $patron->{borrowernumber} }
140     });
141     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
142
143     isa_ok($illrq_obj->patron, 'Koha::Patron',
144            "OK accessing related patron.");
145
146     $builder->build({
147         source => 'Illrequestattribute',
148         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'X' }
149     });
150     $builder->build({
151         source => 'Illrequestattribute',
152         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'Y' }
153     });
154     $builder->build({
155         source => 'Illrequestattribute',
156         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'Z' }
157     });
158
159     is($illrq_obj->illrequestattributes->count, Koha::Illrequestattributes->search->count,
160        "Fetching expected number of Illrequestattributes for our request.");
161
162     my $illrq1 = $builder->build({ source => 'Illrequest' });
163     $builder->build({
164         source => 'Illrequestattribute',
165         value  => { illrequest_id => $illrq1->{illrequest_id}, type => 'X' }
166     });
167
168     is($illrq_obj->illrequestattributes->count + 1, Koha::Illrequestattributes->search->count,
169        "Fetching expected number of Illrequestattributes for our request.");
170
171     is($illrq_obj->biblio, undef, "->biblio returns undef if no biblio");
172     my $biblio = $builder->build_object({ class => 'Koha::Biblios' });
173     my $req_bib = $builder->build_object({
174         class => 'Koha::Illrequests',
175         value => {
176             biblio_id      => $biblio->biblionumber
177         }
178     });
179     isa_ok($req_bib->biblio, 'Koha::Biblio', "OK accessing related biblio");
180
181     $illrq_obj->delete;
182     is(Koha::Illrequestattributes->search->count, 1,
183        "Correct number of illrequestattributes after delete.");
184
185     isa_ok(Koha::Patrons->find($patron->{borrowernumber}), 'Koha::Patron',
186            "Borrower was not deleted after illrq delete.");
187
188     $schema->storage->txn_rollback;
189 };
190
191 subtest 'Status Graph tests' => sub {
192
193     plan tests => 5;
194
195     $schema->storage->txn_begin;
196
197     my $illrq = $builder->build({source => 'Illrequest'});
198     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
199
200     # _core_status_graph tests: it's just a constant, so here we just make
201     # sure it returns a hashref.
202     is(ref $illrq_obj->_core_status_graph, "HASH",
203        "_core_status_graph returns a hash.");
204
205     # _status_graph_union: let's try different merge operations.
206     # Identity operation
207     is_deeply(
208         $illrq_obj->_status_graph_union($illrq_obj->_core_status_graph, {}),
209         $illrq_obj->_core_status_graph,
210         "core_status_graph + null = core_status_graph"
211     );
212
213     # Simple addition
214     is_deeply(
215         $illrq_obj->_status_graph_union({}, $illrq_obj->_core_status_graph),
216         $illrq_obj->_core_status_graph,
217         "null + core_status_graph = core_status_graph"
218     );
219
220     # Correct merge behaviour
221     is_deeply(
222         $illrq_obj->_status_graph_union({
223             REQ => {
224                 prev_actions   => [ ],
225                 id             => 'REQ',
226                 next_actions   => [ ],
227             },
228         }, {
229             QER => {
230                 prev_actions   => [ 'REQ' ],
231                 id             => 'QER',
232                 next_actions   => [ 'REQ' ],
233             },
234         }),
235         {
236             REQ => {
237                 prev_actions   => [ 'QER' ],
238                 id             => 'REQ',
239                 next_actions   => [ 'QER' ],
240             },
241             QER => {
242                 prev_actions   => [ 'REQ' ],
243                 id             => 'QER',
244                 next_actions   => [ 'REQ' ],
245             },
246         },
247         "REQ atom + linking QER = cyclical status graph"
248     );
249
250     # Create a new node, with no prev_actions and no next_actions. This should
251     # protect us against regressions related to bug 22280.
252     my $new_node = {
253         TEST => {
254             prev_actions   => [ ],
255             id             => 'TEST',
256             next_actions   => [ ],
257         },
258     };
259     # Add the new node to the core_status_grpah
260     my $new_graph = $illrq_obj->_status_graph_union( $new_node, $illrq_obj->_core_status_graph);
261     # Compare the updated graph to the expected graph
262     # The structure we compare against here is just a copy of the structure found
263     # in Koha::Illrequest::_core_status_graph() + the new node we created above
264     cmp_deeply( $new_graph,
265         {
266         TEST => {
267             prev_actions   => [ ],
268             id             => 'TEST',
269             next_actions   => [ ],
270         },
271         NEW => {
272             prev_actions => [ ],                           # Actions containing buttons
273                                                            # leading to this status
274             id             => 'NEW',                       # ID of this status
275             name           => 'New request',               # UI name of this status
276             ui_method_name => 'New request',               # UI name of method leading
277                                                            # to this status
278             method         => 'create',                    # method to this status
279             next_actions   => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all
280                                                            # requests with this status
281             ui_method_icon => 'fa-plus',                   # UI Style class
282         },
283         REQ => {
284             prev_actions   => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ],
285             id             => 'REQ',
286             name           => 'Requested',
287             ui_method_name => 'Confirm request',
288             method         => 'confirm',
289             next_actions   => [ 'REQREV', 'COMP', 'CHK' ],
290             ui_method_icon => 'fa-check',
291         },
292         GENREQ => {
293             prev_actions   => [ 'NEW', 'REQREV' ],
294             id             => 'GENREQ',
295             name           => 'Requested from partners',
296             ui_method_name => 'Place request with partners',
297             method         => 'generic_confirm',
298             next_actions   => [ 'COMP', 'CHK' ],
299             ui_method_icon => 'fa-send-o',
300         },
301         REQREV => {
302             prev_actions   => [ 'REQ' ],
303             id             => 'REQREV',
304             name           => 'Request reverted',
305             ui_method_name => 'Revert Request',
306             method         => 'cancel',
307             next_actions   => [ 'REQ', 'GENREQ', 'KILL' ],
308             ui_method_icon => 'fa-times',
309         },
310         QUEUED => {
311             prev_actions   => [ ],
312             id             => 'QUEUED',
313             name           => 'Queued request',
314             ui_method_name => 0,
315             method         => 0,
316             next_actions   => [ 'REQ', 'KILL' ],
317             ui_method_icon => 0,
318         },
319         CANCREQ => {
320             prev_actions   => [ 'NEW' ],
321             id             => 'CANCREQ',
322             name           => 'Cancellation requested',
323             ui_method_name => 0,
324             method         => 0,
325             next_actions   => [ 'KILL', 'REQ' ],
326             ui_method_icon => 0,
327         },
328         COMP => {
329             prev_actions   => [ 'REQ' ],
330             id             => 'COMP',
331             name           => 'Completed',
332             ui_method_name => 'Mark completed',
333             method         => 'mark_completed',
334             next_actions   => [ 'CHK' ],
335             ui_method_icon => 'fa-check',
336         },
337         KILL => {
338             prev_actions   => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ],
339             id             => 'KILL',
340             name           => 0,
341             ui_method_name => 'Delete request',
342             method         => 'delete',
343             next_actions   => [ ],
344             ui_method_icon => 'fa-trash',
345         },
346         CHK => {
347             prev_actions   => [ 'REQ', 'GENREQ', 'COMP' ],
348             id             => 'CHK',
349             name           => 'Checked out',
350             ui_method_name => 'Check out',
351             needs_prefs    => [ 'CirculateILL' ],
352             needs_perms    => [ 'user_circulate_circulate_remaining_permissions' ],
353             needs_all      => ignore(),
354             method         => 'check_out',
355             next_actions   => [ ],
356             ui_method_icon => 'fa-upload',
357         },
358         RET => {
359             prev_actions   => [ 'CHK' ],
360             id             => 'RET',
361             name           => 'Returned to library',
362             ui_method_name => 'Check in',
363             method         => 'check_in',
364             next_actions   => [ 'COMP' ],
365             ui_method_icon => 'fa-download',
366         }
367     },
368         "new node + core_status_graph = bigger status graph"
369     ) || diag explain $new_graph;
370
371     $schema->storage->txn_rollback;
372 };
373
374 subtest 'Backend testing (mocks)' => sub {
375
376     plan tests => 13;
377
378     $schema->storage->txn_begin;
379
380     # testing load_backend & available_backends requires that we have at least
381     # the Dummy plugin installed.  load_backend & available_backends don't
382     # currently have tests as a result.
383
384     t::lib::Mocks->mock_config('interlibrary_loans', { backend_dir => 'a_dir' }  );
385     my $backend = Test::MockObject->new;
386     $backend->set_isa('Koha::Illbackends::Mock');
387     $backend->set_always('name', 'Mock');
388
389     my $patron = $builder->build({ source => 'Borrower' });
390     my $illrq = $builder->build_object({
391         class => 'Koha::Illrequests',
392     });
393
394     $illrq->_backend($backend);
395
396     isa_ok($illrq->_backend, 'Koha::Illbackends::Mock',
397            "OK accessing mocked backend.");
398
399     # _backend_capability tests:
400     # We need to test whether this optional feature of a mocked backend
401     # behaves as expected.
402     # 3 scenarios: feature not implemented, feature implemented, but requested
403     # capability is not provided by backend, & feature is implemented &
404     # capability exists.  This method can be used to implement custom backend
405     # functionality, such as unmediated in the BLDSS backend (also see
406     # bugzilla 18837).
407     $backend->set_always('capabilities', undef);
408     is($illrq->_backend_capability('Test'), 0,
409        "0 returned on Mock not implementing capabilities.");
410
411     $backend->set_always('capabilities', 0);
412     is($illrq->_backend_capability('Test'), 0,
413        "0 returned on Mock not implementing Test capability.");
414
415     $backend->set_always('capabilities', sub { return 'bar'; } );
416     is($illrq->_backend_capability('Test'), 'bar',
417        "'bar' returned on Mock implementing Test capability.");
418
419     # metadata test: we need to be sure that we return the arbitrary values
420     # from the backend.
421     $backend->mock(
422         'metadata',
423         sub {
424             my ( $self, $rq ) = @_;
425             return {
426                 ID => $rq->illrequest_id,
427                 Title => $rq->patron->borrowernumber
428             }
429         }
430     );
431
432     is_deeply(
433         $illrq->metadata,
434         {
435             ID => $illrq->illrequest_id,
436             Title => $illrq->patron->borrowernumber
437         },
438         "Test metadata."
439     );
440
441     # capabilities:
442
443     # No backend graph extension
444     $backend->set_always('status_graph', {});
445     is_deeply($illrq->capabilities('COMP'),
446               {
447                   prev_actions   => [ 'REQ' ],
448                   id             => 'COMP',
449                   name           => 'Completed',
450                   ui_method_name => 'Mark completed',
451                   method         => 'mark_completed',
452                   next_actions   => [ 'CHK' ],
453                   ui_method_icon => 'fa-check',
454               },
455               "Dummy status graph for COMP.");
456     is($illrq->capabilities('UNKNOWN'), undef,
457        "Dummy status graph for UNKNOWN.");
458     is_deeply($illrq->capabilities(),
459               $illrq->_core_status_graph,
460               "Dummy full status graph.");
461     # Simple backend graph extension
462     $backend->set_always('status_graph',
463                          {
464                              QER => {
465                                  prev_actions   => [ 'REQ' ],
466                                  id             => 'QER',
467                                  next_actions   => [ 'REQ' ],
468                              },
469                          });
470     is_deeply($illrq->capabilities('QER'),
471               {
472                   prev_actions   => [ 'REQ' ],
473                   id             => 'QER',
474                   next_actions   => [ 'REQ' ],
475               },
476               "Simple status graph for QER.");
477     is($illrq->capabilities('UNKNOWN'), undef,
478        "Simple status graph for UNKNOWN.");
479     is_deeply($illrq->capabilities(),
480               $illrq->_status_graph_union(
481                   $illrq->_core_status_graph,
482                   {
483                       QER => {
484                           prev_actions   => [ 'REQ' ],
485                           id             => 'QER',
486                           next_actions   => [ 'REQ' ],
487                       },
488                   }
489               ),
490               "Simple full status graph.");
491
492     # custom_capability:
493
494     # No backend graph extension
495     $backend->set_always('status_graph', {});
496     is($illrq->custom_capability('unknown', {}), 0,
497        "Unknown candidate.");
498
499     # Simple backend graph extension
500     $backend->set_always('status_graph',
501                          {
502                              ID => {
503                                  prev_actions   => [ 'REQ' ],
504                                  id             => 'ID',
505                                  method         => 'identity',
506                                  next_actions   => [ 'REQ' ],
507                              },
508                          });
509     $backend->mock('identity',
510                    sub { my ( $self, $params ) = @_; return $params->{other}; });
511     is($illrq->custom_capability('identity', { test => 1, method => 'blah' })->{test}, 1,
512        "Resolve identity custom_capability");
513
514     $schema->storage->txn_rollback;
515 };
516
517
518 subtest 'Backend core methods' => sub {
519
520     plan tests => 18;
521
522     $schema->storage->txn_begin;
523
524     # Build infrastructure
525     my $backend = Test::MockObject->new;
526     $backend->set_isa('Koha::Illbackends::Mock');
527     $backend->set_always('name', 'Mock');
528     $backend->mock('capabilities', sub { return 'Mock'; });
529
530     my $config = Test::MockObject->new;
531     $config->set_always('backend_dir', "/tmp");
532     $config->set_always('getLimitRules',
533                         { default => { count => 0, method => 'active' } });
534
535     my $illrq = $builder->build_object({
536         class => 'Koha::Illrequests',
537         value => { backend => undef }
538     });
539     $illrq->_config($config);
540
541     # Test error conditions (no backend)
542     throws_ok { $illrq->load_backend; }
543         'Koha::Exceptions::Ill::InvalidBackendId',
544         'Exception raised correctly';
545
546     throws_ok { $illrq->load_backend(''); }
547         'Koha::Exceptions::Ill::InvalidBackendId',
548         'Exception raised correctly';
549
550     # Now load the mocked backend
551     $illrq->_backend($backend);
552
553     # expandTemplate:
554     is_deeply($illrq->expandTemplate({ test => 1, method => "bar" }),
555               {
556                   test => 1,
557                   method => "bar",
558                   template => "/tmp/Mock/intra-includes/bar.inc",
559                   opac_template => "/tmp/Mock/opac-includes/bar.inc",
560               },
561               "ExpandTemplate");
562
563     # backend_create
564     # we are testing simple cases.
565     $backend->set_series('create',
566                          { stage => 'bar', method => 'create' },
567                          { stage => 'commit', method => 'create' },
568                          { stage => 'commit', method => 'create' },
569                          { stage => 'commit', method => 'create' },
570                          { stage => 'commit', method => 'create' });
571     # Test non-commit
572     is_deeply($illrq->backend_create({test => 1}),
573               {
574                   stage => 'bar', method => 'create',
575                   template => "/tmp/Mock/intra-includes/create.inc",
576                   opac_template => "/tmp/Mock/opac-includes/create.inc",
577               },
578               "Backend create: arbitrary stage.");
579     # Test commit
580     is_deeply($illrq->backend_create({test => 1}),
581               {
582                   stage => 'commit', method => 'create', permitted => 0,
583                   template => "/tmp/Mock/intra-includes/create.inc",
584                   opac_template => "/tmp/Mock/opac-includes/create.inc",
585               },
586               "Backend create: arbitrary stage, not permitted.");
587     is($illrq->status, "QUEUED", "Backend create: queued if restricted.");
588     $config->set_always('getLimitRules', {});
589     $illrq->status('NEW');
590     is_deeply($illrq->backend_create({test => 1}),
591               {
592                   stage => 'commit', method => 'create', permitted => 1,
593                   template => "/tmp/Mock/intra-includes/create.inc",
594                   opac_template => "/tmp/Mock/opac-includes/create.inc",
595               },
596               "Backend create: arbitrary stage, permitted.");
597     is($illrq->status, "NEW", "Backend create: not-queued.");
598
599     # Test that enabling the unmediated workflow causes the backend's
600     # 'unmediated_ill' method to be called
601     t::lib::Mocks::mock_preference('ILLModuleUnmediated', '1');
602     $backend->mock(
603         'capabilities',
604         sub {
605             my ($self, $name) = @_;
606             if ($name eq 'unmediated_ill') {
607                 return sub {
608                     return { unmediated_ill => 1 };
609                 };
610             }
611         }
612     );
613     $illrq->status('NEW');
614     is_deeply(
615         $illrq->backend_create({test => 1}),
616         {
617             'opac_template' => '/tmp/Mock/opac-includes/.inc',
618             'template' => '/tmp/Mock/intra-includes/.inc',
619             'unmediated_ill' => 1
620         },
621         "Backend create: commit stage, permitted, ILLModuleUnmediated enabled."
622     );
623
624     # Test that disabling the unmediated workflow causes the backend's
625     # 'unmediated_ill' method to be NOT called
626     t::lib::Mocks::mock_preference('ILLModuleUnmediated', '0');
627     $illrq->status('NEW');
628     is_deeply(
629         $illrq->backend_create({test => 1}),
630         {
631             stage => 'commit', method => 'create', permitted => 1,
632             template => "/tmp/Mock/intra-includes/create.inc",
633             opac_template => "/tmp/Mock/opac-includes/create.inc",
634         },
635         "Backend create: commit stage, permitted, ILLModuleUnmediated disabled."
636     );
637
638     # backend_renew
639     $backend->set_series('renew', { stage => 'bar', method => 'renew' });
640     is_deeply($illrq->backend_renew({test => 1}),
641               {
642                   stage => 'bar', method => 'renew',
643                   template => "/tmp/Mock/intra-includes/renew.inc",
644                   opac_template => "/tmp/Mock/opac-includes/renew.inc",
645               },
646               "Backend renew: arbitrary stage.");
647
648     # backend_cancel
649     $backend->set_series('cancel', { stage => 'bar', method => 'cancel' });
650     is_deeply($illrq->backend_cancel({test => 1}),
651               {
652                   stage => 'bar', method => 'cancel',
653                   template => "/tmp/Mock/intra-includes/cancel.inc",
654                   opac_template => "/tmp/Mock/opac-includes/cancel.inc",
655               },
656               "Backend cancel: arbitrary stage.");
657
658     # backend_update_status
659     $backend->set_series('update_status', { stage => 'bar', method => 'update_status' });
660     is_deeply($illrq->backend_update_status({test => 1}),
661               {
662                   stage => 'bar', method => 'update_status',
663                   template => "/tmp/Mock/intra-includes/update_status.inc",
664                   opac_template => "/tmp/Mock/opac-includes/update_status.inc",
665               },
666               "Backend update_status: arbitrary stage.");
667
668     # backend_confirm
669     $backend->set_series('confirm', { stage => 'bar', method => 'confirm' });
670     is_deeply($illrq->backend_confirm({test => 1}),
671               {
672                   stage => 'bar', method => 'confirm',
673                   template => "/tmp/Mock/intra-includes/confirm.inc",
674                   opac_template => "/tmp/Mock/opac-includes/confirm.inc",
675               },
676               "Backend confirm: arbitrary stage.");
677
678     $config->set_always('partner_code', "ILLTSTLIB");
679     $backend->set_always('metadata', { Test => "Foobar" });
680     my $illbrn = $builder->build({
681         source => 'Branch',
682         value => { branchemail => "", branchreplyto => "" }
683     });
684     my $partner1 = $builder->build({
685         source => 'Borrower',
686         value => { categorycode => "ILLTSTLIB" },
687     });
688     my $partner2 = $builder->build({
689         source => 'Borrower',
690         value => { categorycode => "ILLTSTLIB" },
691     });
692     my $gen_conf = $illrq->generic_confirm({
693         current_branchcode => $illbrn->{branchcode}
694     });
695     isnt(index($gen_conf->{value}->{draft}->{body}, $backend->metadata->{Test}), -1,
696          "Generic confirm: draft contains metadata."
697     );
698     is($gen_conf->{value}->{partners}->next->borrowernumber, $partner1->{borrowernumber},
699        "Generic cofnirm: partner 1 is correct."
700     );
701     is($gen_conf->{value}->{partners}->next->borrowernumber, $partner2->{borrowernumber},
702        "Generic confirm: partner 2 is correct."
703     );
704
705     dies_ok { $illrq->generic_confirm({
706         current_branchcode => $illbrn->{branchcode},
707         stage => 'draft'
708     }) }
709         "Generic confirm: missing to dies OK.";
710
711     $schema->storage->txn_rollback;
712 };
713
714
715 subtest 'Helpers' => sub {
716
717     plan tests => 20;
718
719     $schema->storage->txn_begin;
720
721     # Build infrastructure
722     my $backend = Test::MockObject->new;
723     $backend->set_isa('Koha::Illbackends::Mock');
724     $backend->set_always('name', 'Mock');
725     $backend->mock(
726         'metadata',
727         sub {
728             my ( $self, $rq ) = @_;
729             return {
730                 title => 'mytitle',
731                 author => 'myauthor'
732             }
733         }
734     );
735
736     my $config = Test::MockObject->new;
737     $config->set_always('backend_dir', "/tmp");
738
739     my $patron = $builder->build({
740         source => 'Borrower',
741         value => { categorycode => "A" }
742     });
743     # Create a mocked branch with no email addressed defined
744     my $illbrn = $builder->build({
745         source => 'Branch',
746         value => {
747             branchcode => 'HDE',
748             branchemail => "",
749             branchillemail => "",
750             branchreplyto => ""
751         }
752     });
753     my $illrq = $builder->build({
754         source => 'Illrequest',
755         value => { branchcode => "HDE", borrowernumber => $patron->{borrowernumber} }
756     });
757     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
758     $illrq_obj->_config($config);
759     $illrq_obj->_backend($backend);
760
761     # getPrefix
762     $config->set_series('getPrefixes',
763                         { HDE => "TEST", TSL => "BAR", default => "DEFAULT" },
764                         { A => "ATEST", C => "CBAR", default => "DEFAULT" });
765     is($illrq_obj->getPrefix({ brw_cat => "UNKNOWN", branch => "HDE" }), "TEST",
766        "getPrefix: branch");
767     $config->set_series('getPrefixes',
768                         { HDE => "TEST", TSL => "BAR", default => "DEFAULT" },
769                         { A => "ATEST", C => "CBAR", default => "DEFAULT" });
770     is($illrq_obj->getPrefix({ branch => "UNKNOWN" }), "",
771        "getPrefix: default");
772     $config->set_always('getPrefixes', {});
773     is($illrq_obj->getPrefix({ branch => "UNKNOWN" }), "",
774        "getPrefix: the empty prefix");
775
776     # id_prefix
777     $config->set_series('getPrefixes',
778                         { HDE => "TEST", TSL => "BAR", default => "DEFAULT" },
779                         { AB => "ATEST", CD => "CBAR", default => "DEFAULT" });
780     is($illrq_obj->id_prefix, "TEST-", "id_prefix: branch");
781     $config->set_series('getPrefixes',
782                         { HDET => "TEST", TSLT => "BAR", default => "DEFAULT" },
783                         { AB => "ATEST", CD => "CBAR", default => "DEFAULT" });
784     is($illrq_obj->id_prefix, "", "id_prefix: default");
785
786     # requires_moderation
787     $illrq_obj->status('NEW')->store;
788     is($illrq_obj->requires_moderation, undef, "requires_moderation: No.");
789     $illrq_obj->status('CANCREQ')->store;
790     is($illrq_obj->requires_moderation, 'CANCREQ', "requires_moderation: Yes.");
791
792     #send_patron_notice
793     my $attr = Koha::MessageAttributes->find({ message_name => 'Ill_ready' });
794     C4::Members::Messaging::SetMessagingPreference({
795         borrowernumber => $patron->{borrowernumber},
796         message_attribute_id => $attr->message_attribute_id,
797         message_transport_types => ['email']
798     });
799     my $return_patron = $illrq_obj->send_patron_notice('ILL_PICKUP_READY');
800     my $notice = $schema->resultset('MessageQueue')->search({
801             letter_code => 'ILL_PICKUP_READY',
802             message_transport_type => 'email',
803             borrowernumber => $illrq_obj->borrowernumber
804         })->next()->letter_code;
805     is_deeply(
806         $return_patron,
807         { result => { success => ['email'], fail => [] } },
808         "Correct return when notice created"
809     );
810     is($notice, 'ILL_PICKUP_READY' ,"Notice is correctly created");
811
812     my $return_patron_fail = $illrq_obj->send_patron_notice();
813     is_deeply(
814         $return_patron_fail,
815         { error => 'notice_no_type' },
816         "Correct error when missing type"
817     );
818
819     #send_staff_notice
820     # Specify that no staff notices should be send
821     t::lib::Mocks::mock_preference('ILLSendStaffNotices', '');
822     my $return_staff_cancel_fail =
823         $illrq_obj->send_staff_notice('ILL_REQUEST_CANCEL');
824     is_deeply(
825         $return_staff_cancel_fail,
826         { error => 'notice_not_enabled' },
827         "Does not send notices that are not enabled"
828     );
829     my $queue = $schema->resultset('MessageQueue')->search({
830             letter_code => 'ILL_REQUEST_CANCEL'
831         });
832     is($queue->count, 0, "Notice is not queued");
833
834     # Specify that the cancel notice can be sent
835     t::lib::Mocks::mock_preference('ILLSendStaffNotices', 'ILL_REQUEST_CANCEL');
836     my $return_staff_cancel = $illrq_obj->send_staff_notice(
837         'ILL_REQUEST_CANCEL'
838     );
839     is_deeply(
840         $return_staff_cancel,
841         { success => 'notice_queued' },
842         "Correct return when staff notice created"
843     );
844     $queue = $schema->resultset('MessageQueue')->search({
845             letter_code => 'ILL_REQUEST_CANCEL'
846         });
847     is($queue->count, 1, "Notice queued as expected");
848
849     my $return_staff_fail = $illrq_obj->send_staff_notice();
850     is_deeply(
851         $return_staff_fail,
852         { error => 'notice_no_type' },
853         "Correct error when missing type"
854     );
855     $queue = $schema->resultset('MessageQueue')->search({
856             letter_code => 'ILL_REQUEST_CANCEL'
857         });
858     is($queue->count, 1, "Notice is not queued");
859
860     #get_notice
861     my $not = $illrq_obj->get_notice({
862         notice_code => 'ILL_REQUEST_CANCEL',
863         transport   => 'email'
864     });
865
866     # We test the properties of the hashref separately because the random
867     # hash ordering of the metadata means we can't test the entire thing
868     # with is_deeply
869     ok(
870         $not->{module} eq 'ill',
871         'Correct module return from get_notice'
872     );
873     ok(
874         $not->{name} eq 'ILL request cancelled',
875         'Correct name return from get_notice'
876     );
877     ok(
878         $not->{message_transport_type} eq 'email',
879         'Correct message_transport_type return from get_notice'
880     );
881     ok(
882         $not->{title} eq 'Interlibrary loan request cancelled',
883         'Correct title return from get_notice'
884     );
885
886     $schema->storage->txn_rollback;
887 };
888
889
890 subtest 'Censorship' => sub {
891
892     plan tests => 2;
893
894     $schema->storage->txn_begin;
895
896     # Build infrastructure
897     my $backend = Test::MockObject->new;
898     $backend->set_isa('Koha::Illbackends::Mock');
899     $backend->set_always('name', 'Mock');
900
901     my $config = Test::MockObject->new;
902     $config->set_always('backend_dir', "/tmp");
903
904     my $illrq = $builder->build({source => 'Illrequest'});
905     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
906     $illrq_obj->_config($config);
907     $illrq_obj->_backend($backend);
908
909     $config->set_always('censorship', { censor_notes_staff => 1, censor_reply_date => 0 });
910
911     my $censor_out = $illrq_obj->_censor({ foo => 'bar', baz => 564 });
912     is_deeply($censor_out, { foo => 'bar', baz => 564, display_reply_date => 1 },
913               "_censor: not OPAC, reply_date = 1");
914
915     $censor_out = $illrq_obj->_censor({ foo => 'bar', baz => 564, opac => 1 });
916     is_deeply($censor_out, {
917         foo => 'bar', baz => 564, censor_notes_staff => 1,
918         display_reply_date => 1, opac => 1
919     }, "_censor: notes_staff = 0, reply_date = 0");
920
921     $schema->storage->txn_rollback;
922 };
923
924 subtest 'Checking out' => sub {
925
926     plan tests => 17;
927
928     $schema->storage->txn_begin;
929
930     my $itemtype = $builder->build_object({
931         class => 'Koha::ItemTypes',
932         value => {
933             notforloan => 1
934         }
935     });
936     my $library = $builder->build_object({ class => 'Koha::Libraries' });
937     my $biblio = $builder->build_sample_biblio();
938     my $patron = $builder->build_object({
939         class => 'Koha::Patrons',
940         value => { category_type => 'x' }
941     });
942     my $request = $builder->build_object({
943         class => 'Koha::Illrequests',
944         value => {
945             borrowernumber => $patron->borrowernumber,
946             biblio_id      => $biblio->biblionumber
947         }
948     });
949
950     # First test that calling check_out without a stage param returns
951     # what's required to build the form
952     my $no_stage = $request->check_out();
953     is($no_stage->{method}, 'check_out');
954     is($no_stage->{stage}, 'form');
955     isa_ok($no_stage->{value}, 'HASH');
956     isa_ok($no_stage->{value}->{itemtypes}, 'Koha::ItemTypes');
957     isa_ok($no_stage->{value}->{libraries}, 'Koha::Libraries');
958     isa_ok($no_stage->{value}->{statistical}, 'Koha::Patrons');
959     isa_ok($no_stage->{value}->{biblio}, 'Koha::Biblio');
960
961     # Now test that form validation works when we supply a 'form' stage
962     #
963     # No item_type
964     my $form_stage_missing_params = $request->check_out({
965         stage => 'form'
966     });
967     is_deeply($form_stage_missing_params->{value}->{errors}, {
968         item_type => 1
969     });
970     # inhouse passed but not a valid patron
971     my $form_stage_bad_patron = $request->check_out({
972         stage     => 'form',
973         item_type => $itemtype->itemtype,
974         inhouse   => 'I_DONT_EXIST'
975     });
976     is_deeply($form_stage_bad_patron->{value}->{errors}, {
977         inhouse => 1
978     });
979     # Too many items attached to biblio
980     my $item1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
981     my $item2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
982     my $form_stage_two_items = $request->check_out({
983         stage     => 'form',
984         item_type => $itemtype->itemtype,
985     });
986     is_deeply($form_stage_two_items->{value}->{errors}, {
987         itemcount => 1
988     });
989
990     # Delete the items we created, so we can test that we can create one
991     $item1->delete;
992     $item2->delete;
993
994     # We need to mock the user environment for AddIssue
995     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
996     #
997
998     # First we pass bad parameters to the item creation to test we're
999     # catching the failure of item creation
1000     my $form_stage_bad_branchcode;
1001     warning_like {
1002         $form_stage_bad_branchcode = $request->check_out({
1003             stage     => 'form',
1004             item_type => $itemtype->itemtype,
1005             branchcode => '---'
1006         });
1007     } qr/DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/,
1008     "Item creation fails on bad parameters";
1009
1010     is_deeply($form_stage_bad_branchcode->{value}->{errors}, {
1011         item_creation => 1
1012     },"We get expected failure of item creation");
1013
1014     # Now create a proper item
1015     my $form_stage_good_branchcode = $request->check_out({
1016         stage      => 'form',
1017         item_type  => $itemtype->itemtype,
1018         branchcode => $library->branchcode
1019     });
1020     # By default, this item should not be loanable, so check that we're
1021     # informed of that fact
1022     is_deeply(
1023         $form_stage_good_branchcode->{value}->{check_out_errors},
1024         {
1025             error => {
1026                 NOT_FOR_LOAN => 1,
1027                 itemtype_notforloan => $itemtype->itemtype
1028             }
1029         },
1030         "We get expected error on notforloan of item"
1031     );
1032     # Delete the item that was created
1033     $biblio->items->delete;
1034     # Now create an itemtype that is loanable
1035     my $itemtype_loanable = $builder->build_object({
1036         class => 'Koha::ItemTypes',
1037         value => {
1038             notforloan => 0
1039         }
1040     });
1041     # We need to mock the user environment for AddIssue
1042     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
1043     my $form_stage_loanable = $request->check_out({
1044         stage      => 'form',
1045         item_type  => $itemtype_loanable->itemtype,
1046         branchcode => $library->branchcode
1047     });
1048     is($form_stage_loanable->{stage}, 'done_check_out');
1049     isa_ok($patron->checkouts, 'Koha::Checkouts');
1050     is($patron->checkouts->count, 1);
1051     is($request->status, 'CHK');
1052
1053     $schema->storage->txn_rollback;
1054 };
1055
1056 subtest 'Checking Limits' => sub {
1057
1058     plan tests => 30;
1059
1060     $schema->storage->txn_begin;
1061
1062     # Build infrastructure
1063     my $backend = Test::MockObject->new;
1064     $backend->set_isa('Koha::Illbackends::Mock');
1065     $backend->set_always('name', 'Mock');
1066
1067     my $config = Test::MockObject->new;
1068     $config->set_always('backend_dir', "/tmp");
1069
1070     my $illrq = $builder->build({source => 'Illrequest'});
1071     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
1072     $illrq_obj->_config($config);
1073     $illrq_obj->_backend($backend);
1074
1075     # getLimits
1076     $config->set_series('getLimitRules',
1077                         { CPL => { count => 1, method => 'test' } },
1078                         { default => { count => 0, method => 'active' } });
1079     is_deeply($illrq_obj->getLimits({ type => 'branch', value => "CPL" }),
1080               { count => 1, method => 'test' },
1081               "getLimits: by value.");
1082     is_deeply($illrq_obj->getLimits({ type => 'branch' }),
1083               { count => 0, method => 'active' },
1084               "getLimits: by default.");
1085     is_deeply($illrq_obj->getLimits({ type => 'branch', value => "CPL" }),
1086               { count => -1, method => 'active' },
1087               "getLimits: by hard-coded.");
1088
1089     #_limit_counter
1090     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
1091        1, "_limit_counter: Initial branch annual count.");
1092     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
1093        1, "_limit_counter: Initial branch active count.");
1094     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
1095        1, "_limit_counter: Initial patron annual count.");
1096     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
1097        1, "_limit_counter: Initial patron active count.");
1098     $builder->build({
1099         source => 'Illrequest',
1100         value => {
1101             branchcode => $illrq_obj->branchcode,
1102             borrowernumber => $illrq_obj->borrowernumber,
1103         }
1104     });
1105     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
1106        2, "_limit_counter: Add a qualifying request for branch annual count.");
1107     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
1108        2, "_limit_counter: Add a qualifying request for branch active count.");
1109     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
1110        2, "_limit_counter: Add a qualifying request for patron annual count.");
1111     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
1112        2, "_limit_counter: Add a qualifying request for patron active count.");
1113     $builder->build({
1114         source => 'Illrequest',
1115         value => {
1116             branchcode => $illrq_obj->branchcode,
1117             borrowernumber => $illrq_obj->borrowernumber,
1118             placed => "2005-05-31",
1119         }
1120     });
1121     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
1122        2, "_limit_counter: Add an out-of-date branch request.");
1123     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
1124        3, "_limit_counter: Add a qualifying request for branch active count.");
1125     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
1126        2, "_limit_counter: Add an out-of-date patron request.");
1127     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
1128        3, "_limit_counter: Add a qualifying request for patron active count.");
1129     $builder->build({
1130         source => 'Illrequest',
1131         value => {
1132             branchcode => $illrq_obj->branchcode,
1133             borrowernumber => $illrq_obj->borrowernumber,
1134             status => "COMP",
1135         }
1136     });
1137     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
1138        3, "_limit_counter: Add a qualifying request for branch annual count.");
1139     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
1140        3, "_limit_counter: Add a completed request for branch active count.");
1141     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
1142        3, "_limit_counter: Add a qualifying request for patron annual count.");
1143     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
1144        3, "_limit_counter: Add a completed request for patron active count.");
1145
1146     # check_limits:
1147
1148     # We've tested _limit_counter, so all we need to test here is whether the
1149     # current counts of 3 for each work as they should against different
1150     # configuration declarations.
1151
1152     # No limits
1153     $config->set_always('getLimitRules', undef);
1154     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1155                                  librarycode => $illrq_obj->branchcode}),
1156        1, "check_limits: no configuration => no limits.");
1157
1158     # Branch tests
1159     $config->set_always('getLimitRules',
1160                         { $illrq_obj->branchcode => { count => 1, method => 'active' } });
1161     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1162                                  librarycode => $illrq_obj->branchcode}),
1163        0, "check_limits: branch active limit exceeded.");
1164     $config->set_always('getLimitRules',
1165                         { $illrq_obj->branchcode => { count => 1, method => 'annual' } });
1166     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1167                                  librarycode => $illrq_obj->branchcode}),
1168        0, "check_limits: branch annual limit exceeded.");
1169     $config->set_always('getLimitRules',
1170                         { $illrq_obj->branchcode => { count => 4, method => 'active' } });
1171     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1172                                  librarycode => $illrq_obj->branchcode}),
1173        1, "check_limits: branch active limit OK.");
1174     $config->set_always('getLimitRules',
1175                         { $illrq_obj->branchcode => { count => 4, method => 'annual' } });
1176     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1177                                  librarycode => $illrq_obj->branchcode}),
1178        1, "check_limits: branch annual limit OK.");
1179
1180     # Patron tests
1181     $config->set_always('getLimitRules',
1182                         { $illrq_obj->patron->categorycode => { count => 1, method => 'active' } });
1183     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1184                                  librarycode => $illrq_obj->branchcode}),
1185        0, "check_limits: patron category active limit exceeded.");
1186     $config->set_always('getLimitRules',
1187                         { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } });
1188     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1189                                  librarycode => $illrq_obj->branchcode}),
1190        0, "check_limits: patron category annual limit exceeded.");
1191     $config->set_always('getLimitRules',
1192                         { $illrq_obj->patron->categorycode => { count => 4, method => 'active' } });
1193     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1194                                  librarycode => $illrq_obj->branchcode}),
1195        1, "check_limits: patron category active limit OK.");
1196     $config->set_always('getLimitRules',
1197                         { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } });
1198     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1199                                  librarycode => $illrq_obj->branchcode}),
1200        1, "check_limits: patron category annual limit OK.");
1201
1202     # One rule cancels the other
1203     $config->set_series('getLimitRules',
1204                         # Branch rules allow request
1205                         { $illrq_obj->branchcode => { count => 4, method => 'active' } },
1206                         # Patron rule forbids it
1207                         { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } });
1208     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1209                                  librarycode => $illrq_obj->branchcode}),
1210        0, "check_limits: patron category veto overrides branch OK.");
1211     $config->set_series('getLimitRules',
1212                         # Branch rules allow request
1213                         { $illrq_obj->branchcode => { count => 1, method => 'active' } },
1214                         # Patron rule forbids it
1215                         { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } });
1216     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1217                                  librarycode => $illrq_obj->branchcode}),
1218        0, "check_limits: branch veto overrides patron category OK.");
1219
1220     $schema->storage->txn_rollback;
1221 };
1222
1223 subtest 'Custom statuses' => sub {
1224
1225     plan tests => 3;
1226
1227     $schema->storage->txn_begin;
1228
1229     my $cat = Koha::AuthorisedValueCategories->search(
1230         {
1231             category_name => 'ILLSTATUS'
1232         }
1233     );
1234
1235     if ($cat->count == 0) {
1236         $cat  = $builder->build_object(
1237             {
1238                 class => 'Koha::AuthorisedValueCategory',
1239                 value => {
1240                     category_name => 'ILLSTATUS'
1241                 }
1242             }
1243         );
1244     };
1245
1246     my $av = $builder->build_object(
1247         {
1248             class => 'Koha::AuthorisedValues',
1249             value => {
1250                 category => 'ILLSTATUS'
1251             }
1252         }
1253     );
1254
1255     is($av->category, 'ILLSTATUS',
1256        "Successfully created authorised value for custom status");
1257
1258     my $ill_req = $builder->build_object(
1259         {
1260             class => 'Koha::Illrequests',
1261             value => {
1262                 status_alias => $av->authorised_value
1263             }
1264         }
1265     );
1266     isa_ok($ill_req->statusalias, 'Koha::AuthorisedValue',
1267            "statusalias correctly returning Koha::AuthorisedValue object");
1268
1269     $ill_req->status("COMP");
1270     is($ill_req->statusalias, undef,
1271         "Koha::Illrequest->status overloading resetting status_alias");
1272
1273     $schema->storage->txn_rollback;
1274 };
1275
1276 subtest 'Checking in hook' => sub {
1277
1278     plan tests => 2;
1279
1280     $schema->storage->txn_begin;
1281
1282     # Build infrastructure
1283     my $backend = Test::MockObject->new;
1284     $backend->set_isa('Koha::Illbackends::Mock');
1285     $backend->set_always('name', 'Mock');
1286
1287     my $config = Test::MockObject->new;
1288     $config->set_always('backend_dir', "/tmp");
1289
1290     my $item   = $builder->build_sample_item();
1291     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1292
1293     t::lib::Mocks::mock_userenv(
1294         {
1295             patron     => $patron,
1296             branchcode => $patron->branchcode
1297         }
1298     );
1299
1300     my $illrq = $builder->build_object(
1301         {
1302             class => 'Koha::Illrequests',
1303             value => {
1304                 biblio_id => $item->biblio->biblionumber,
1305                 status    => 'NEW'
1306             }
1307         }
1308     );
1309
1310     $illrq->_config($config);
1311     $illrq->_backend($backend);
1312
1313     t::lib::Mocks::mock_preference('CirculateILL', 1);
1314
1315     # Add an issue
1316     AddIssue( $patron->unblessed, $item->barcode );
1317     # Make the item withdrawn so checking-in is rejected
1318     t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1);
1319     $item->set({ withdrawn => 1 })->store;
1320     AddReturn( $item->barcode, $patron->branchcode );
1321     # refresh request
1322     $illrq->discard_changes;
1323     isnt( $illrq->status, 'RET' );
1324
1325     # allow the check-in
1326     $item->set({ withdrawn => 0 })->store;
1327     AddReturn( $item->barcode, $patron->branchcode );
1328     # refresh request
1329     $illrq->discard_changes;
1330     is( $illrq->status, 'RET' );
1331
1332     $schema->storage->txn_rollback;
1333 };