Bug 19841: Unit tests
[koha.git] / t / db_dependent / Members.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 Test::More tests => 64;
21 use Test::MockModule;
22 use Test::Exception;
23
24 use Data::Dumper qw/Dumper/;
25 use C4::Context;
26 use Koha::Database;
27 use Koha::Holds;
28 use Koha::List::Patron;
29 use Koha::Patrons;
30
31 use t::lib::Mocks;
32 use t::lib::TestBuilder;
33
34 BEGIN {
35         use_ok('C4::Members');
36 }
37
38 my $schema = Koha::Database->schema;
39 $schema->storage->txn_begin;
40 my $builder = t::lib::TestBuilder->new;
41 my $dbh = C4::Context->dbh;
42
43 # Remove invalid guarantorid's as long as we have no FK
44 $dbh->do("UPDATE borrowers b1 LEFT JOIN borrowers b2 ON b2.borrowernumber=b1.guarantorid SET b1.guarantorid=NULL where b1.guarantorid IS NOT NULL AND b2.borrowernumber IS NULL");
45
46 my $library1 = $builder->build({
47     source => 'Branch',
48 });
49 my $library2 = $builder->build({
50     source => 'Branch',
51 });
52 my $patron_category = $builder->build({ source => 'Category' });
53 my $CARDNUMBER   = 'TESTCARD01';
54 my $FIRSTNAME    = 'Marie';
55 my $SURNAME      = 'Mcknight';
56 my $BRANCHCODE   = $library1->{branchcode};
57
58 my $CHANGED_FIRSTNAME = "Marry Ann";
59 my $EMAIL             = "Marie\@email.com";
60 my $EMAILPRO          = "Marie\@work.com";
61 my $PHONE             = "555-12123";
62
63 # XXX should be randomised and checked against the database
64 my $IMPOSSIBLE_CARDNUMBER = "XYZZZ999";
65
66 #my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter)= @_;
67 my @USERENV = (
68     1,
69     'test',
70     'MASTERTEST',
71     'Test',
72     'Test',
73     't',
74     'Test',
75     0,
76 );
77 my $BRANCH_IDX = 5;
78
79 C4::Context->_new_userenv ('DUMMY_SESSION_ID');
80 C4::Context->set_userenv ( @USERENV );
81
82 my $userenv = C4::Context->userenv
83   or BAIL_OUT("No userenv");
84
85 # Make a borrower for testing
86 my %data = (
87     cardnumber => $CARDNUMBER,
88     firstname =>  $FIRSTNAME . q{ },
89     surname => $SURNAME,
90     categorycode => $patron_category->{categorycode},
91     branchcode => $BRANCHCODE,
92     dateofbirth => '',
93     dateexpiry => '9999-12-31',
94     userid => 'tomasito'
95 );
96
97 my $addmem=AddMember(%data);
98 ok($addmem, "AddMember()");
99
100 my $member = Koha::Patrons->find( { cardnumber => $CARDNUMBER } )
101   or BAIL_OUT("Cannot read member with card $CARDNUMBER");
102 $member = $member->unblessed;
103
104 ok ( $member->{firstname}    eq $FIRSTNAME    &&
105      $member->{surname}      eq $SURNAME      &&
106      $member->{categorycode} eq $patron_category->{categorycode} &&
107      $member->{branchcode}   eq $BRANCHCODE
108      , "Got member")
109   or diag("Mismatching member details: ".Dumper(\%data, $member));
110
111 is($member->{dateofbirth}, undef, "Empty dates handled correctly");
112
113 $member->{firstname} = $CHANGED_FIRSTNAME . q{ };
114 $member->{email}     = $EMAIL;
115 $member->{phone}     = $PHONE;
116 $member->{emailpro}  = $EMAILPRO;
117 ModMember(%$member);
118 my $changedmember = Koha::Patrons->find( { cardnumber => $CARDNUMBER } )->unblessed;
119 ok ( $changedmember->{firstname} eq $CHANGED_FIRSTNAME &&
120      $changedmember->{email}     eq $EMAIL             &&
121      $changedmember->{phone}     eq $PHONE             &&
122      $changedmember->{emailpro}  eq $EMAILPRO
123      , "Member Changed")
124   or diag("Mismatching member details: ".Dumper($member, $changedmember));
125
126 t::lib::Mocks::mock_preference( 'CardnumberLength', '' );
127 C4::Context->clear_syspref_cache();
128
129 my $checkcardnum=C4::Members::checkcardnumber($CARDNUMBER, "");
130 is ($checkcardnum, "1", "Card No. in use");
131
132 $checkcardnum=C4::Members::checkcardnumber($IMPOSSIBLE_CARDNUMBER, "");
133 is ($checkcardnum, "0", "Card No. not used");
134
135 t::lib::Mocks::mock_preference( 'CardnumberLength', '4' );
136 C4::Context->clear_syspref_cache();
137
138 $checkcardnum=C4::Members::checkcardnumber($IMPOSSIBLE_CARDNUMBER, "");
139 is ($checkcardnum, "2", "Card number is too long");
140
141
142
143 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
144 C4::Context->clear_syspref_cache();
145
146 my $notice_email = GetNoticeEmailAddress($member->{'borrowernumber'});
147 is ($notice_email, $EMAIL, "GetNoticeEmailAddress returns correct value when AutoEmailPrimaryAddress is off");
148
149 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
150 C4::Context->clear_syspref_cache();
151
152 $notice_email = GetNoticeEmailAddress($member->{'borrowernumber'});
153 is ($notice_email, $EMAILPRO, "GetNoticeEmailAddress returns correct value when AutoEmailPrimaryAddress is emailpro");
154
155 # Check_Userid tests
156 %data = (
157     cardnumber   => "123456789",
158     firstname    => "Tomasito",
159     surname      => "None",
160     categorycode => $patron_category->{categorycode},
161     branchcode   => $library2->{branchcode},
162     dateofbirth  => '',
163     debarred     => '',
164     dateexpiry   => '',
165     dateenrolled => '',
166 );
167 # Add a new borrower
168 my $borrowernumber = AddMember( %data );
169 is( Check_Userid( 'tomasito.non', $borrowernumber ), 1,
170     'recently created userid -> unique (borrowernumber passed)' );
171 is( Check_Userid( 'tomasitoxxx', $borrowernumber ), 1,
172     'non-existent userid -> unique (borrowernumber passed)' );
173 is( Check_Userid( 'tomasito.none', '' ), 0,
174     'userid exists (blank borrowernumber)' );
175 is( Check_Userid( 'tomasitoxxx', '' ), 1,
176     'non-existent userid -> unique (blank borrowernumber)' );
177
178 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
179 is( $borrower->{dateofbirth}, undef, 'AddMember should undef dateofbirth if empty string is given');
180 is( $borrower->{debarred}, undef, 'AddMember should undef debarred if empty string is given');
181 isnt( $borrower->{dateexpiry}, '0000-00-00', 'AddMember should not set dateexpiry to 0000-00-00 if empty string is given');
182 isnt( $borrower->{dateenrolled}, '0000-00-00', 'AddMember should not set dateenrolled to 0000-00-00 if empty string is given');
183
184 ModMember( borrowernumber => $borrowernumber, dateofbirth => '', debarred => '', dateexpiry => '', dateenrolled => '' );
185 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
186 is( $borrower->{dateofbirth}, undef, 'ModMember should undef dateofbirth if empty string is given');
187 is( $borrower->{debarred}, undef, 'ModMember should undef debarred if empty string is given');
188 isnt( $borrower->{dateexpiry}, '0000-00-00', 'ModMember should not set dateexpiry to 0000-00-00 if empty string is given');
189 isnt( $borrower->{dateenrolled}, '0000-00-00', 'ModMember should not set dateenrolled to 0000-00-00 if empty string is given');
190
191 ModMember( borrowernumber => $borrowernumber, dateofbirth => '1970-01-01', debarred => '2042-01-01', dateexpiry => '9999-12-31', dateenrolled => '2015-09-06' );
192 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
193 is( $borrower->{dateofbirth}, '1970-01-01', 'ModMember should correctly set dateofbirth if a valid date is given');
194 is( $borrower->{debarred}, '2042-01-01', 'ModMember should correctly set debarred if a valid date is given');
195 is( $borrower->{dateexpiry}, '9999-12-31', 'ModMember should correctly set dateexpiry if a valid date is given');
196 is( $borrower->{dateenrolled}, '2015-09-06', 'ModMember should correctly set dateenrolled if a valid date is given');
197
198 # Add a new borrower with the same userid but different cardnumber
199 $data{ cardnumber } = "987654321";
200 my $new_borrowernumber = AddMember( %data );
201 is( Check_Userid( 'tomasito.none', '' ), 0,
202     'userid not unique (blank borrowernumber)' );
203 is( Check_Userid( 'tomasito.none', $new_borrowernumber ), 0,
204     'userid not unique (second borrowernumber passed)' );
205 $borrower = Koha::Patrons->find( $new_borrowernumber )->unblessed;
206 ok( $borrower->{userid} ne 'tomasito', "Borrower with duplicate userid has new userid generated" );
207
208 $data{ cardnumber } = "234567890";
209 $data{userid} = 'a_user_id';
210 $borrowernumber = AddMember( %data );
211 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
212 is( $borrower->{userid}, $data{userid}, 'AddMember should insert the given userid' );
213
214 subtest 'ModMember should not update userid if not true' => sub {
215     plan tests => 3;
216     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => '' );
217     $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
218     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an empty string' );
219     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => 0 );
220     $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
221     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an 0');
222     ModMember( borrowernumber => $borrowernumber, firstname => 'Tomas', userid => undef );
223     $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
224     is ( $borrower->{userid}, $data{userid}, 'ModMember should not update the userid with an undefined value');
225 };
226
227 #Regression tests for bug 10612
228 my $library3 = $builder->build({
229     source => 'Branch',
230 });
231 $builder->build({
232         source => 'Category',
233         value => {
234             categorycode         => 'STAFFER',
235             description          => 'Staff dont batch del',
236             category_type        => 'S',
237         },
238 });
239
240 $builder->build({
241         source => 'Category',
242         value => {
243             categorycode         => 'CIVILIAN',
244             description          => 'Civilian batch del',
245             category_type        => 'A',
246         },
247 });
248
249 $builder->build({
250         source => 'Category',
251         value => {
252             categorycode         => 'KIDclamp',
253             description          => 'Kid to be guaranteed',
254             category_type        => 'C',
255         },
256 });
257
258 my $borrower1 = $builder->build({
259         source => 'Borrower',
260         value  => {
261             categorycode=>'STAFFER',
262             branchcode => $library3->{branchcode},
263             dateexpiry => '2015-01-01',
264             guarantorid=> undef,
265         },
266 });
267 my $bor1inlist = $borrower1->{borrowernumber};
268 my $borrower2 = $builder->build({
269         source => 'Borrower',
270         value  => {
271             categorycode=>'STAFFER',
272             branchcode => $library3->{branchcode},
273             dateexpiry => '2015-01-01',
274             guarantorid=> undef,
275         },
276 });
277
278 my $guarantee = $builder->build({
279         source => 'Borrower',
280         value  => {
281             categorycode=>'KIDclamp',
282             branchcode => $library3->{branchcode},
283             dateexpiry => '2015-01-01',
284             guarantorid=> undef, # will be filled later
285         },
286 });
287
288 my $bor2inlist = $borrower2->{borrowernumber};
289
290 $builder->build({
291         source => 'OldIssue',
292         value  => {
293             borrowernumber => $bor2inlist,
294             timestamp => '2016-01-01',
295         },
296 });
297
298 # The following calls to GetBorrowersToExpunge are assuming that the pref
299 # IndependentBranches is off.
300 t::lib::Mocks::mock_preference('IndependentBranches', 0);
301
302 my $owner = AddMember (categorycode => 'STAFFER', branchcode => $library2->{branchcode} );
303 my $list1 = AddPatronList( { name => 'Test List 1', owner => $owner } );
304 my @listpatrons = ($bor1inlist, $bor2inlist);
305 AddPatronsToList(  { list => $list1, borrowernumbers => \@listpatrons });
306 my $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id() } );
307 is( scalar(@$patstodel),0,'No staff deleted from list of all staff');
308 ModMember( borrowernumber => $bor2inlist, categorycode => 'CIVILIAN' );
309 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
310 ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted from list');
311 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
312 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by branchcode and list');
313 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } );
314 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by expirationdate and list');
315 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
316 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by last issue date');
317
318 ModMember( borrowernumber => $bor1inlist, categorycode => 'CIVILIAN' );
319 ModMember( borrowernumber => $guarantee->{borrowernumber} ,guarantorid=>$bor1inlist );
320
321 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
322 ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted from list');
323 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
324 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by branchcode and list');
325 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } );
326 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by expirationdate and list');
327 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
328 ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by last issue date');
329 ModMember( borrowernumber => $guarantee->{borrowernumber}, guarantorid=>'' );
330
331 $builder->build({
332         source => 'Issue',
333         value  => {
334             borrowernumber => $bor2inlist,
335         },
336 });
337 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
338 is( scalar(@$patstodel),1,'Borrower with issue not deleted from list');
339 $patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } );
340 is( scalar(@$patstodel),1,'Borrower with issue not deleted by branchcode and list');
341 $patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } );
342 is( scalar(@$patstodel),1,'Borrower with issue not deleted by category_code and list');
343 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } );
344 is( scalar(@$patstodel),1,'Borrower with issue not deleted by expiration_date and list');
345 $builder->schema->resultset( 'Issue' )->delete_all;
346 $patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} );
347 ok( scalar(@$patstodel)== 2,'Borrowers without issue deleted from list');
348 $patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } );
349 is( scalar(@$patstodel),2,'Borrowers without issues deleted by category_code and list');
350 $patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } );
351 is( scalar(@$patstodel),2,'Borrowers without issues deleted by expiration_date and list');
352 $patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } );
353 is( scalar(@$patstodel),2,'Borrowers without issues deleted by last issue date');
354
355 # Test GetBorrowersToExpunge and TrackLastPatronActivity
356 $dbh->do(q|UPDATE borrowers SET lastseen=NULL|);
357 $builder->build({ source => 'Borrower', value => { lastseen => '2016-01-01 01:01:01', categorycode => 'CIVILIAN', guarantorid => undef } } );
358 $builder->build({ source => 'Borrower', value => { lastseen => '2016-02-02 02:02:02', categorycode => 'CIVILIAN', guarantorid => undef } } );
359 $builder->build({ source => 'Borrower', value => { lastseen => '2016-03-03 03:03:03', categorycode => 'CIVILIAN', guarantorid => undef } } );
360 $patstodel = GetBorrowersToExpunge( { last_seen => '1999-12-12' });
361 is( scalar @$patstodel, 0, 'TrackLastPatronActivity - 0 patrons must be deleted' );
362 $patstodel = GetBorrowersToExpunge( { last_seen => '2016-02-15' });
363 is( scalar @$patstodel, 2, 'TrackLastPatronActivity - 2 patrons must be deleted' );
364 $patstodel = GetBorrowersToExpunge( { last_seen => '2016-04-04' });
365 is( scalar @$patstodel, 3, 'TrackLastPatronActivity - 3 patrons must be deleted' );
366 my $patron2 = $builder->build({ source => 'Borrower', value => { lastseen => undef } });
367 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
368 Koha::Patrons->find( $patron2->{borrowernumber} )->track_login;
369 is( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should not be changed' );
370 Koha::Patrons->find( $patron2->{borrowernumber} )->track_login({ force => 1 });
371 isnt( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should be changed now' );
372
373 # Regression tests for BZ13502
374 ## Remove all entries with userid='' (should be only 1 max)
375 $dbh->do(q|DELETE FROM borrowers WHERE userid = ''|);
376 ## And create a patron with a userid=''
377 $borrowernumber = AddMember( categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} );
378 $dbh->do(q|UPDATE borrowers SET userid = '' WHERE borrowernumber = ?|, undef, $borrowernumber);
379 # Create another patron and verify the userid has been generated
380 $borrowernumber = AddMember( categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} );
381 ok( $borrowernumber > 0, 'AddMember should have inserted the patron even if no userid is given' );
382 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
383 ok( $borrower->{userid},  'A userid should have been generated correctly' );
384
385 # Regression tests for BZ12226
386 is( Check_Userid( C4::Context->config('user'), '' ), 0,
387     'Check_Userid should return 0 for the DB user (Bug 12226)');
388
389 subtest 'GetMemberAccountRecords' => sub {
390
391     plan tests => 2;
392
393     my $borrowernumber = $builder->build({ source => 'Borrower' })->{ borrowernumber };
394     my $accountline_1  = $builder->build({
395         source => 'Accountline',
396         value  => {
397             borrowernumber    => $borrowernumber,
398             amountoutstanding => 64.60
399         }
400     });
401
402     my ($total,undef,undef) = GetMemberAccountRecords( $borrowernumber );
403     is( $total , 64.60, "Rounding works correctly in total calculation (single value)" );
404
405     my $accountline_2 = $builder->build({
406         source => 'Accountline',
407         value  => {
408             borrowernumber    => $borrowernumber,
409             amountoutstanding => 10.65
410         }
411     });
412
413     ($total,undef,undef) = GetMemberAccountRecords( $borrowernumber );
414     is( $total , 75.25, "Rounding works correctly in total calculation (multiple values)" );
415
416 };
417
418 subtest 'GetMemberAccountBalance' => sub {
419
420     plan tests => 6;
421
422     my $members_mock = new Test::MockModule('C4::Members');
423     $members_mock->mock( 'GetMemberAccountRecords', sub {
424         my ($borrowernumber) = @_;
425         if ($borrowernumber) {
426             my @accountlines = (
427             { amountoutstanding => '7', accounttype => 'Rent' },
428             { amountoutstanding => '5', accounttype => 'Res' },
429             { amountoutstanding => '3', accounttype => 'Pay' } );
430             return ( 15, \@accountlines );
431         }
432         else {
433             my @accountlines;
434             return ( 0, \@accountlines );
435         }
436     });
437
438     # do not count holds charges
439     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge', '1' );
440     t::lib::Mocks::mock_preference( 'ManInvInNoissuesCharge', '0' );
441     my ($total, $total_minus_charges,
442         $other_charges) = C4::Members::GetMemberAccountBalance(123);
443     is( $total, 15 , "Total calculated correctly");
444     is( $total_minus_charges, 15, "Holds charges are not count if HoldsInNoissuesCharge=1");
445     is( $other_charges, 0, "Holds charges are not considered if HoldsInNoissuesCharge=1");
446
447     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge', '0' );
448     ($total, $total_minus_charges,
449         $other_charges) = C4::Members::GetMemberAccountBalance(123);
450     is( $total, 15 , "Total calculated correctly");
451     is( $total_minus_charges, 10, "Holds charges are count if HoldsInNoissuesCharge=0");
452     is( $other_charges, 5, "Holds charges are considered if HoldsInNoissuesCharge=1");
453 };
454
455 subtest 'purgeSelfRegistration' => sub {
456     plan tests => 2;
457
458     #purge unverified
459     my $d=360;
460     C4::Members::DeleteUnverifiedOpacRegistrations($d);
461     foreach(1..3) {
462         $dbh->do("INSERT INTO borrower_modifications (timestamp, borrowernumber, verification_token) VALUES ('2014-01-01 01:02:03',0,?)", undef, (scalar localtime)."_$_");
463     }
464     is( C4::Members::DeleteUnverifiedOpacRegistrations($d), 3, 'Test for DeleteUnverifiedOpacRegistrations' );
465
466     #purge members in temporary category
467     my $c= 'XYZ';
468     $dbh->do("INSERT IGNORE INTO categories (categorycode) VALUES ('$c')");
469     t::lib::Mocks::mock_preference('PatronSelfRegistrationDefaultCategory', $c );
470     t::lib::Mocks::mock_preference('PatronSelfRegistrationExpireTemporaryAccountsDelay', 360);
471     C4::Members::DeleteExpiredOpacRegistrations();
472     $dbh->do("INSERT INTO borrowers (surname, address, city, branchcode, categorycode, dateenrolled) VALUES ('Testaabbcc', 'Street 1', 'CITY', ?, '$c', '2014-01-01 01:02:03')", undef, $library1->{branchcode});
473     is( C4::Members::DeleteExpiredOpacRegistrations(), 1, 'Test for DeleteExpiredOpacRegistrations');
474 };
475
476 sub _find_member {
477     my ($resultset) = @_;
478     my $found = $resultset && grep( { $_->{cardnumber} && $_->{cardnumber} eq $CARDNUMBER } @$resultset );
479     return $found;
480 }
481
482 # Regression tests for BZ15343
483 my $password="";
484 ( $borrowernumber, $password ) = AddMember_Opac(surname=>"Dick",firstname=>'Philip',branchcode => $library2->{branchcode});
485 is( $password =~ /^[a-zA-Z]{10}$/ , 1, 'Test for autogenerated password if none submitted');
486 ( $borrowernumber, $password ) = AddMember_Opac(surname=>"Deckard",firstname=>"Rick",password=>"Nexus-6",branchcode => $library2->{branchcode});
487 is( $password eq "Nexus-6", 1, 'Test password used if submitted');
488 $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
489 my $hashed_up =  Koha::AuthUtils::hash_password("Nexus-6", $borrower->{password});
490 is( $borrower->{password} eq $hashed_up, 1, 'Check password hash equals hash of submitted password' );
491
492 subtest 'Trivial test for AddMember_Auto' => sub {
493     plan tests => 3;
494     my $members_mock = Test::MockModule->new( 'C4::Members' );
495     $members_mock->mock( 'fixup_cardnumber', sub { 12345; } );
496     my $library = $builder->build({ source => 'Branch' });
497     my $category = $builder->build({ source => 'Category' });
498     my %borr = AddMember_Auto( surname=> 'Dick3', firstname => 'Philip', branchcode => $library->{branchcode}, categorycode => $category->{categorycode}, password => '34567890' );
499     ok( $borr{borrowernumber}, 'Borrower hash contains borrowernumber' );
500     is( $borr{cardnumber}, 12345, 'Borrower hash contains cardnumber' );
501     my $patron = Koha::Patrons->find( $borr{borrowernumber} );
502     isnt( $patron, undef, 'Patron found' );
503 };
504
505 $schema->storage->txn_rollback;
506
507 subtest 'AddMember (invalid categorycode) tests' => sub {
508     plan tests => 1;
509
510     $schema->storage->txn_begin;
511
512     my $category    = $builder->build_object({ class => 'Koha::Patron::Categories' });
513     my $category_id = $category->id;
514     # Remove category to make sure the id is not on the DB
515     $category->delete;
516
517     my $patron_data = {
518         categorycode => $category_id
519     };
520
521     throws_ok
522         { AddMember( %{ $patron_data } ); }
523         'Koha::Exceptions::BadParameter',
524         'AddMember raises an exception on invalid categorycode';
525
526     $schema->storage->txn_rollback;
527 };