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