Bug 21337: (QA follow-up) Rename exception code
[koha_ffzg] / t / db_dependent / Koha / Patrons.t
index c494241..c552220 100644 (file)
 
 use Modern::Perl;
 
-use Test::More tests => 26;
+use Test::More tests => 34;
 use Test::Warn;
+use Test::Exception;
+use Test::MockModule;
 use Time::Fake;
 use DateTime;
 use JSON;
 
-use C4::Biblio;
-use C4::Circulation;
-use C4::Members;
 use C4::Circulation;
+use C4::Biblio;
+use C4::Auth qw(checkpw_hash);
 
 use Koha::Holds;
-use Koha::Patron;
 use Koha::Patrons;
 use Koha::Patron::Categories;
 use Koha::Database;
@@ -83,7 +83,7 @@ subtest 'library' => sub {
 };
 
 subtest 'guarantees' => sub {
-    plan tests => 8;
+    plan tests => 13;
     my $guarantees = $new_patron_1->guarantees;
     is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
     is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee' );
@@ -101,6 +101,53 @@ subtest 'guarantees' => sub {
     is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
     is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
     $_->delete for @guarantees;
+
+    #Test return order of guarantees BZ 18635
+    my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
+    my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
+
+    my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
+
+    my $order_guarantee1 = $builder->build_object( { class => 'Koha::Patrons' ,  value => {
+            surname => 'Zebra',
+            guarantorid => $guarantor->borrowernumber
+        }
+    })->borrowernumber;
+
+    my $order_guarantee2 = $builder->build_object( { class => 'Koha::Patrons' ,  value => {
+            surname => 'Yak',
+            guarantorid => $guarantor->borrowernumber
+        }
+    })->borrowernumber;
+
+    my $order_guarantee3 = $builder->build_object( { class => 'Koha::Patrons' ,  value => {
+            surname => 'Xerus',
+            firstname => 'Walrus',
+            guarantorid => $guarantor->borrowernumber
+        }
+    })->borrowernumber;
+
+    my $order_guarantee4 = $builder->build_object( { class => 'Koha::Patrons' ,  value => {
+            surname => 'Xerus',
+            firstname => 'Vulture',
+            guarantorid => $guarantor->borrowernumber
+        }
+    })->borrowernumber;
+
+    my $order_guarantee5 = $builder->build_object( { class => 'Koha::Patrons' ,  value => {
+            surname => 'Xerus',
+            firstname => 'Unicorn',
+            guarantorid => $guarantor->borrowernumber
+        }
+    })->borrowernumber;
+
+    $guarantees = $guarantor->guarantees();
+
+    is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
+    is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
+    is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
+    is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
+    is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
 };
 
 subtest 'category' => sub {
@@ -173,9 +220,9 @@ subtest 'update_password' => sub {
     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' );
 
-    $retrieved_patron_1->update_password( 'another_nonexistent_userid_1', 'another_password' );
+    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, 'another_password',             'Koha::Patron->update_password should have updated the password' );
+    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' );
@@ -376,6 +423,30 @@ subtest "delete" => sub {
     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
 };
 
+subtest 'Koha::Patrons->delete' => sub {
+    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' );
+    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 {
     plan tests => 4;
 
@@ -394,7 +465,7 @@ subtest 'add_enrolment_fee_if_needed' => sub {
         branchcode   => $library->{branchcode},
     );
 
-    my $borrowernumber = C4::Members::AddMember(%borrower_data);
+    my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
     $borrower_data{borrowernumber} = $borrowernumber;
 
     my $patron = Koha::Patrons->find( $borrowernumber );
@@ -403,22 +474,21 @@ subtest 'add_enrolment_fee_if_needed' => sub {
 
     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
     $borrower_data{categorycode} = 'J';
-    C4::Members::ModMember(%borrower_data);
+    $patron->set(\%borrower_data)->store;
     $total = $patron->account->balance;
     is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
 
     $borrower_data{categorycode} = 'K';
-    C4::Members::ModMember(%borrower_data);
+    $patron->set(\%borrower_data)->store;
     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
 
     $borrower_data{categorycode} = 'J';
-    C4::Members::ModMember(%borrower_data);
+    $patron->set(\%borrower_data)->store;
     $total = $patron->account->balance;
     is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
 
     # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
     $patron->categorycode('YA')->store;
-    my $fee = $patron->add_enrolment_fee_if_needed;
     $total = $patron->account->balance;
     is( int($total),
         int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
@@ -428,8 +498,8 @@ subtest 'add_enrolment_fee_if_needed' => sub {
     $patron->delete;
 };
 
-subtest 'checkouts + get_overdues + old_checkouts' => sub {
-    plan tests => 12;
+subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
+    plan tests => 17;
 
     my $library = $builder->build( { source => 'Branch' } );
     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
@@ -481,6 +551,9 @@ subtest 'checkouts + get_overdues + old_checkouts' => sub {
     my $checkouts = $patron->checkouts;
     is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
+    my $pending_checkouts = $patron->pending_checkouts;
+    is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
+    is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
     my $old_checkouts = $patron->old_checkouts;
     is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
@@ -499,6 +572,12 @@ subtest 'checkouts + get_overdues + old_checkouts' => sub {
     $checkouts = $patron->checkouts;
     is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
+    $pending_checkouts = $patron->pending_checkouts;
+    is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
+    is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
+
+    my $first_checkout = $pending_checkouts->next;
+    is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
 
     my $overdues = $patron->get_overdues;
     is( $overdues->count, 2, 'Patron should have 2 overdues');
@@ -519,6 +598,49 @@ subtest 'checkouts + get_overdues + old_checkouts' => sub {
     $module->unmock('userenv');
 };
 
+subtest 'get_routing_lists' => sub {
+    plan tests => 5;
+
+    my $biblio = Koha::Biblio->new()->store();
+    my $subscription = Koha::Subscription->new({
+        biblionumber => $biblio->biblionumber,
+        }
+    )->store;
+
+    my $patron = $builder->build( { source => 'Borrower' } );
+    $patron = Koha::Patrons->find( $patron->{borrowernumber} );
+
+    is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
+
+    my $routinglist_count = Koha::Subscription::Routinglists->count;
+    my $routinglist = Koha::Subscription::Routinglist->new({
+        borrowernumber   => $patron->borrowernumber,
+        ranking          => 5,
+        subscriptionid   => $subscription->subscriptionid
+    })->store;
+
+    is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
+
+    my $routinglists = $patron->get_routing_lists;
+    is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
+    is( ref($routinglists),   'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
+
+    my $subscription2 = Koha::Subscription->new({
+        biblionumber => $biblio->biblionumber,
+        }
+    )->store;
+    my $routinglist2 = Koha::Subscription::Routinglist->new({
+        borrowernumber   => $patron->borrowernumber,
+        ranking          => 1,
+        subscriptionid   => $subscription2->subscriptionid
+    })->store;
+
+    is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
+
+    $patron->delete; # Clean up for later tests
+
+};
+
 subtest 'get_age' => sub {
     plan tests => 7;
 
@@ -944,6 +1066,7 @@ subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited
     #   + library_12
     # group2
     #   + library21
+    $nb_of_patrons = Koha::Patrons->search->count;
     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
     my $library_11 = $builder->build( { source => 'Branch' } );
@@ -1014,8 +1137,8 @@ subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited
         plan tests => 6;
 
         set_logged_in_user( $patron_11_1 );
-        my $total_number_of_patrons = $nb_of_patrons + 6; # 2 created before + 4 for these subtests
-        is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
+        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 );
@@ -1119,29 +1242,363 @@ subtest 'is_child | is_adult' => sub {
     $patron_other->delete;
 };
 
+subtest 'get_overdues' => sub {
+    plan tests => 7;
+
+    my $library = $builder->build( { source => 'Branch' } );
+    my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
+    my $item_1 = $builder->build(
+        {
+            source => 'Item',
+            value  => {
+                homebranch    => $library->{branchcode},
+                holdingbranch => $library->{branchcode},
+                biblionumber  => $biblionumber_1
+            }
+        }
+    );
+    my $item_2 = $builder->build(
+        {
+            source => 'Item',
+            value  => {
+                homebranch    => $library->{branchcode},
+                holdingbranch => $library->{branchcode},
+                biblionumber  => $biblionumber_1
+            }
+        }
+    );
+    my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
+    my $item_3 = $builder->build(
+        {
+            source => 'Item',
+            value  => {
+                homebranch    => $library->{branchcode},
+                holdingbranch => $library->{branchcode},
+                biblionumber  => $biblionumber_2
+            }
+        }
+    );
+    my $patron = $builder->build(
+        {
+            source => 'Borrower',
+            value  => { branchcode => $library->{branchcode} }
+        }
+    );
+
+    my $module = new Test::MockModule('C4::Context');
+    $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
+
+    AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
+    AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
+    AddIssue( $patron, $item_3->{barcode} );
+
+    $patron = Koha::Patrons->find( $patron->{borrowernumber} );
+    my $overdues = $patron->get_overdues;
+    is( $overdues->count, 2, 'Patron should have 2 overdues');
+    is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
+    is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
+
+    my $o = $overdues->reset->next;
+    my $unblessed_overdue = $o->unblessed_all_relateds;
+    is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
+    is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
+    is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
+    is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
+
+    # Clean stuffs
+    $patron->checkouts->delete;
+    $patron->delete;
+};
+
+subtest 'userid_is_valid' => sub {
+    plan tests => 8;
+
+    my $library = $builder->build_object( { class => 'Koha::Libraries' } );
+    my $patron_category = $builder->build_object(
+        {
+            class => 'Koha::Patron::Categories',
+            value => { category_type => 'P', enrolmentfee => 0 }
+        }
+    );
+    my %data = (
+        cardnumber   => "123456789",
+        firstname    => "Tomasito",
+        surname      => "None",
+        categorycode => $patron_category->categorycode,
+        branchcode   => $library->branchcode,
+    );
+
+    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->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
+
+    $patron_1->userid( 'tomasito.non' );
+    is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
+        1, 'recently created userid -> unique (borrowernumber passed)' );
+
+    $patron_1->userid( 'tomasitoxxx' );
+    is( $patron_1->has_valid_userid,
+        1, 'non-existent userid -> unique (borrowernumber passed)' );
+    $patron_1->discard_changes; # We compare with the original userid later
+
+    my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
+    is( $patron_not_in_storage->has_valid_userid,
+        0, 'userid exists for another patron, patron is not in storage yet' );
+
+    $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
+    is( $patron_not_in_storage->has_valid_userid,
+        1, 'non-existent userid, patron is not in storage yet' );
+
+    # Regression tests for BZ12226
+    my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
+    is( $db_patron->has_valid_userid,
+        0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
+
+    # Add a new borrower with the same userid but different cardnumber
+    $data{cardnumber} = "987654321";
+    my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
+    my $patron_2 = Koha::Patrons->find($new_borrowernumber);
+    $patron_2->userid($patron_1->userid);
+    is( $patron_2->has_valid_userid,
+        0, 'The userid is already in used, it cannot be used for another patron' );
+
+    my $new_userid = 'a_user_id';
+    $data{cardnumber} = "234567890";
+    $data{userid}     = 'a_user_id';
+    $borrowernumber   = Koha::Patron->new(\%data)->store->borrowernumber;
+    my $patron_3 = Koha::Patrons->find($borrowernumber);
+    is( $patron_3->userid, $new_userid,
+        'Koha::Patron->store should insert the given userid' );
+
+    # Cleanup
+    $patron_1->delete;
+    $patron_2->delete;
+    $patron_3->delete;
+};
+
+subtest 'generate_userid' => sub {
+    plan tests => 7;
+
+    my $library = $builder->build_object( { class => 'Koha::Libraries' } );
+    my $patron_category = $builder->build_object(
+        {
+            class => 'Koha::Patron::Categories',
+            value => { category_type => 'P', enrolmentfee => 0 }
+        }
+    );
+    my %data = (
+        cardnumber   => "123456789",
+        firstname    => "Tomasito",
+        surname      => "None",
+        categorycode => $patron_category->categorycode,
+        branchcode   => $library->branchcode,
+    );
+
+    my $expected_userid_patron_1 = 'tomasito.none';
+    my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
+    $new_patron->generate_userid;
+    my $userid = $new_patron->userid;
+    is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
+    my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
+    my $patron_1 = Koha::Patrons->find($borrowernumber);
+    is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
+
+    $new_patron->generate_userid;
+    $userid = $new_patron->userid;
+    is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
+    $data{cardnumber} = '987654321';
+    my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
+    my $patron_2 = Koha::Patrons->find($new_borrowernumber);
+    isnt( $patron_2->userid, 'tomasito',
+        "Patron with duplicate userid has new userid generated" );
+    is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
+        "Patron with duplicate userid has new userid generated (1 is appened" );
+
+    $new_patron->generate_userid;
+    $userid = $new_patron->userid;
+    is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
+
+    $patron_1 = Koha::Patrons->find($borrowernumber);
+    $patron_1->userid(undef);
+    $patron_1->generate_userid;
+    $userid = $patron_1->userid;
+    is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
+
+    # Cleanup
+    $patron_1->delete;
+    $patron_2->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' );
+is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
 
 subtest 'Log cardnumber change' => sub {
     plan tests => 3;
 
     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
-    my $patron = $builder->build( { source => 'Borrower' } );
+    my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
 
-    my $cardnumber = $patron->{cardnumber};
-    $patron->{cardnumber} = 'TESTCARDNUMBER';
-    ModMember(%$patron);
+    my $cardnumber = $patron->cardnumber;
+    $patron->set( { cardnumber => 'TESTCARDNUMBER' });
+    $patron->store;
 
-    my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->{borrowernumber} } );
+    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.' );
 };
 
-
 $schema->storage->txn_rollback;
 
+subtest 'Test Koha::Patrons::merge' => sub {
+    plan tests => 110;
+
+    my $schema = Koha::Database->new()->schema();
+
+    my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
+
+    $schema->storage->txn_begin;
+
+    my $keeper  = $builder->build_object({ class => 'Koha::Patrons' });
+    my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
+    my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
+
+    while (my ($r, $field) = each(%$resultsets)) {
+        $builder->build({ source => $r, value => { $field => $keeper->id } });
+        $builder->build({ source => $r, value => { $field => $loser_1 } });
+        $builder->build({ source => $r, value => { $field => $loser_2 } });
+
+        my $keeper_rs =
+          $schema->resultset($r)->search( { $field => $keeper->id } );
+        is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
+
+        my $loser_1_rs =
+          $schema->resultset($r)->search( { $field => $loser_1 } );
+        is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
+
+        my $loser_2_rs =
+          $schema->resultset($r)->search( { $field => $loser_2 } );
+        is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
+    }
+
+    my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
+
+    while (my ($r, $field) = each(%$resultsets)) {
+        my $keeper_rs =
+          $schema->resultset($r)->search( {$field => $keeper->id } );
+        is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
+    }
+
+    is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
+    is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
+
+    $schema->storage->txn_rollback;
+};
+
+subtest '->store' => sub {
+    plan tests => 3;
+    my $schema = Koha::Database->new->schema;
+    $schema->storage->txn_begin;
+
+    my $print_error = $schema->storage->dbh->{PrintError};
+    $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
+
+    my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
+    my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
+
+    throws_ok
+        { $patron_2->userid($patron_1->userid)->store; }
+        'Koha::Exceptions::Object::DuplicateID',
+        'Koha::Patron->store raises an exception on duplicate ID';
+
+    # Test password
+    my $password = 'password';
+    $patron_1->update_password($patron_1->userid, $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');
+
+    $schema->storage->dbh->{PrintError} = $print_error;
+    $schema->storage->txn_rollback;
+};
+
+subtest '->set_password' => sub {
+
+    plan tests => 12;
+
+    $schema->storage->txn_begin;
+
+    my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
+
+    # Disable logging password changes for this tests
+    t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
+
+    # Password-length tests
+    t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
+    throws_ok { $patron->set_password('ab'); }
+        'Koha::Exceptions::Password::TooShort',
+        'minPasswordLength is undef, fall back to 3, fail test';
+
+    t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
+    throws_ok { $patron->set_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'); }
+        'Koha::Exceptions::Password::TooShort',
+        'minPasswordLength is 5, fail test';
+
+    # Trailing spaces tests
+    throws_ok { $patron->set_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'); }
+        'Koha::Exceptions::Password::TooWeak',
+        'Password is too weak, exception is thrown';
+
+    # Refresh patron from DB, just to make sure
+    $patron->discard_changes;
+    is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
+
+    $patron->set_password('abcD12 34');
+    $patron->discard_changes;
+
+    is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
+
+    # Completeness
+    t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
+    $patron->login_attempts(3)->store;
+    my $old_digest = $patron->password;
+    $patron->set_password('abcd   a');
+    $patron->discard_changes;
+
+    isnt( $patron->password, $old_digest, 'Password has been updated' );
+    ok( checkpw_hash('abcd   a', $patron->password), 'Password hash is correct' );
+    is( $patron->login_attempts, 0, 'Login attemps have been reset' );
+
+    my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
+    is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
+
+    # Enable logging password changes
+    t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
+    $patron->set_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' );
+
+    $schema->storage->txn_rollback;
+};
+
+
+
 # TODO Move to t::lib::Mocks and reuse it!
 sub set_logged_in_user {
     my ($patron) = @_;