Bug 23219: (QA Follow up) Cancel patrons holds when patron delete
[koha-equinox.git] / t / db_dependent / Koha / Patrons.t
index f16c73f..b98037a 100644 (file)
 
 use Modern::Perl;
 
-use Test::More tests => 33;
+use Test::More tests => 40;
 use Test::Warn;
 use Test::Exception;
+use Test::MockModule;
 use Time::Fake;
 use DateTime;
 use JSON;
@@ -31,6 +32,7 @@ use C4::Biblio;
 use C4::Auth qw(checkpw_hash);
 
 use Koha::Holds;
+use Koha::Old::Holds;
 use Koha::Patrons;
 use Koha::Patron::Categories;
 use Koha::Database;
@@ -67,8 +69,7 @@ my $new_patron_2  = Koha::Patron->new(
     }
 )->store;
 
-C4::Context->_new_userenv('xxx');
-set_logged_in_user( $new_patron_1 );
+t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
 
 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
 
@@ -207,31 +208,6 @@ subtest 'has_overdues' => sub {
     $issue->delete();
 };
 
-subtest 'update_password' => sub {
-    plan tests => 7;
-
-    t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
-    my $original_userid   = $new_patron_1->userid;
-    my $original_password = $new_patron_1->password;
-    warning_like { $retrieved_patron_1->update_password( $new_patron_2->userid, 'another_password' ) }
-    qr{Duplicate entry},
-      'Koha::Patron->update_password should warn if the userid is already used by another patron';
-    is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid,   $original_userid,   'Koha::Patron->update_password should not have updated the userid' );
-    is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, $original_password, 'Koha::Patron->update_password should not have updated the userid' );
-
-    my $digest = $retrieved_patron_1->update_password( 'another_nonexistent_userid_1', 'another_password' );
-    is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid,   'another_nonexistent_userid_1', 'Koha::Patron->update_password should have updated the userid' );
-    is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, $digest,             'Koha::Patron->update_password should have updated the password' );
-
-    my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
-    is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should have logged' );
-
-    t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
-    $retrieved_patron_1->update_password( 'yet_another_nonexistent_userid_1', 'another_password' );
-    $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
-    is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should not have logged' );
-};
-
 subtest 'is_expired' => sub {
     plan tests => 4;
     my $patron = $builder->build({ source => 'Borrower' });
@@ -288,16 +264,16 @@ subtest 'is_going_to_expire' => sub {
 
 
 subtest 'renew_account' => sub {
-    plan tests => 36;
+    plan tests => 48;
 
-    for my $date ( '2016-03-31', '2016-11-30', dt_from_string() ) {
+    for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
         my $dt = dt_from_string( $date, 'iso' );
         Time::Fake->offset( $dt->epoch );
         my $a_month_ago                = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
         my $a_year_later               = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
-        my $a_year_later_minus_a_month = $dt->clone->add( months => 11, end_of_month => 'limit' )->truncate( to => 'day' );
+        my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
         my $a_month_later              = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
-        my $a_year_later_plus_a_month  = $dt->clone->add( months => 13, end_of_month => 'limit' )->truncate( to => 'day' );
+        my $a_year_later_plus_a_month  = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
         my $patron_category = $builder->build(
             {   source => 'Category',
                 value  => {
@@ -394,7 +370,7 @@ subtest "move_to_deleted" => sub {
 };
 
 subtest "delete" => sub {
-    plan tests => 5;
+    plan tests => 6;
     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
     my $patron           = $builder->build( { source => 'Borrower' } );
     my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
@@ -414,6 +390,8 @@ subtest "delete" => sub {
 
     is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
 
+    is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
+
     is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's holds| );
 
     is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
@@ -423,16 +401,27 @@ subtest "delete" => sub {
 };
 
 subtest 'Koha::Patrons->delete' => sub {
-    plan tests => 3;
+    plan tests => 4;
+
+    my $mod_patron = Test::MockModule->new( 'Koha::Patron' );
+    my $moved_to_deleted = 0;
+    $mod_patron->mock( 'move_to_deleted', sub { $moved_to_deleted++; } );
+
     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
     my $id1 = $patron1->borrowernumber;
     my $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
     is( $set->count, 2, 'Two patrons found as expected' );
-    my $count1 = $schema->resultset('Deletedborrower')->count;
-    is( $set->delete({ move => 1 }), 1, 'Two patrons deleted' );
-    my $count2 = $schema->resultset('Deletedborrower')->count;
-    is( $count2, $count1 + 2, 'Patrons moved to deletedborrowers' );
+    is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
+    is( $moved_to_deleted, 2, 'Patrons moved to deletedborrowers' );
+
+    # Add again, test if we can raise an exception
+    $mod_patron->mock( 'delete', sub { return -1; } );
+    $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
+    $id1 = $patron1->borrowernumber;
+    $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
+    throws_ok { $set->delete } 'Koha::Exceptions::Patron::FailedDelete',
+        'Exception raised for deleting patron';
 };
 
 subtest 'add_enrolment_fee_if_needed' => sub {
@@ -549,8 +538,7 @@ subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
     # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
     $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
 
-    my $module = new Test::MockModule('C4::Context');
-    $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
+    t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
 
     AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
     AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
@@ -583,7 +571,6 @@ subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
     # Clean stuffs
     Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
     $patron->delete;
-    $module->unmock('userenv');
 };
 
 subtest 'get_routing_lists' => sub {
@@ -655,6 +642,64 @@ subtest 'get_age' => sub {
     $patron->delete;
 };
 
+subtest 'is_valid_age' => sub {
+    plan tests => 10;
+
+    my $today = dt_from_string;
+
+    my $category = $builder->build({
+        source => 'Category',
+        value => {
+            categorycode        => 'AGE_5_10',
+            dateofbirthrequired => 5,
+            upperagelimit       => 10
+        }
+    });
+    $category = Koha::Patron::Categories->find( $category->{categorycode} );
+
+    my $patron = $builder->build({
+        source => 'Borrower',
+        value => {
+            categorycode        => 'AGE_5_10'
+        }
+    });
+    $patron = Koha::Patrons->find( $patron->{borrowernumber} );
+
+
+    $patron->dateofbirth( undef );
+    is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
+
+    $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1 ) );
+    is( $patron->is_valid_age, 0, 'Patron is 12, so the age is above allowed range 5-10 years');
+
+    $patron->dateofbirth( $today->clone->add( years => -3, months => -6, days => -1 ) );
+    is( $patron->is_valid_age, 0, 'Patron is 3, so the age is below allowed range 5-10 years');
+
+    $patron->dateofbirth( $today->clone->add( years => -7, months => -6, days => -1 ) );
+    is( $patron->is_valid_age, 1, 'Patron is 7, so the age perfectly suits allowed range 5-10 years');
+
+    $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 0 ) );
+    is( $patron->is_valid_age, 1, 'Patron celebrates the 5th birthday today, so the age is allowed for this category');
+
+    $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 1 ) );
+    is( $patron->is_valid_age, 0, 'Patron will celebrate the 5th birthday tomorrow, so the age is NOT allowed for this category');
+
+    $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => -1 ) );
+    is( $patron->is_valid_age, 1, 'Patron celebrated the 5th birthday yesterday, so the age is allowed for this category');
+
+    $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 0 ) );
+    is( $patron->is_valid_age, 0, 'Patron celebrate the 11th birthday today, so the age is NOT allowed for this category');
+
+    $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 1 ) );
+    is( $patron->is_valid_age, 1, 'Patron will celebrate the 11th birthday tomorrow, so the age is allowed for this category');
+
+    $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => -1 ) );
+    is( $patron->is_valid_age, 0, 'Patron celebrated the 11th birthday yesterday, so the age is NOT allowed for this category');
+
+    $patron->delete;
+    $category->delete;
+};
+
 subtest 'account' => sub {
     plan tests => 1;
 
@@ -832,25 +877,18 @@ subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
 
     # TODO create a subroutine in t::lib::Mocks
     my $branch = $builder->build({ source => 'Branch' });
-    my $userenv_patron = $builder->build({
-        source => 'Borrower',
-        value  => { branchcode => $branch->{branchcode} },
+    my $userenv_patron = $builder->build_object({
+        class  => 'Koha::Patrons',
+        value  => { branchcode => $branch->{branchcode}, flags => 0 },
     });
-    C4::Context->_new_userenv('DUMMY SESSION');
-    C4::Context->set_userenv(
-        $userenv_patron->{borrowernumber},
-        $userenv_patron->{userid},
-        'usercnum', 'First name', 'Surname',
-        $branch->{branchcode},
-        $branch->{branchname},
-        0,
-    );
+    t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
+
     my $anonymous = $builder->build( { source => 'Borrower', }, );
 
     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
 
     subtest 'patron privacy is 1 (default)' => sub {
-        plan tests => 8;
+        plan tests => 9;
 
         t::lib::Mocks::mock_preference('IndependentBranches', 0);
         my $patron = $builder->build(
@@ -891,8 +929,8 @@ subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
             }
         );
 
-        my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, undef, '2010-10-10' );
-        my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, undef, '2011-11-11' );
+        my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
+        my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
         is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
 
         my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
@@ -901,6 +939,9 @@ subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
 
+        $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
+        is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
+
         my $dbh = C4::Context->dbh;
         my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
         $sth->execute($item_1->{itemnumber});
@@ -930,7 +971,7 @@ subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
     };
 
     subtest 'patron privacy is 0 (forever)' => sub {
-        plan tests => 3;
+        plan tests => 2;
 
         t::lib::Mocks::mock_preference('IndependentBranches', 0);
         my $patron = $builder->build(
@@ -955,10 +996,8 @@ subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
             }
         );
 
