diff --git a/lib/tests/moodlelib_test.php b/lib/tests/moodlelib_test.php index ac907c45238..14782b45011 100644 --- a/lib/tests/moodlelib_test.php +++ b/lib/tests/moodlelib_test.php @@ -4295,6 +4295,27 @@ class core_moodlelib_testcase extends advanced_testcase { 'Fetch data using an invalid username' => [ 'username', 's2', false ], + 'Fetch by email' => [ + 'email', 's1@example.com', true + ], + 'Fetch data using a non-existent email' => [ + 'email', 's2@example.com', false + ], + 'Fetch data using a non-existent email, throw exception' => [ + 'email', 's2@example.com', false, dml_missing_record_exception::class + ], + 'Multiple accounts with the same email' => [ + 'email', 's1@example.com', false, 1 + ], + 'Multiple accounts with the same email, throw exception' => [ + 'email', 's1@example.com', false, 1, dml_multiple_records_exception::class + ], + 'Fetch data using a valid user ID' => [ + 'id', true, true + ], + 'Fetch data using a non-existent user ID' => [ + 'id', false, false + ], ]; } @@ -4305,10 +4326,15 @@ class core_moodlelib_testcase extends advanced_testcase { * @param string $field The field to use for the query. * @param string|boolean $value The field value. When fetching by ID, set true to fetch valid user ID, false otherwise. * @param boolean $success Whether we expect for the fetch to succeed or return false. + * @param int $allowaccountssameemail Value for $CFG->allowaccountssameemail. + * @param string $expectedexception The exception to be expected. */ - public function test_get_complete_user_data($field, $value, $success) { + public function test_get_complete_user_data($field, $value, $success, $allowaccountssameemail = 0, $expectedexception = '') { $this->resetAfterTest(); + // Set config settings we need for our environment. + set_config('allowaccountssameemail', $allowaccountssameemail); + // Generate the user data. $generator = $this->getDataGenerator(); $userdata = [ @@ -4317,6 +4343,11 @@ class core_moodlelib_testcase extends advanced_testcase { ]; $user = $generator->create_user($userdata); + if ($allowaccountssameemail) { + // Create another user with the same email address. + $generator->create_user(['email' => 's1@example.com']); + } + // Since the data provider can't know what user ID to use, do a special handling for ID field tests. if ($field === 'id') { if ($value) { @@ -4327,7 +4358,15 @@ class core_moodlelib_testcase extends advanced_testcase { $value = $user->id + 1; } } - $fetcheduser = get_complete_user_data($field, $value); + + // When an exception is expected. + $throwexception = false; + if ($expectedexception) { + $this->expectException($expectedexception); + $throwexception = true; + } + + $fetcheduser = get_complete_user_data($field, $value, null, $throwexception); if ($success) { $this->assertEquals($user->id, $fetcheduser->id); $this->assertEquals($user->username, $fetcheduser->username);