first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
@@ -0,0 +1,320 @@
@tool @tool_uploaduser @_file_upload
Feature: Upload users
In order to add users to the system
As an admin
I need to upload files containing the users data
@javascript
Scenario: Upload users enrolling them on courses and groups
Given the following "courses" exist:
| fullname | shortname | category |
| Maths | math102 | 0 |
And the following "groups" exist:
| name | course | idnumber |
| Section 1 | math102 | S1 |
| Section 3 | math102 | S3 |
And I log in as "admin"
And I navigate to "Users > Accounts > Upload users" in site administration
When I upload "lib/tests/fixtures/upload_users.csv" file to "File" filemanager
And I press "Upload users"
Then I should see "Upload users preview"
And I should see "Tom"
And I should see "Jones"
And I should see "verysecret"
And I should see "jonest@example.com"
And I should see "Reznor"
And I should see "course1"
And I should see "math102"
And I should see "group1"
And I should see "Section 1"
And I press "Upload users"
And I press "Continue"
And I navigate to "Users > Accounts > Browse list of users" in site administration
And I should see "Tom Jones"
And I should see "Trent Reznor"
And I should see "reznor@example.com"
And I am on the "Maths" "groups" page
And I set the field "groups" to "Section 1 (1)"
And the "members" select box should contain "Tom Jones (jonest@example.com)"
@javascript
Scenario: Upload users enrolling them on courses and groups applying defaults
Given the following "courses" exist:
| fullname | shortname | category |
| Maths | math102 | 0 |
And the following "groups" exist:
| name | course | idnumber |
| Section 1 | math102 | S1 |
| Section 3 | math102 | S3 |
And I log in as "admin"
And I navigate to "Users > Accounts > Upload users" in site administration
When I upload "lib/tests/fixtures/upload_users.csv" file to "File" filemanager
And I press "Upload users"
And I should see "Upload users preview"
And I set the following fields to these values:
| City/town | Brighton |
| Department | Purchasing |
And I press "Upload users"
And I press "Continue"
And I navigate to "Users > Accounts > Browse list of users" in site administration
And I should see "Tom Jones"
And I follow "Tom Jones"
And I follow "Edit profile"
And the field "City/town" matches value "Brighton"
And the field "Department" matches value "Purchasing"
@javascript
Scenario: Upload users with custom profile fields
# Create user profile field.
Given the following "custom profile fields" exist:
| datatype | shortname | name |
| text | superfield | Super field |
And I log in as "admin"
# Upload users.
When I navigate to "Users > Accounts > Upload users" in site administration
And I upload "lib/tests/fixtures/upload_users_profile.csv" file to "File" filemanager
And I press "Upload users"
And I should see "Upload users preview"
And I press "Upload users"
# Check that users were created and the superfield is filled.
And I navigate to "Users > Accounts > Browse list of users" in site administration
And I follow "Tom Jones"
And I should see "Super field"
And I should see "The big guy"
And I log out
@javascript
Scenario: Upload users setting their email stop value
Given I log in as "admin"
And I navigate to "Users > Accounts > Upload users" in site administration
When I upload "lib/tests/fixtures/upload_users_emailstop.csv" file to "File" filemanager
And I press "Upload users"
Then I should see "Upload users preview"
And the following should exist in the "uupreview" table:
| CSV line | username | emailstop |
| 2 | jbloggs | 1 |
| 3 | fbloggs | 0 |
And I press "Upload users"
And I should see "Users created: 2"
And I log out
@javascript
Scenario: Upload users setting their user theme
Given the following "courses" exist:
| fullname | shortname | category |
| Maths | math102 | 0 |
# We need to do a bit of setup here.
And I change window size to "large"
And I log in as "admin"
And I navigate to "Security > Site security settings" in site administration
And I click on "Password policy" "checkbox"
And I click on "Save changes" "button"
And I navigate to "Appearance > Advanced theme settings" in site administration
And I click on "Allow user themes" "checkbox"
And I click on "Save changes" "button"
# Upload the users.
And I navigate to "Users > Accounts > Upload users" in site administration
When I upload "lib/tests/fixtures/upload_users_themes.csv" file to "File" filemanager
And I press "Upload users"
Then I should see "Upload users preview"
And I should see "boost"
And I should see "classic"
And I should see "No theme is defined for this user."
And I should see "Theme \"somefaketheme\" is not installed and will be ignored."
And I press "Upload users"
And I should see "Users created: 4"
And I press "Continue"
# Boost check.
And I am on the "jonest@example.com" "user > editing" page
And I should see "Boost"
# Classic check.
And I am on the "reznor@example.com" "user > editing" page
And I should see "Classic"
@javascript
Scenario: Upload users setting their user theme when allowuserthemes is false
Given the following "courses" exist:
| fullname | shortname | category |
| Maths | math102 | 0 |
# We need to do a bit of setup here.
And I change window size to "large"
And I log in as "admin"
And I navigate to "Security > Site security settings" in site administration
And I click on "Password policy" "checkbox"
And I click on "Save changes" "button"
# Upload the users.
And I navigate to "Users > Accounts > Upload users" in site administration
When I upload "lib/tests/fixtures/upload_users_themes.csv" file to "File" filemanager
And I press "Upload users"
Then I should see "Upload users preview"
And I should see "boost"
And I should see "classic"
And I press "Upload users"
And I should see "User themes are not enabled, so any included in the upload users file will be ignored."
And I should see "Users created: 4"
And I press "Continue"
And I log out
@javascript
Scenario: Upload users setting their enrol date and period
Given the following "courses" exist:
| fullname | shortname | category |
| Maths | math102 | 0 |
# Upload the users.
And I change window size to "large"
And I log in as "admin"
And I navigate to "Users > Accounts > Upload users" in site administration
When I upload "lib/tests/fixtures/upload_users_enrol_date_period.csv" file to "File" filemanager
And I press "Upload users"
Then I should see "Upload users preview"
And I press "Upload users"
# Check user enrolment start date and period
And I am on "Maths" course homepage
Then I navigate to course participants
And I click on "Manual enrolments" "link" in the "Student One" "table_row"
Then I should see "1 January 2019" in the "Enrolment starts" "table_row"
And I should not see "Enrolment ends"
And I click on "Close" "button" in the "Enrolment details" "dialogue"
And I click on "Manual enrolments" "link" in the "Student Two" "table_row"
Then I should see "2 January 2020" in the "Enrolment starts" "table_row"
And I should see "12 January 2020" in the "Enrolment ends" "table_row"
And I click on "Close" "button" in the "Enrolment details" "dialogue"
And I log out
@javascript
Scenario: Upload users enrolling them on courses and assign category roles
Given the following "courses" exist:
| fullname | shortname |
| management1 | management1 |
| film1 | film1 |
And the following "categories" exist:
| name | idnumber |
| MGMT | MGMT |
| Film | Film |
And I log in as "admin"
And I navigate to "Users > Accounts > Upload users" in site administration
When I upload "lib/tests/fixtures/upload_users_category.csv" file to "File" filemanager
And I press "Upload users"
Then I should see "Upload users preview"
And I should see "Tom"
And I should see "Jones"
And I should see "Trent"
And I should see "Reznor"
And I should see "Aurora"
And I should see "Jiang"
And I should see "Federico"
And I should see "Fellini"
And I should see "Ivan"
And I should see "Ivanov"
And I should see "John"
And I should see "Smith"
And I should see "Warm"
And I should see "Cool"
And I should see "James"
And I should see "Bond"
And I should see "MGMT"
And I should see "Film"
And I should see "manager"
And I should see "student"
And I should see "coursecreator"
And I should see "management1"
And I should see "film1"
And I press "Upload users"
And I should see "Unknown category with category ID number \"Movie\""
And I should see "Unknown course named \"movie1\""
And I should see "Unknown role \"notcoursecreator\""
And I should see "Could not assign role to user: missing role for category"
And I press "Continue"
And I navigate to "Users > Accounts > Browse list of users" in site administration
And I should see "Tom Jones"
And I should see "Trent Reznor"
And I should see "reznor@example.com"
And I am on the "management1" "enrolled users" page
And I should see "Tom Jones"
And I should see "Trent Reznor"
And I should see "Aurora Jiang"
And I should see "Student"
And I am on the "film1" "enrolled users" page
And I should see "Federico Fellini"
And I should see "Student"
And I am on site homepage
And I navigate to "Courses > Manage courses and categories" in site administration
And I click on "permissions" action for "MGMT" in management category listing
And I set the field "Participants tertiary navigation" to "Assign roles"
And I should see "Manager"
And I should see "Tom Jones"
And I should see "Trent Reznor"
And I should see "Course creator"
And I should see "Aurora Jiang"
And I am on site homepage
And I navigate to "Courses > Manage courses and categories" in site administration
And I click on "permissions" action for "Film" in management category listing
And I set the field "Participants tertiary navigation" to "Assign roles"
And I should see "Course creator"
And I should see "Federico Fellini"
@javascript
Scenario: Update existing users matching them on email
Given the following "users" exist:
| username | firstname | lastname | email |
| bilbob | Blasbo | Blabbins | bilbo@example.com |
| frodob | Frodeo | Baspins | frodo@example.com |
And I log in as "admin"
And I navigate to "Users > Accounts >Upload users" in site administration
When I upload "lib/tests/fixtures/upload_users_email_matching.csv" file to "File" filemanager
And I press "Upload users"
Then I should see "Upload users preview"
And I set the following fields to these values:
| Upload type | Update existing users only |
| Existing user details | Override with file |
| Match on email address | Yes |
And I press "Upload users"
And I press "Continue"
And I navigate to "Users > Accounts > Browse list of users" in site administration
And I should see "Bilbo Baggins"
And I should see "Frodo Baggins"
@javascript
Scenario: Update existing users matching them on email where one email address is associated with multiple users
Given the following "users" exist:
| username | firstname | lastname | email |
| bilbob | Blasbo | Blabbins | bilbo@example.com |
| frodob | Frodeo | Baspins | frodo@example.com |
| fredob | Fredoo | Baspins | frodo@example.com |
And I log in as "admin"
And I navigate to "Users > Accounts > Upload users" in site administration
When I upload "lib/tests/fixtures/upload_users_email_matching.csv" file to "File" filemanager
And I press "Upload users"
Then I should see "Upload users preview"
And I set the following fields to these values:
| Upload type | Update existing users only |
| Existing user details | Override with file |
| Match on email address | Yes |
And I press "Upload users"
And I should see "Multiple users with email frodo@example.com detected"
And I press "Continue"
And I navigate to "Users > Accounts > Browse list of users" in site administration
And I should see "Bilbo Baggins"
And I should not see "Frodo Baggins"
@javascript
Scenario: Create a new user when matching them on email where where the username already exists
Given the following "users" exist:
| username | firstname | lastname | email |
| bilbob | Samwise | Gamgee | samwise@example.com |
| frodob | Frodeo | Baspins | frodo@example.com |
And I log in as "admin"
And I navigate to "Users > Accounts > Upload users" in site administration
When I upload "lib/tests/fixtures/upload_users_email_matching.csv" file to "File" filemanager
And I press "Upload users"
Then I should see "Upload users preview"
And I set the following fields to these values:
| Upload type | Add new and update existing users |
| Existing user details | Override with file |
| Match on email address | Yes |
And I press "Upload users"
And I should see "User not added - username already exists under a different email"
And I press "Continue"
And I navigate to "Users > Accounts > Browse list of users" in site administration
And I should see "Samwise Gamgee"
And I should see "Frodo Baggins"
+287
View File
@@ -0,0 +1,287 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace tool_uploaduser;
/**
* Tests for CLI tool_uploaduser.
*
* @package tool_uploaduser
* @copyright 2020 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cli_test extends \advanced_testcase {
/**
* Generate cli_helper and mock $_SERVER['argv']
*
* @param array $mockargv
* @return \tool_uploaduser\cli_helper
*/
protected function construct_helper(array $mockargv = []) {
if (array_key_exists('argv', $_SERVER)) {
$oldservervars = $_SERVER['argv'];
}
$_SERVER['argv'] = array_merge([''], $mockargv);
$clihelper = new cli_helper(\tool_uploaduser\local\text_progress_tracker::class);
if (isset($oldservervars)) {
$_SERVER['argv'] = $oldservervars;
} else {
unset($_SERVER['argv']);
}
return $clihelper;
}
/**
* Tests simple upload with course enrolment and group allocation
*/
public function test_upload_with_course_enrolment(): void {
global $CFG;
$this->resetAfterTest();
set_config('passwordpolicy', 0);
$this->setAdminUser();
$course = $this->getDataGenerator()->create_course(['fullname' => 'Maths', 'shortname' => 'math102']);
$g1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 1', 'idnumber' => 'S1']);
$g2 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 3', 'idnumber' => 'S3']);
$filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users.csv';
$clihelper = $this->construct_helper(["--file=$filepath"]);
ob_start();
$clihelper->process();
$output = ob_get_contents();
ob_end_clean();
// CLI output suggests that 2 users were created.
$stats = $clihelper->get_stats();
$this->assertEquals(2, preg_match_all('/New user/', $output));
$this->assertEquals('Users created: 2', $stats[0]);
// Tom Jones and Trent Reznor are enrolled into the course, first one to group $g1 and second to group $g2.
$enrols = array_values(enrol_get_course_users($course->id));
$this->assertEqualsCanonicalizing(['reznor', 'jonest'], [$enrols[0]->username, $enrols[1]->username]);
$g1members = groups_get_groups_members($g1->id);
$this->assertEquals(1, count($g1members));
$this->assertEquals('Jones', $g1members[key($g1members)]->lastname);
$g2members = groups_get_groups_members($g2->id);
$this->assertEquals(1, count($g2members));
$this->assertEquals('Reznor', $g2members[key($g2members)]->lastname);
}
/**
* Test applying defaults during the user upload
*/
public function test_upload_with_applying_defaults(): void {
global $CFG;
$this->resetAfterTest();
set_config('passwordpolicy', 0);
$this->setAdminUser();
$course = $this->getDataGenerator()->create_course(['fullname' => 'Maths', 'shortname' => 'math102']);
$g1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 1', 'idnumber' => 'S1']);
$g2 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 3', 'idnumber' => 'S3']);
$filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users.csv';
$clihelper = $this->construct_helper(["--file=$filepath", '--city=Brighton', '--department=Purchasing']);
ob_start();
$clihelper->process();
$output = ob_get_contents();
ob_end_clean();
// CLI output suggests that 2 users were created.
$stats = $clihelper->get_stats();
$this->assertEquals(2, preg_match_all('/New user/', $output));
$this->assertEquals('Users created: 2', $stats[0]);
// Users have default values applied.
$user1 = \core_user::get_user_by_username('jonest');
$this->assertEquals('Brighton', $user1->city);
$this->assertEquals('Purchasing', $user1->department);
}
/**
* User upload with user profile fields
*/
public function test_upload_with_profile_fields(): void {
global $CFG;
$this->resetAfterTest();
set_config('passwordpolicy', 0);
$this->setAdminUser();
$this->getDataGenerator()->create_custom_profile_field([
'shortname' => 'superfield', 'name' => 'Super field',
'datatype' => 'text', 'signup' => 1, 'visible' => 1, 'required' => 1, 'sortorder' => 1]);
$filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users_profile.csv';
$clihelper = $this->construct_helper(["--file=$filepath"]);
ob_start();
$clihelper->process();
$output = ob_get_contents();
ob_end_clean();
// CLI output suggests that 2 users were created.
$stats = $clihelper->get_stats();
$this->assertEquals(2, preg_match_all('/New user/', $output));
$this->assertEquals('Users created: 2', $stats[0]);
// Created users have data in the profile fields.
$user1 = \core_user::get_user_by_username('reznort');
$profilefields1 = profile_user_record($user1->id);
$this->assertObjectHasProperty('superfield', $profilefields1);
$this->assertEquals('Loves cats', $profilefields1->superfield);
}
/**
* Testing that help for CLI does not throw errors
*/
public function test_cli_help(): void {
$this->resetAfterTest();
$this->setAdminUser();
$clihelper = $this->construct_helper(["--help"]);
ob_start();
$clihelper->print_help();
$output = ob_get_contents();
ob_end_clean();
// Basically a test that everything can be parsed and displayed without errors. Check that some options are present.
$this->assertEquals(1, preg_match('/--delimiter_name=VALUE/', $output));
$this->assertEquals(1, preg_match('/--uutype=VALUE/', $output));
$this->assertEquals(1, preg_match('/--auth=VALUE/', $output));
}
/**
* Testing skipped user when one exists
*/
public function test_create_when_user_exists(): void {
global $CFG;
$this->resetAfterTest();
set_config('passwordpolicy', 0);
$this->setAdminUser();
$course = $this->getDataGenerator()->create_course(['fullname' => 'Maths', 'shortname' => 'math102']);
$g1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 1', 'idnumber' => 'S1']);
$g2 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 3', 'idnumber' => 'S3']);
// Create a user with username jonest.
$user1 = $this->getDataGenerator()->create_user(['username' => 'jonest', 'email' => 'jonest@someplace.edu']);
$filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users.csv';
$clihelper = $this->construct_helper(["--file=$filepath"]);
ob_start();
$clihelper->process();
$output = ob_get_contents();
ob_end_clean();
// CLI output suggests that 1 user was created and 1 skipped.
$stats = $clihelper->get_stats();
$this->assertEquals(1, preg_match_all('/New user/', $output));
$this->assertEquals('Users created: 1', $stats[0]);
$this->assertEquals('Users skipped: 1', $stats[1]);
// Trent Reznor is enrolled into the course, Tom Jones is not!
$enrols = array_values(enrol_get_course_users($course->id));
$this->assertEqualsCanonicalizing(['reznor'], [$enrols[0]->username]);
}
/**
* Testing update mode - do not update user records but allow enrolments
*/
public function test_enrolments_when_user_exists(): void {
global $CFG;
require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/uploaduser/locallib.php');
$this->resetAfterTest();
set_config('passwordpolicy', 0);
$this->setAdminUser();
$course = $this->getDataGenerator()->create_course(['fullname' => 'Maths', 'shortname' => 'math102']);
$g1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 1', 'idnumber' => 'S1']);
$g2 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 3', 'idnumber' => 'S3']);
// Create a user with username jonest.
$this->getDataGenerator()->create_user(['username' => 'jonest', 'email' => 'jonest@someplace.edu',
'firstname' => 'OLDNAME']);
$filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users.csv';
$clihelper = $this->construct_helper(["--file=$filepath", '--uutype='.UU_USER_UPDATE]);
ob_start();
$clihelper->process();
$output = ob_get_contents();
ob_end_clean();
// CLI output suggests that 1 user was created and 1 skipped.
$stats = $clihelper->get_stats();
$this->assertEquals(0, preg_match_all('/New user/', $output));
$this->assertEquals('Users updated: 0', $stats[0]);
$this->assertEquals('Users skipped: 1', $stats[1]);
// Tom Jones is enrolled into the course.
$enrols = array_values(enrol_get_course_users($course->id));
$this->assertEqualsCanonicalizing(['jonest'], [$enrols[0]->username]);
// User reznor is not created.
$this->assertFalse(\core_user::get_user_by_username('reznor'));
// User jonest is not updated.
$this->assertEquals('OLDNAME', \core_user::get_user_by_username('jonest')->firstname);
}
/**
* Testing update mode - update user records and perform enrolments.
*/
public function test_udpate_user(): void {
global $CFG;
require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/uploaduser/locallib.php');
$this->resetAfterTest();
set_config('passwordpolicy', 0);
$this->setAdminUser();
$course = $this->getDataGenerator()->create_course(['fullname' => 'Maths', 'shortname' => 'math102']);
$g1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 1', 'idnumber' => 'S1']);
$g2 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 3', 'idnumber' => 'S3']);
// Create a user with username jonest.
$this->getDataGenerator()->create_user(['username' => 'jonest',
'email' => 'jonest@someplace.edu', 'firstname' => 'OLDNAME']);
$filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users.csv';
$clihelper = $this->construct_helper(["--file=$filepath", '--uutype='.UU_USER_UPDATE,
'--uuupdatetype='.UU_UPDATE_FILEOVERRIDE]);
ob_start();
$clihelper->process();
$output = ob_get_contents();
ob_end_clean();
// CLI output suggests that 1 user was created and 1 skipped.
$stats = $clihelper->get_stats();
$this->assertEquals(0, preg_match_all('/New user/', $output));
$this->assertEquals('Users updated: 1', $stats[0]);
$this->assertEquals('Users skipped: 1', $stats[1]);
// Tom Jones is enrolled into the course.
$enrols = array_values(enrol_get_course_users($course->id));
$this->assertEqualsCanonicalizing(['jonest'], [$enrols[0]->username]);
// User reznor is not created.
$this->assertFalse(\core_user::get_user_by_username('reznor'));
// User jonest is updated, new first name is Tom.
$this->assertEquals('Tom', \core_user::get_user_by_username('jonest')->firstname);
}
}
@@ -0,0 +1,72 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace tool_uploaduser;
use tool_uploaduser\local\field_value_validators;
/**
* Tests for field value validators of tool_uploaduser.
*
* @package tool_uploaduser
* @copyright 2019 Jun Pataleta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class field_value_validators_test extends \advanced_testcase {
/**
* Data provider for \field_value_validators_testcase::test_validate_theme().
*/
public function themes_provider() {
return [
'User themes disabled' => [
false, 'boost', 'warning', get_string('userthemesnotallowed', 'tool_uploaduser')
],
'User themes enabled, empty theme' => [
true, '', 'warning', get_string('notheme', 'tool_uploaduser')
],
'User themes enabled, invalid theme' => [
true, 'badtheme', 'warning', get_string('invalidtheme', 'tool_uploaduser', 'badtheme')
],
'User themes enabled, valid theme' => [
true, 'boost', 'normal', ''
],
];
}
/**
* Unit test for \tool_uploaduser\local\field_value_validators::validate_theme()
*
* @dataProvider themes_provider
* @param boolean $userthemesallowed Whether to allow user themes.
* @param string $themename The theme name to be tested.
* @param string $expectedstatus The expected status.
* @param string $expectedmessage The expected validation message.
*/
public function test_validate_theme($userthemesallowed, $themename, $expectedstatus, $expectedmessage): void {
$this->resetAfterTest();
// Set value for $CFG->allowuserthemes.
set_config('allowuserthemes', $userthemesallowed);
// Validate the theme.
list($status, $message) = field_value_validators::validate_theme($themename);
// Check the status and validation message.
$this->assertEquals($expectedstatus, $status);
$this->assertEquals($expectedmessage, $message);
}
}
@@ -0,0 +1,241 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace tool_uploaduser;
use advanced_testcase;
use context_system;
use context_course;
use context_coursecat;
use stdClass;
use tool_uploaduser\cli_helper;
use tool_uploaduser\local\text_progress_tracker;
/**
* Class upload_users_test
*
* @package tool_uploaduser
* @copyright 2020 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class upload_users_test extends advanced_testcase {
/**
* Load required test libraries
*/
public static function setUpBeforeClass(): void {
global $CFG;
require_once("{$CFG->dirroot}/{$CFG->admin}/tool/uploaduser/locallib.php");
}
/**
* Test upload users, enrol and role assignation
* @covers \tool_uploadusers::process
*/
public function test_user_can_upload_with_course_enrolment(): void {
$this->resetAfterTest();
set_config('passwordpolicy', 0);
$this->setAdminUser();
// Create category and course.
$coursecat = $this->getDataGenerator()->create_category();
$coursecatcontext = context_coursecat::instance($coursecat->id);
$course = $this->getDataGenerator()->create_course(['shortname' => 'course01', 'category' => $coursecat->id]);
$coursecontext = context_course::instance($course->id);
// Create user.
$user = $this->getDataGenerator()->create_user();
// Create role with capability to upload CSV files, and assign this role to user.
$uploadroleid = create_role('upload role', 'uploadrole', '');
set_role_contextlevels($uploadroleid, [CONTEXT_SYSTEM]);
$systemcontext = context_system::instance();
assign_capability('moodle/site:uploadusers', CAP_ALLOW, $uploadroleid, $systemcontext->id);
$this->getDataGenerator()->role_assign($uploadroleid, $user->id, $systemcontext->id);
// Create role with some of allowed capabilities to enrol users, and assign this role to user.
$enrolroleid = create_role('enrol role', 'enrolrole', '');
set_role_contextlevels($enrolroleid, [CONTEXT_COURSECAT]);
assign_capability('enrol/manual:enrol', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
assign_capability('moodle/course:enrolreview', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
assign_capability('moodle/role:assign', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
$this->getDataGenerator()->role_assign($enrolroleid, $user->id, $coursecatcontext->id);
// User makes assignments.
$studentarch = get_archetype_roles('student');
$studentrole = array_shift($studentarch);
core_role_set_assign_allowed($enrolroleid, $studentrole->id);
// Flush accesslib.
accesslib_clear_all_caches_for_unit_testing();
// Process CSV file as user.
$csv = <<<EOF
username,firstname,lastname,email,course1,role1
student1,Student,One,s1@example.com,{$course->shortname},{$studentrole->shortname}
student2,Student,Two,s2@example.com,{$course->shortname},teacher
EOF;
$this->setUser($user);
$output = $this->process_csv_upload($csv, ['--uutype=' . UU_USER_ADDNEW]);
$this->assertStringContainsString('Enrolled in "course01" as "student"', $output);
$this->assertStringContainsString('Unknown role "teacher"', $output);
// Check user creation, enrolment and role assignation.
$this->assertEquals(1, count_enrolled_users($coursecontext));
$usersasstudent = get_role_users($studentrole->id, $coursecontext);
$this->assertCount(1, $usersasstudent);
$this->assertEquals('student1', reset($usersasstudent)->username);
}
/**
* Test upload users, enrol and assign default role from manual enrol plugin.
* @covers \tool_uploadusers::process
*/
public function test_user_can_upload_with_course_enrolment_default_role(): void {
$this->resetAfterTest();
set_config('passwordpolicy', 0);
$this->setAdminUser();
// Create category and courses.
$coursecat = $this->getDataGenerator()->create_category();
$coursecatcontext = context_coursecat::instance($coursecat->id);
$course1 = $this->getDataGenerator()->create_course(['shortname' => 'course01', 'category' => $coursecat->id]);
$course1context = context_course::instance($course1->id);
// Change the default role to 'teacher'.
set_config('roleid', 4, 'enrol_manual');
$course2 = $this->getDataGenerator()->create_course(['shortname' => 'course02', 'category' => $coursecat->id]);
$course2context = context_course::instance($course2->id);
// Create user.
$user = $this->getDataGenerator()->create_user();
// Create role with capability to upload CSV files, and assign this role to user.
$uploadroleid = create_role('upload role', 'uploadrole', '');
set_role_contextlevels($uploadroleid, [CONTEXT_SYSTEM]);
$systemcontext = context_system::instance();
assign_capability('moodle/site:uploadusers', CAP_ALLOW, $uploadroleid, $systemcontext->id);
$this->getDataGenerator()->role_assign($uploadroleid, $user->id, $systemcontext->id);
// Create role with some of allowed capabilities to enrol users, and assign this role to user.
$enrolroleid = create_role('enrol role', 'enrolrole', '');
set_role_contextlevels($enrolroleid, [CONTEXT_COURSECAT]);
assign_capability('enrol/manual:enrol', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
assign_capability('moodle/course:enrolreview', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
assign_capability('moodle/role:assign', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
$this->getDataGenerator()->role_assign($enrolroleid, $user->id, $coursecatcontext->id);
// User makes assignments.
$studentarch = get_archetype_roles('student');
$studentrole = array_shift($studentarch);
core_role_set_assign_allowed($enrolroleid, $studentrole->id);
// Flush accesslib.
accesslib_clear_all_caches_for_unit_testing();
// Process CSV file (no roles specified) as user.
$csv = <<<EOF
username,firstname,lastname,email,course1,role1
student1,Student,One,s1@example.com,{$course1->shortname},
student2,Student,Two,s2@example.com,{$course2->shortname},
EOF;
$this->setUser($user);
$output = $this->process_csv_upload($csv, ['--uutype=' . UU_USER_ADDNEW]);
$this->assertStringContainsString('Enrolled in "course01" as "student"', $output);
// This $user cannot assign teacher role.
$this->assertStringContainsString('Unknown role "teacher"', $output);
// Check user creation, enrolment and role assignation.
$this->assertEquals(1, count_enrolled_users($course1context));
// This $user cannot enrol anyone as teacher.
$this->assertEquals(0, count_enrolled_users($course2context));
// Test user is enrolled as default-manual-enrol-plugin role.
$manualenrolinstance = new stdClass;
$enrolinstances = enrol_get_instances($course1->id, true);
foreach ($enrolinstances as $courseenrolinstance) {
if ($courseenrolinstance->enrol === 'manual') {
$manualenrolinstance = $courseenrolinstance;
break;
}
}
$defaulroleidexpected = $manualenrolinstance->roleid ?? 0;
// The default role of course01 is student, id 5.
$this->assertEquals(5, $defaulroleidexpected);
$usersasdefaultrole = get_role_users($defaulroleidexpected, $course1context);
$this->assertCount(1, $usersasdefaultrole);
$this->assertEquals('student1', reset($usersasdefaultrole)->username);
}
/**
* Test that invalid data contained in uploaded CSV triggers appropriate warnings
*/
public function test_user_upload_user_validate(): void {
$this->resetAfterTest();
$this->setAdminUser();
$csv = <<<EOF
username,firstname,lastname,email,country
student1,Student,One,s1@example.com,Wales
EOF;
$output = $this->process_csv_upload($csv, ['--uutype=' . UU_USER_ADDNEW]);
// We should get the debugging from the user class itself, as well as warning in the output regarding the same.
$this->assertDebuggingCalled('The property \'country\' has invalid data and has been cleaned.');
$this->assertStringContainsString('Incorrect data (country) found for user student1. ' .
'This data has been corrected or deleted.', $output);
}
/**
* Generate cli_helper and mock $_SERVER['argv']
*
* @param string $filecontent
* @param array $mockargv
* @return string
*/
protected function process_csv_upload(string $filecontent, array $mockargv = []): string {
$filepath = make_request_directory() . '/upload.csv';
file_put_contents($filepath, $filecontent);
$mockargv[] = "--file={$filepath}";
if (array_key_exists('argv', $_SERVER)) {
$oldservervars = $_SERVER['argv'];
}
$_SERVER['argv'] = array_merge([''], $mockargv);
$clihelper = new cli_helper(text_progress_tracker::class);
if (isset($oldservervars)) {
$_SERVER['argv'] = $oldservervars;
} else {
unset($_SERVER['argv']);
}
ob_start();
$clihelper->process();
$output = ob_get_contents();
ob_end_clean();
return $output;
}
}