-        my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
+        my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
         is( $returned, 1, 'The item should have been returned' );
-        my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
-        ok( $rows_affected > 0, 'AnonymiseIssueHistory should not return any error if success' );
 
         my $dbh = C4::Context->dbh;
         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
@@ -996,7 +1035,7 @@ subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
             }
         );
 
-        my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
+        my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
         is( $returned, 1, 'The item should have been returned' );
         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
@@ -1034,13 +1073,13 @@ subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
             }
         );
 
-        my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
+        my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
         is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
         Koha::Patrons->find( $patron->{borrowernumber})->delete;
     };
 
     Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
-    Koha::Patrons->find( $userenv_patron->{borrowernumber})->delete;
+    $userenv_patron->delete;
 
     # Reset IndependentBranches for further tests
     t::lib::Mocks::mock_preference('IndependentBranches', 0);
@@ -1096,27 +1135,27 @@ subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited
 
         my @branchcodes;
 
-        set_logged_in_user( $patron_11_1 );
+        t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
         @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
         is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
 
-        set_logged_in_user( $patron_11_2 );
+        t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
         @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
         is_deeply( \@branchcodes, [ sort ( $library_11->branchcode, $library_12->branchcode ) ], q|patron_11_2 has not view_borrower_infos_from_any_libraries => Can only see patron's from its group| );
 
-        set_logged_in_user( $patron_21 );
+        t::lib::Mocks::mock_userenv({ patron => $patron_21 });
         @branchcodes = $patron_21->libraries_where_can_see_patrons;
         is_deeply( \@branchcodes, [$library_21->branchcode], q|patron_21 has not view_borrower_infos_from_any_libraries => Can only see patron's from its group| );
     };
     subtest 'can_see_patron_infos' => sub {
         plan tests => 6;
 
-        set_logged_in_user( $patron_11_1 );
+        t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
         is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
         is( $patron_11_1->can_see_patron_infos( $patron_12 ),   1, q|patron_11_1 can see patron_12, from its group| );
         is( $patron_11_1->can_see_patron_infos( $patron_21 ),   1, q|patron_11_1 can see patron_11_2, from another group| );
 
-        set_logged_in_user( $patron_11_2 );
+        t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
         is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
         is( $patron_11_2->can_see_patron_infos( $patron_12 ),   1, q|patron_11_2 can see patron_12, from its group| );
         is( $patron_11_2->can_see_patron_infos( $patron_21 ),   0, q|patron_11_2 can NOT see patron_21, from another group| );
@@ -1124,16 +1163,16 @@ subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited
     subtest 'search_limited' => sub {
         plan tests => 6;
 
-        set_logged_in_user( $patron_11_1 );
+        t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
         my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
         is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
 
-        set_logged_in_user( $patron_11_2 );
+        t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
         is( Koha::Patrons->search_limited->count, 3, 'patron_12_1 is not allowed to see patrons from other groups, only patron_11_1, patron_11_2 and patron_12' );
 
-        set_logged_in_user( $patron_21 );
+        t::lib::Mocks::mock_userenv({ patron => $patron_21 });
         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
         is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
     };
@@ -1144,14 +1183,17 @@ subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited
 };
 
 subtest 'account_locked' => sub {
-    plan tests => 8;
+    plan tests => 13;
     my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
     for my $value ( undef, '', 0 ) {
         t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
+        $patron->login_attempts(0)->store;
         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
         $patron->login_attempts(1)->store;
         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
+        $patron->login_attempts(-1)->store;
+        is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
     }
 
     t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
@@ -1159,6 +1201,10 @@ subtest 'account_locked' => sub {
     is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
     $patron->login_attempts(3)->store;
     is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
+    $patron->login_attempts(4)->store;
+    is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
+    $patron->login_attempts(-1)->store;
+    is( $patron->account_locked, 1, 'Administrative lockout triggered' );
 
     $patron->delete;
 };
@@ -1273,8 +1319,7 @@ subtest 'get_overdues' => sub {
         }
     );
 
-    my $module = new Test::MockModule('C4::Context');
-    $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
+    t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
 
     AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
     AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
@@ -1299,7 +1344,7 @@ subtest 'get_overdues' => sub {
 };
 
 subtest 'userid_is_valid' => sub {
-    plan tests => 8;
+    plan tests => 9;
 
     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
     my $patron_category = $builder->build_object(
@@ -1319,6 +1364,7 @@ subtest 'userid_is_valid' => sub {
     my $expected_userid_patron_1 = 'tomasito.none';
     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
     my $patron_1       = Koha::Patrons->find($borrowernumber);
+    is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
 
     $patron_1->userid( 'tomasito.non' );
@@ -1418,12 +1464,61 @@ subtest 'generate_userid' => sub {
     $patron_2->delete;
 };
 
+subtest 'attributes' => sub {
+    plan tests => 2;
+
+    my $library1 = Koha::Library->new({
+        branchcode => 'LIBPATRON',
+        branchname => 'Library of testing patron',
+    })->store;
+
+    my $library2 = Koha::Library->new({
+        branchcode => 'LIBATTR',
+        branchname => 'Library for testing attribute',
+    })->store;
+
+    my $category = Koha::Patron::Category->new({
+        categorycode => 'CAT1',
+        description => 'Category 1',
+    })->store;
+
+    my $patron = Koha::Patron->new({
+        firstname => 'Patron',
+        surname => 'with attributes',
+        branchcode => 'LIBPATRON',
+        categorycode => 'CAT1',
+    })->store;
+
+    my $attribute_type1 = Koha::Patron::Attribute::Type->new({
+        code => 'CODE_A',
+        description => 'Code A desciption',
+    })->store;
+
+    my $attribute_type2 = Koha::Patron::Attribute::Type->new({
+        code => 'CODE_B',
+        description => 'Code A desciption',
+    })->store;
+
+    $attribute_type2->library_limits ( [ $library2->branchcode ] );
+
+    Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type1->code, attribute => 'value 1' } )->store();
+    Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type2->code, attribute => 'value 2' } )->store();
+
+    is( $patron->attributes->count, 1, 'There should be one attribute');
+
+    $attribute_type2->library_limits ( [ $library1->branchcode ] );
+
+    is( $patron->attributes->count, 2, 'There should be 2 attributes');
+
+    $patron->delete;
+};
+
 $nb_of_patrons = Koha::Patrons->search->count;
 $retrieved_patron_1->delete;
 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
 
