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