Bug 7317: Handle backend absense more gracefuly
[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 use Koha::Database;
22 use Koha::Illrequestattributes;
23 use Koha::Illrequest::Config;
24 use Koha::Patrons;
25 use t::lib::Mocks;
26 use t::lib::TestBuilder;
27 use Test::MockObject;
28 use Test::MockModule;
29 use Test::Exception;
30
31 use Test::More tests => 11;
32
33 my $schema = Koha::Database->new->schema;
34 my $builder = t::lib::TestBuilder->new;
35 use_ok('Koha::Illrequest');
36 use_ok('Koha::Illrequests');
37
38 subtest 'Basic object tests' => sub {
39
40     plan tests => 21;
41
42     $schema->storage->txn_begin;
43
44     Koha::Illrequests->search->delete;
45     my $illrq = $builder->build({ source => 'Illrequest' });
46     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
47
48     isa_ok($illrq_obj, 'Koha::Illrequest',
49            "Correctly create and load an illrequest object.");
50     isa_ok($illrq_obj->_config, 'Koha::Illrequest::Config',
51            "Created a config object as part of Illrequest creation.");
52
53     is($illrq_obj->illrequest_id, $illrq->{illrequest_id},
54        "Illrequest_id getter works.");
55     is($illrq_obj->borrowernumber, $illrq->{borrowernumber},
56        "Borrowernumber getter works.");
57     is($illrq_obj->biblio_id, $illrq->{biblio_id},
58        "Biblio_Id getter works.");
59     is($illrq_obj->branchcode, $illrq->{branchcode},
60        "Branchcode getter works.");
61     is($illrq_obj->status, $illrq->{status},
62        "Status getter works.");
63     is($illrq_obj->placed, $illrq->{placed},
64        "Placed getter works.");
65     is($illrq_obj->replied, $illrq->{replied},
66        "Replied getter works.");
67     is($illrq_obj->updated, $illrq->{updated},
68        "Updated getter works.");
69     is($illrq_obj->completed, $illrq->{completed},
70        "Completed getter works.");
71     is($illrq_obj->medium, $illrq->{medium},
72        "Medium getter works.");
73     is($illrq_obj->accessurl, $illrq->{accessurl},
74        "Accessurl getter works.");
75     is($illrq_obj->cost, $illrq->{cost},
76        "Cost getter works.");
77     is($illrq_obj->notesopac, $illrq->{notesopac},
78        "Notesopac getter works.");
79     is($illrq_obj->notesstaff, $illrq->{notesstaff},
80        "Notesstaff getter works.");
81     is($illrq_obj->orderid, $illrq->{orderid},
82        "Orderid getter works.");
83     is($illrq_obj->backend, $illrq->{backend},
84        "Backend getter works.");
85
86     isnt($illrq_obj->status, 'COMP',
87          "ILL is not currently marked complete.");
88     $illrq_obj->mark_completed;
89     is($illrq_obj->status, 'COMP',
90        "ILL is now marked complete.");
91
92     $illrq_obj->delete;
93
94     is(Koha::Illrequests->search->count, 0,
95        "No illrequest found after delete.");
96
97     $schema->storage->txn_rollback;
98 };
99
100 subtest 'Working with related objects' => sub {
101
102     plan tests => 5;
103
104     $schema->storage->txn_begin;
105
106     my $patron = $builder->build({ source => 'Borrower' });
107     my $illrq = $builder->build({
108         source => 'Illrequest',
109         value => { borrowernumber => $patron->{borrowernumber} }
110     });
111     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
112
113     isa_ok($illrq_obj->patron, 'Koha::Patron',
114            "OK accessing related patron.");
115
116     $builder->build({
117         source => 'Illrequestattribute',
118         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'X' }
119     });
120     $builder->build({
121         source => 'Illrequestattribute',
122         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'Y' }
123     });
124     $builder->build({
125         source => 'Illrequestattribute',
126         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'Z' }
127     });
128
129     is($illrq_obj->illrequestattributes->count, Koha::Illrequestattributes->search->count,
130        "Fetching expected number of Illrequestattributes for our request.");
131
132     my $illrq1 = $builder->build({ source => 'Illrequest' });
133     $builder->build({
134         source => 'Illrequestattribute',
135         value  => { illrequest_id => $illrq1->{illrequest_id}, type => 'X' }
136     });
137
138     is($illrq_obj->illrequestattributes->count + 1, Koha::Illrequestattributes->search->count,
139        "Fetching expected number of Illrequestattributes for our request.");
140
141     $illrq_obj->delete;
142     is(Koha::Illrequestattributes->search->count, 1,
143        "Correct number of illrequestattributes after delete.");
144
145     isa_ok(Koha::Patrons->find($patron->{borrowernumber}), 'Koha::Patron',
146            "Borrower was not deleted after illrq delete.");
147
148     $schema->storage->txn_rollback;
149 };
150
151 subtest 'Status Graph tests' => sub {
152
153     plan tests => 4;
154
155     $schema->storage->txn_begin;
156
157     my $illrq = $builder->build({source => 'Illrequest'});
158     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
159
160     # _core_status_graph tests: it's just a constant, so here we just make
161     # sure it returns a hashref.
162     is(ref $illrq_obj->_core_status_graph, "HASH",
163        "_core_status_graph returns a hash.");
164
165     # _status_graph_union: let's try different merge operations.
166     # Identity operation
167     is_deeply(
168         $illrq_obj->_status_graph_union($illrq_obj->_core_status_graph, {}),
169         $illrq_obj->_core_status_graph,
170         "core_status_graph + null = core_status_graph"
171     );
172
173     # Simple addition
174     is_deeply(
175         $illrq_obj->_status_graph_union({}, $illrq_obj->_core_status_graph),
176         $illrq_obj->_core_status_graph,
177         "null + core_status_graph = core_status_graph"
178     );
179
180     # Correct merge behaviour
181     is_deeply(
182         $illrq_obj->_status_graph_union({
183             REQ => {
184                 prev_actions   => [ ],
185                 id             => 'REQ',
186                 next_actions   => [ ],
187             },
188         }, {
189             QER => {
190                 prev_actions   => [ 'REQ' ],
191                 id             => 'QER',
192                 next_actions   => [ 'REQ' ],
193             },
194         }),
195         {
196             REQ => {
197                 prev_actions   => [ 'QER' ],
198                 id             => 'REQ',
199                 next_actions   => [ 'QER' ],
200             },
201             QER => {
202                 prev_actions   => [ 'REQ' ],
203                 id             => 'QER',
204                 next_actions   => [ 'REQ' ],
205             },
206         },
207         "REQ atom + linking QER = cyclical status graph"
208     );
209
210     $schema->storage->txn_rollback;
211 };
212
213 subtest 'Backend testing (mocks)' => sub {
214
215     plan tests => 13;
216
217     $schema->storage->txn_begin;
218
219     # testing load_backend & available_backends requires that we have at least
220     # the Dummy plugin installed.  load_backend & available_backends don't
221     # currently have tests as a result.
222
223     my $backend = Test::MockObject->new;
224     $backend->set_isa('Koha::Illbackends::Mock');
225     $backend->set_always('name', 'Mock');
226
227     my $patron = $builder->build({ source => 'Borrower' });
228     my $illrq = $builder->build({
229         source => 'Illrequest',
230         value => { borrowernumber => $patron->{borrowernumber} }
231     });
232     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
233
234     $illrq_obj->_backend($backend);
235
236     isa_ok($illrq_obj->_backend, 'Koha::Illbackends::Mock',
237            "OK accessing mocked backend.");
238
239     # _backend_capability tests:
240     # We need to test whether this optional feature of a mocked backend
241     # behaves as expected.
242     # 3 scenarios: feature not implemented, feature implemented, but requested
243     # capability is not provided by backend, & feature is implemented &
244     # capability exists.  This method can be used to implement custom backend
245     # functionality, such as unmediated in the BLDSS backend (also see
246     # bugzilla 18837).
247     $backend->set_always('capabilities', undef);
248     is($illrq_obj->_backend_capability('Test'), 0,
249        "0 returned on Mock not implementing capabilities.");
250
251     $backend->set_always('capabilities', 0);
252     is($illrq_obj->_backend_capability('Test'), 0,
253        "0 returned on Mock not implementing Test capability.");
254
255     $backend->set_always('capabilities', sub { return 'bar'; } );
256     is($illrq_obj->_backend_capability('Test'), 'bar',
257        "'bar' returned on Mock implementing Test capability.");
258
259     # metadata test: we need to be sure that we return the arbitrary values
260     # from the backend.
261     $backend->mock(
262         'metadata',
263         sub {
264             my ( $self, $rq ) = @_;
265             return {
266                 ID => $rq->illrequest_id,
267                 Title => $rq->patron->borrowernumber
268             }
269         }
270     );
271
272     is_deeply(
273         $illrq_obj->metadata,
274         {
275             ID => $illrq_obj->illrequest_id,
276             Title => $illrq_obj->patron->borrowernumber
277         },
278         "Test metadata."
279     );
280
281     # capabilities:
282
283     # No backend graph extension
284     $backend->set_always('status_graph', {});
285     is_deeply($illrq_obj->capabilities('COMP'),
286               {
287                   prev_actions   => [ 'REQ' ],
288                   id             => 'COMP',
289                   name           => 'Completed',
290                   ui_method_name => 'Mark completed',
291                   method         => 'mark_completed',
292                   next_actions   => [ ],
293                   ui_method_icon => 'fa-check',
294               },
295               "Dummy status graph for COMP.");
296     is($illrq_obj->capabilities('UNKNOWN'), undef,
297        "Dummy status graph for UNKNOWN.");
298     is_deeply($illrq_obj->capabilities(),
299               $illrq_obj->_core_status_graph,
300               "Dummy full status graph.");
301     # Simple backend graph extension
302     $backend->set_always('status_graph',
303                          {
304                              QER => {
305                                  prev_actions   => [ 'REQ' ],
306                                  id             => 'QER',
307                                  next_actions   => [ 'REQ' ],
308                              },
309                          });
310     is_deeply($illrq_obj->capabilities('QER'),
311               {
312                   prev_actions   => [ 'REQ' ],
313                   id             => 'QER',
314                   next_actions   => [ 'REQ' ],
315               },
316               "Simple status graph for QER.");
317     is($illrq_obj->capabilities('UNKNOWN'), undef,
318        "Simple status graph for UNKNOWN.");
319     is_deeply($illrq_obj->capabilities(),
320               $illrq_obj->_status_graph_union(
321                   $illrq_obj->_core_status_graph,
322                   {
323                       QER => {
324                           prev_actions   => [ 'REQ' ],
325                           id             => 'QER',
326                           next_actions   => [ 'REQ' ],
327                       },
328                   }
329               ),
330               "Simple full status graph.");
331
332     # custom_capability:
333
334     # No backend graph extension
335     $backend->set_always('status_graph', {});
336     is($illrq_obj->custom_capability('unknown', {}), 0,
337        "Unknown candidate.");
338
339     # Simple backend graph extension
340     $backend->set_always('status_graph',
341                          {
342                              ID => {
343                                  prev_actions   => [ 'REQ' ],
344                                  id             => 'ID',
345                                  method         => 'identity',
346                                  next_actions   => [ 'REQ' ],
347                              },
348                          });
349     $backend->mock('identity',
350                    sub { my ( $self, $params ) = @_; return $params->{other}; });
351     is($illrq_obj->custom_capability('identity', { test => 1 })->{test}, 1,
352        "Resolve identity custom_capability");
353
354     $schema->storage->txn_rollback;
355 };
356
357
358 subtest 'Backend core methods' => sub {
359
360     plan tests => 18;
361
362     $schema->storage->txn_begin;
363
364     # Build infrastructure
365     my $backend = Test::MockObject->new;
366     $backend->set_isa('Koha::Illbackends::Mock');
367     $backend->set_always('name', 'Mock');
368
369     my $config = Test::MockObject->new;
370     $config->set_always('backend_dir', "/tmp");
371     $config->set_always('getLimitRules',
372                         { default => { count => 0, method => 'active' } });
373
374     my $illrq = $builder->build_object({
375         class => 'Koha::Illrequests',
376         value => { backend => undef }
377     });
378     $illrq->_config($config);
379
380     # Test error conditions (no backend)
381     throws_ok { $illrq->load_backend; }
382         'Koha::Exceptions::Ill::InvalidBackendId',
383         'Exception raised correctly';
384
385     throws_ok { $illrq->load_backend(''); }
386         'Koha::Exceptions::Ill::InvalidBackendId',
387         'Exception raised correctly';
388
389     # Now load the mocked backend
390     $illrq->_backend($backend);
391
392     # expandTemplate:
393     is_deeply($illrq->expandTemplate({ test => 1, method => "bar" }),
394               {
395                   test => 1,
396                   method => "bar",
397                   template => "/tmp/Mock/intra-includes/bar.inc",
398                   opac_template => "/tmp/Mock/opac-includes/bar.inc",
399               },
400               "ExpandTemplate");
401
402     # backend_create
403     # we are testing simple cases.
404     $backend->set_series('create',
405                          { stage => 'bar', method => 'create' },
406                          { stage => 'commit', method => 'create' },
407                          { stage => 'commit', method => 'create' });
408     # Test Copyright Clearance
409     t::lib::Mocks::mock_preference("ILLModuleCopyrightClearance", "Test Copyright Clearance.");
410     is_deeply($illrq->backend_create({test => 1}),
411               {
412                   error   => 0,
413                   status  => '',
414                   message => '',
415                   method  => 'create',
416                   stage   => 'copyrightclearance',
417                   value   => {
418                       backend => "Mock"
419                   }
420               },
421               "Backend create: copyright clearance.");
422     t::lib::Mocks::mock_preference("ILLModuleCopyrightClearance", "");
423     # Test non-commit
424     is_deeply($illrq->backend_create({test => 1}),
425               {
426                   stage => 'bar', method => 'create',
427                   template => "/tmp/Mock/intra-includes/create.inc",
428                   opac_template => "/tmp/Mock/opac-includes/create.inc",
429               },
430               "Backend create: arbitrary stage.");
431     # Test commit
432     is_deeply($illrq->backend_create({test => 1}),
433               {
434                   stage => 'commit', method => 'create', permitted => 0,
435                   template => "/tmp/Mock/intra-includes/create.inc",
436                   opac_template => "/tmp/Mock/opac-includes/create.inc",
437               },
438               "Backend create: arbitrary stage, not permitted.");
439     is($illrq->status, "QUEUED", "Backend create: queued if restricted.");
440     $config->set_always('getLimitRules', {});
441     $illrq->status('NEW');
442     is_deeply($illrq->backend_create({test => 1}),
443               {
444                   stage => 'commit', method => 'create', permitted => 1,
445                   template => "/tmp/Mock/intra-includes/create.inc",
446                   opac_template => "/tmp/Mock/opac-includes/create.inc",
447               },
448               "Backend create: arbitrary stage, permitted.");
449     is($illrq->status, "NEW", "Backend create: not-queued.");
450
451     # backend_renew
452     $backend->set_series('renew', { stage => 'bar', method => 'renew' });
453     is_deeply($illrq->backend_renew({test => 1}),
454               {
455                   stage => 'bar', method => 'renew',
456                   template => "/tmp/Mock/intra-includes/renew.inc",
457                   opac_template => "/tmp/Mock/opac-includes/renew.inc",
458               },
459               "Backend renew: arbitrary stage.");
460
461     # backend_cancel
462     $backend->set_series('cancel', { stage => 'bar', method => 'cancel' });
463     is_deeply($illrq->backend_cancel({test => 1}),
464               {
465                   stage => 'bar', method => 'cancel',
466                   template => "/tmp/Mock/intra-includes/cancel.inc",
467                   opac_template => "/tmp/Mock/opac-includes/cancel.inc",
468               },
469               "Backend cancel: arbitrary stage.");
470
471     # backend_update_status
472     $backend->set_series('update_status', { stage => 'bar', method => 'update_status' });
473     is_deeply($illrq->backend_update_status({test => 1}),
474               {
475                   stage => 'bar', method => 'update_status',
476                   template => "/tmp/Mock/intra-includes/update_status.inc",
477                   opac_template => "/tmp/Mock/opac-includes/update_status.inc",
478               },
479               "Backend update_status: arbitrary stage.");
480
481     # backend_confirm
482     $backend->set_series('confirm', { stage => 'bar', method => 'confirm' });
483     is_deeply($illrq->backend_confirm({test => 1}),
484               {
485                   stage => 'bar', method => 'confirm',
486                   template => "/tmp/Mock/intra-includes/confirm.inc",
487                   opac_template => "/tmp/Mock/opac-includes/confirm.inc",
488               },
489               "Backend confirm: arbitrary stage.");
490
491     $config->set_always('partner_code', "ILLTSTLIB");
492     $backend->set_always('metadata', { Test => "Foobar" });
493     my $illbrn = $builder->build({
494         source => 'Branch',
495         value => { branchemail => "", branchreplyto => "" }
496     });
497     my $partner1 = $builder->build({
498         source => 'Borrower',
499         value => { categorycode => "ILLTSTLIB" },
500     });
501     my $partner2 = $builder->build({
502         source => 'Borrower',
503         value => { categorycode => "ILLTSTLIB" },
504     });
505     my $gen_conf = $illrq->generic_confirm({
506         current_branchcode => $illbrn->{branchcode}
507     });
508     isnt(index($gen_conf->{value}->{draft}->{body}, $backend->metadata->{Test}), -1,
509          "Generic confirm: draft contains metadata."
510     );
511     is($gen_conf->{value}->{partners}->next->borrowernumber, $partner1->{borrowernumber},
512        "Generic cofnirm: partner 1 is correct."
513     );
514     is($gen_conf->{value}->{partners}->next->borrowernumber, $partner2->{borrowernumber},
515        "Generic confirm: partner 2 is correct."
516     );
517
518     dies_ok { $illrq->generic_confirm({
519         current_branchcode => $illbrn->{branchcode},
520         stage => 'draft'
521     }) }
522         "Generic confirm: missing to dies OK.";
523
524     dies_ok { $illrq->generic_confirm({
525         current_branchcode => $illbrn->{branchcode},
526         partners => $partner1->{email},
527         stage => 'draft'
528     }) }
529         "Generic confirm: missing from dies OK.";
530
531     $schema->storage->txn_rollback;
532 };
533
534
535 subtest 'Helpers' => sub {
536
537     plan tests => 9;
538
539     $schema->storage->txn_begin;
540
541     # Build infrastructure
542     my $backend = Test::MockObject->new;
543     $backend->set_isa('Koha::Illbackends::Mock');
544     $backend->set_always('name', 'Mock');
545
546     my $config = Test::MockObject->new;
547     $config->set_always('backend_dir', "/tmp");
548
549     my $patron = $builder->build({
550         source => 'Borrower',
551         value => { categorycode => "A" }
552     });
553     my $illrq = $builder->build({
554         source => 'Illrequest',
555         value => { branchcode => "CPL", borrowernumber => $patron->{borrowernumber} }
556     });
557     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
558     $illrq_obj->_config($config);
559     $illrq_obj->_backend($backend);
560
561     # getPrefix
562     $config->set_series('getPrefixes',
563                         { CPL => "TEST", TSL => "BAR", default => "DEFAULT" },
564                         { A => "ATEST", C => "CBAR", default => "DEFAULT" });
565     is($illrq_obj->getPrefix({ brw_cat => "C", branch => "CPL" }), "CBAR",
566        "getPrefix: brw_cat");
567     $config->set_series('getPrefixes',
568                         { CPL => "TEST", TSL => "BAR", default => "DEFAULT" },
569                         { A => "ATEST", C => "CBAR", default => "DEFAULT" });
570     is($illrq_obj->getPrefix({ brw_cat => "UNKNOWN", branch => "CPL" }), "TEST",
571        "getPrefix: branch");
572     $config->set_series('getPrefixes',
573                         { CPL => "TEST", TSL => "BAR", default => "DEFAULT" },
574                         { A => "ATEST", C => "CBAR", default => "DEFAULT" });
575     is($illrq_obj->getPrefix({ brw_cat => "UNKNOWN", branch => "UNKNOWN" }), "DEFAULT",
576        "getPrefix: default");
577     $config->set_always('getPrefixes', {});
578     is($illrq_obj->getPrefix({ brw_cat => "UNKNOWN", branch => "UNKNOWN" }), "",
579        "getPrefix: the empty prefix");
580
581     # id_prefix
582     $config->set_series('getPrefixes',
583                         { CPL => "TEST", TSL => "BAR", default => "DEFAULT" },
584                         { A => "ATEST", C => "CBAR", default => "DEFAULT" });
585     is($illrq_obj->id_prefix, "ATEST-", "id_prefix: brw_cat");
586     $config->set_series('getPrefixes',
587                         { CPL => "TEST", TSL => "BAR", default => "DEFAULT" },
588                         { AB => "ATEST", CD => "CBAR", default => "DEFAULT" });
589     is($illrq_obj->id_prefix, "TEST-", "id_prefix: branch");
590     $config->set_series('getPrefixes',
591                         { CPLT => "TEST", TSLT => "BAR", default => "DEFAULT" },
592                         { AB => "ATEST", CD => "CBAR", default => "DEFAULT" });
593     is($illrq_obj->id_prefix, "DEFAULT-", "id_prefix: default");
594
595     # requires_moderation
596     $illrq_obj->status('NEW')->store;
597     is($illrq_obj->requires_moderation, undef, "requires_moderation: No.");
598     $illrq_obj->status('CANCREQ')->store;
599     is($illrq_obj->requires_moderation, 'CANCREQ', "requires_moderation: Yes.");
600
601     $schema->storage->txn_rollback;
602 };
603
604
605 subtest 'Censorship' => sub {
606
607     plan tests => 2;
608
609     $schema->storage->txn_begin;
610
611     # Build infrastructure
612     my $backend = Test::MockObject->new;
613     $backend->set_isa('Koha::Illbackends::Mock');
614     $backend->set_always('name', 'Mock');
615
616     my $config = Test::MockObject->new;
617     $config->set_always('backend_dir', "/tmp");
618
619     my $illrq = $builder->build({source => 'Illrequest'});
620     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
621     $illrq_obj->_config($config);
622     $illrq_obj->_backend($backend);
623
624     $config->set_always('censorship', { censor_notes_staff => 1, censor_reply_date => 0 });
625
626     my $censor_out = $illrq_obj->_censor({ foo => 'bar', baz => 564 });
627     is_deeply($censor_out, { foo => 'bar', baz => 564, display_reply_date => 1 },
628               "_censor: not OPAC, reply_date = 1");
629
630     $censor_out = $illrq_obj->_censor({ foo => 'bar', baz => 564, opac => 1 });
631     is_deeply($censor_out, {
632         foo => 'bar', baz => 564, censor_notes_staff => 1,
633         display_reply_date => 1, opac => 1
634     }, "_censor: notes_staff = 0, reply_date = 0");
635
636     $schema->storage->txn_rollback;
637 };
638
639 subtest 'Checking Limits' => sub {
640
641     plan tests => 30;
642
643     $schema->storage->txn_begin;
644
645     # Build infrastructure
646     my $backend = Test::MockObject->new;
647     $backend->set_isa('Koha::Illbackends::Mock');
648     $backend->set_always('name', 'Mock');
649
650     my $config = Test::MockObject->new;
651     $config->set_always('backend_dir', "/tmp");
652
653     my $illrq = $builder->build({source => 'Illrequest'});
654     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
655     $illrq_obj->_config($config);
656     $illrq_obj->_backend($backend);
657
658     # getLimits
659     $config->set_series('getLimitRules',
660                         { CPL => { count => 1, method => 'test' } },
661                         { default => { count => 0, method => 'active' } });
662     is_deeply($illrq_obj->getLimits({ type => 'branch', value => "CPL" }),
663               { count => 1, method => 'test' },
664               "getLimits: by value.");
665     is_deeply($illrq_obj->getLimits({ type => 'branch' }),
666               { count => 0, method => 'active' },
667               "getLimits: by default.");
668     is_deeply($illrq_obj->getLimits({ type => 'branch', value => "CPL" }),
669               { count => -1, method => 'active' },
670               "getLimits: by hard-coded.");
671
672     #_limit_counter
673     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
674        1, "_limit_counter: Initial branch annual count.");
675     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
676        1, "_limit_counter: Initial branch active count.");
677     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
678        1, "_limit_counter: Initial patron annual count.");
679     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
680        1, "_limit_counter: Initial patron active count.");
681     $builder->build({
682         source => 'Illrequest',
683         value => {
684             branchcode => $illrq_obj->branchcode,
685             borrowernumber => $illrq_obj->borrowernumber,
686         }
687     });
688     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
689        2, "_limit_counter: Add a qualifying request for branch annual count.");
690     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
691        2, "_limit_counter: Add a qualifying request for branch active count.");
692     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
693        2, "_limit_counter: Add a qualifying request for patron annual count.");
694     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
695        2, "_limit_counter: Add a qualifying request for patron active count.");
696     $builder->build({
697         source => 'Illrequest',
698         value => {
699             branchcode => $illrq_obj->branchcode,
700             borrowernumber => $illrq_obj->borrowernumber,
701             placed => "2005-05-31",
702         }
703     });
704     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
705        2, "_limit_counter: Add an out-of-date branch request.");
706     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
707        3, "_limit_counter: Add a qualifying request for branch active count.");
708     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
709        2, "_limit_counter: Add an out-of-date patron request.");
710     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
711        3, "_limit_counter: Add a qualifying request for patron active count.");
712     $builder->build({
713         source => 'Illrequest',
714         value => {
715             branchcode => $illrq_obj->branchcode,
716             borrowernumber => $illrq_obj->borrowernumber,
717             status => "COMP",
718         }
719     });
720     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
721        3, "_limit_counter: Add a qualifying request for branch annual count.");
722     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
723        3, "_limit_counter: Add a completed request for branch active count.");
724     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
725        3, "_limit_counter: Add a qualifying request for patron annual count.");
726     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
727        3, "_limit_counter: Add a completed request for patron active count.");
728
729     # check_limits:
730
731     # We've tested _limit_counter, so all we need to test here is whether the
732     # current counts of 3 for each work as they should against different
733     # configuration declarations.
734
735     # No limits
736     $config->set_always('getLimitRules', undef);
737     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
738                                  librarycode => $illrq_obj->branchcode}),
739        1, "check_limits: no configuration => no limits.");
740
741     # Branch tests
742     $config->set_always('getLimitRules',
743                         { $illrq_obj->branchcode => { count => 1, method => 'active' } });
744     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
745                                  librarycode => $illrq_obj->branchcode}),
746        0, "check_limits: branch active limit exceeded.");
747     $config->set_always('getLimitRules',
748                         { $illrq_obj->branchcode => { count => 1, method => 'annual' } });
749     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
750                                  librarycode => $illrq_obj->branchcode}),
751        0, "check_limits: branch annual limit exceeded.");
752     $config->set_always('getLimitRules',
753                         { $illrq_obj->branchcode => { count => 4, method => 'active' } });
754     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
755                                  librarycode => $illrq_obj->branchcode}),
756        1, "check_limits: branch active limit OK.");
757     $config->set_always('getLimitRules',
758                         { $illrq_obj->branchcode => { count => 4, method => 'annual' } });
759     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
760                                  librarycode => $illrq_obj->branchcode}),
761        1, "check_limits: branch annual limit OK.");
762
763     # Patron tests
764     $config->set_always('getLimitRules',
765                         { $illrq_obj->patron->categorycode => { count => 1, method => 'active' } });
766     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
767                                  librarycode => $illrq_obj->branchcode}),
768        0, "check_limits: patron category active limit exceeded.");
769     $config->set_always('getLimitRules',
770                         { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } });
771     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
772                                  librarycode => $illrq_obj->branchcode}),
773        0, "check_limits: patron category annual limit exceeded.");
774     $config->set_always('getLimitRules',
775                         { $illrq_obj->patron->categorycode => { count => 4, method => 'active' } });
776     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
777                                  librarycode => $illrq_obj->branchcode}),
778        1, "check_limits: patron category active limit OK.");
779     $config->set_always('getLimitRules',
780                         { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } });
781     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
782                                  librarycode => $illrq_obj->branchcode}),
783        1, "check_limits: patron category annual limit OK.");
784
785     # One rule cancels the other
786     $config->set_series('getLimitRules',
787                         # Branch rules allow request
788                         { $illrq_obj->branchcode => { count => 4, method => 'active' } },
789                         # Patron rule forbids it
790                         { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } });
791     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
792                                  librarycode => $illrq_obj->branchcode}),
793        0, "check_limits: patron category veto overrides branch OK.");
794     $config->set_series('getLimitRules',
795                         # Branch rules allow request
796                         { $illrq_obj->branchcode => { count => 1, method => 'active' } },
797                         # Patron rule forbids it
798                         { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } });
799     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
800                                  librarycode => $illrq_obj->branchcode}),
801        0, "check_limits: branch veto overrides patron category OK.");
802
803     $schema->storage->txn_rollback;
804 };
805
806 subtest 'TO_JSON() tests' => sub {
807
808     plan tests => 10;
809
810     my $illreqmodule = Test::MockModule->new('Koha::Illrequest');
811
812     # Mock ->capabilities
813     $illreqmodule->mock( 'capabilities', sub { return 'capable'; } );
814
815     # Mock ->metadata
816     $illreqmodule->mock( 'metadata', sub { return 'metawhat?'; } );
817
818     $schema->storage->txn_begin;
819
820     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
821     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
822     my $illreq  = $builder->build_object(
823         {
824             class => 'Koha::Illrequests',
825             value => {
826                 branchcode     => $library->branchcode,
827                 borrowernumber => $patron->borrowernumber
828             }
829         }
830     );
831     my $illreq_json = $illreq->TO_JSON;
832     is( $illreq_json->{patron},
833         undef, '%embed not passed, no \'patron\' attribute' );
834     is( $illreq_json->{metadata},
835         undef, '%embed not passed, no \'metadata\' attribute' );
836     is( $illreq_json->{capabilities},
837         undef, '%embed not passed, no \'capabilities\' attribute' );
838     is( $illreq_json->{branch},
839         undef, '%embed not passed, no \'branch\' attribute' );
840
841     $illreq_json = $illreq->TO_JSON(
842         { patron => 1, metadata => 1, capabilities => 1, branch => 1 } );
843     is( $illreq_json->{patron}->{firstname},
844         $patron->firstname,
845         '%embed passed, \'patron\' attribute correct (firstname)' );
846     is( $illreq_json->{patron}->{surname},
847         $patron->surname,
848         '%embed passed, \'patron\' attribute correct (surname)' );
849     is( $illreq_json->{patron}->{cardnumber},
850         $patron->cardnumber,
851         '%embed passed, \'patron\' attribute correct (cardnumber)' );
852     is( $illreq_json->{metadata},
853         'metawhat?', '%embed passed, \'metadata\' attribute correct' );
854     is( $illreq_json->{capabilities},
855         'capable', '%embed passed, \'capabilities\' attribute correct' );
856     is( $illreq_json->{branch}->{branchcode},
857         $library->branchcode, '%embed not passed, no \'branch\' attribute' );
858
859     $schema->storage->txn_rollback;
860 };