-subtest 'Log cardnumber change' => sub {
-    plan tests => 3;
+subtest 'BorrowersLog tests' => sub {
+    plan tests => 4;
 
     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
@@ -1434,9 +1529,14 @@ subtest 'Log cardnumber change' => sub {
 
     my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
     my $log_info = from_json( $logs[0]->info );
-    is( $log_info->{cardnumber_replaced}->{new_cardnumber}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
-    is( $log_info->{cardnumber_replaced}->{previous_cardnumber}, $cardnumber, 'Got correct old cardnumber' );
-    is( scalar @logs, 2, 'With BorrowerLogs, Change in cardnumber should be logged, as well as general alert of patron mod.' );
+    is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
+    is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
+    is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
+
+    t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
+    $patron->track_login();
+    @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
+    is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
 };
 
 $schema->storage->txn_rollback;
@@ -1487,7 +1587,7 @@ subtest 'Test Koha::Patrons::merge' => sub {
 };
 
 subtest '->store' => sub {
-    plan tests => 3;
+    plan tests => 5;
     my $schema = Koha::Database->new->schema;
     $schema->storage->txn_begin;
 
@@ -1503,20 +1603,32 @@ subtest '->store' => sub {
         'Koha::Patron->store raises an exception on duplicate ID';
 
     # Test password
+    t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
     my $password = 'password';
-    $patron_1->update_password($patron_1->userid, $password);
+    $patron_1->set_password({ password => $password });
     like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
     my $digest = $patron_1->password;
     $patron_1->surname('xxx')->store;
     is( $patron_1->password, $digest, 'Password should not have changed on ->store');
 
+    # Test uppercasesurname
+    t::lib::Mocks::mock_preference( 'uppercasesurname', 1 );
+    my $surname = lc $patron_1->surname;
+    $patron_1->surname($surname)->store;
+    isnt( $patron_1->surname, $surname,
+        'Surname converts to uppercase on store.');
+    t::lib::Mocks::mock_preference( 'uppercasesurname', 0 );
+    $patron_1->surname($surname)->store;
+    is( $patron_1->surname, $surname,
+        'Surname remains unchanged on store.');
+
     $schema->storage->dbh->{PrintError} = $print_error;
     $schema->storage->txn_rollback;
 };
 
 subtest '->set_password' => sub {
 
-    plan tests => 12;
+    plan tests => 14;
 
     $schema->storage->txn_begin;
 
@@ -1527,28 +1639,32 @@ subtest '->set_password' => sub {
 
     # Password-length tests
     t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
-    throws_ok { $patron->set_password('ab'); }
+    throws_ok { $patron->set_password({ password => 'ab' }); }
         'Koha::Exceptions::Password::TooShort',
         'minPasswordLength is undef, fall back to 3, fail test';
+    is( "$@",
+        'Password length (2) is shorter than required (3)',
+        'Exception parameters passed correctly'
+    );
 
     t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
-    throws_ok { $patron->set_password('ab'); }
+    throws_ok { $patron->set_password({ password => 'ab' }); }
         'Koha::Exceptions::Password::TooShort',
         'minPasswordLength is 2, fall back to 3, fail test';
 
     t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
-    throws_ok { $patron->set_password('abcb'); }
+    throws_ok { $patron->set_password({ password => 'abcb' }); }
         'Koha::Exceptions::Password::TooShort',
         'minPasswordLength is 5, fail test';
 
     # Trailing spaces tests
-    throws_ok { $patron->set_password('abcD12d   '); }
+    throws_ok { $patron->set_password({ password => 'abcD12d   ' }); }
         'Koha::Exceptions::Password::WhitespaceCharacters',
         'Password contains trailing spaces, exception is thrown';
 
     # Require strong password tests
     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
-    throws_ok { $patron->set_password('abcd   a'); }
+    throws_ok { $patron->set_password({ password => 'abcd   a' }); }
         'Koha::Exceptions::Password::TooWeak',
         'Password is too weak, exception is thrown';
 
@@ -1556,16 +1672,19 @@ subtest '->set_password' => sub {
     $patron->discard_changes;
     is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
 
-    $patron->set_password('abcD12 34');
+    $patron->set_password({ password => 'abcD12 34' });
     $patron->discard_changes;
 
     is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
 
+    lives_ok { $patron->set_password({ password => 'abcd   a', skip_validation => 1 }) }
+        'Password is weak, but skip_validation was passed, so no exception thrown';
+
     # Completeness
     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
     $patron->login_attempts(3)->store;
     my $old_digest = $patron->password;
-    $patron->set_password('abcd   a');
+    $patron->set_password({ password => 'abcd   a' });
     $patron->discard_changes;
 
     isnt( $patron->password, $old_digest, 'Password has been updated' );
@@ -1577,7 +1696,7 @@ subtest '->set_password' => sub {
 
     # Enable logging password changes
     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
-    $patron->set_password('abcd   b');
+    $patron->set_password({ password => 'abcd   b' });
 
     $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
@@ -1585,16 +1704,165 @@ subtest '->set_password' => sub {
     $schema->storage->txn_rollback;
 };
 
+$schema->storage->txn_begin;
+subtest 'search_unsubscribed' => sub {
+    plan tests => 4;
 
+    t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
+    t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
+    is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
 
-# TODO Move to t::lib::Mocks and reuse it!
-sub set_logged_in_user {
-    my ($patron) = @_;
-    C4::Context->set_userenv(
-        $patron->borrowernumber, $patron->userid,
-        $patron->cardnumber,     'firstname',
-        'surname',               $patron->library->branchcode,
-        'Midway Public Library', $patron->flags,
-        '',                      ''
-    );
-}
+    my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
+    my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
+
+    t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
+    Koha::Patron::Consents->delete; # for correct counts
+    Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string })->store;
+    is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
+
+    # Add another refusal but shift the period
+    t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
+    Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string->subtract(days=>2) })->store;
+    is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
+
+    # Try another (special) attempts setting
+    t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
+    # Lockout is now disabled
+    # Patron2 still matches: refused earlier, not locked
+    is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
+};
+
+subtest 'search_anonymize_candidates' => sub {
+    plan tests => 5;
+    my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
+    my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
+    $patron1->anonymized(0);
+    $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
+    $patron2->anonymized(0);
+    $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
+
+    t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
+    is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
+
+    t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
+    my $cnt = Koha::Patrons->search_anonymize_candidates->count;
+    $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
+    $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
+    is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
+
+    t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
+    $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
+    $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
+    $cnt = Koha::Patrons->search_anonymize_candidates->count;
+    $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
+    $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
+    is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
+
+    t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
+    $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
+    $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
+    $cnt = Koha::Patrons->search_anonymize_candidates->count;
+    $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
+    $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
+    is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
+
+    t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
+    $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
+    $patron1->login_attempts(0)->store;
+    $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
+    $patron2->login_attempts(0)->store;
+    $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
+    $patron1->login_attempts(3)->store;
+    is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
+        $cnt+1, 'Locked flag' );
+};
+
+subtest 'search_anonymized' => sub {
+    plan tests => 3;
+    my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
+
+    t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
+    is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
+
+    t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
+    $patron1->dateexpiry( dt_from_string );
+    $patron1->anonymized(0)->store;
+    my $cnt = Koha::Patrons->search_anonymized->count;
+    $patron1->anonymized(1)->store;
+    is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
+    $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
+    is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
+};
+
+subtest 'lock' => sub {
+    plan tests => 8;
+
+    my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
+    my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
+    my $hold = $builder->build_object({
+        class => 'Koha::Holds',
+        value => { borrowernumber => $patron1->borrowernumber },
+    });
+
+    t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
+    my $expiry = dt_from_string->add(days => 1);
+    $patron1->dateexpiry( $expiry );
+    $patron1->lock;
+    is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
+    is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
+    is( $patron1->holds->count, 1, 'No holds removed' );
+
+    $patron1->lock({ expire => 1, remove => 1});
+    isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
+    is( $patron1->holds->count, 0, 'Holds removed' );
+
+    # Disable lockout feature
+    t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
+    $patron1->login_attempts(0);
+    $patron1->dateexpiry( $expiry );
+    $patron1->store;
+    $patron1->lock;
+    is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
+
+    # Trivial wrapper test (Koha::Patrons->lock)
+    $patron1->login_attempts(0)->store;
+    Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
+    $patron1->discard_changes; # refresh
+    $patron2->discard_changes;
+    is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
+    is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
+};
+
+subtest 'anonymize' => sub {
+    plan tests => 10;
+
+    my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
+    my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
+
+    # First try patron with issues
+    my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
+    warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
+    $issue->delete;
+
+    t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
+    my $surname = $patron1->surname; # expect change, no clear
+    my $branchcode = $patron1->branchcode; # expect skip
+    $patron1->anonymize;
+    is($patron1->anonymized, 1, 'Check flag' );
+
+    is( $patron1->dateofbirth, undef, 'Birth date cleared' );
+    is( $patron1->firstname, undef, 'First name cleared' );
+    isnt( $patron1->surname, $surname, 'Surname changed' );
+    ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
+    is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
+    is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
+
+    # Test wrapper in Koha::Patrons
+    $patron1->surname($surname)->store; # restore
+    my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
+    $patron1->discard_changes; # refresh
+    isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
+    $patron2->discard_changes; # refresh
+    is( $patron2->firstname, undef, 'First name patron2 cleared' );
+};
+$schema->storage->txn_rollback;