Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
namespace tool_uploaduser;
18
 
19
use advanced_testcase;
20
use context_system;
21
use context_course;
22
use context_coursecat;
23
use stdClass;
24
use tool_uploaduser\cli_helper;
25
use tool_uploaduser\local\text_progress_tracker;
26
 
27
/**
28
 * Class upload_users_test
29
 *
30
 * @package    tool_uploaduser
31
 * @copyright  2020 Marina Glancy
32
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33
 */
1441 ariadna 34
final class upload_users_test extends advanced_testcase {
1 efrain 35
 
36
    /**
37
     * Load required test libraries
38
     */
39
    public static function setUpBeforeClass(): void {
40
        global $CFG;
41
 
42
        require_once("{$CFG->dirroot}/{$CFG->admin}/tool/uploaduser/locallib.php");
1441 ariadna 43
        parent::setUpBeforeClass();
1 efrain 44
    }
45
 
46
    /**
47
     * Test upload users, enrol and role assignation
48
     * @covers \tool_uploadusers::process
49
     */
50
    public function test_user_can_upload_with_course_enrolment(): void {
51
 
52
        $this->resetAfterTest();
53
        set_config('passwordpolicy', 0);
54
        $this->setAdminUser();
55
 
56
        // Create category and course.
57
        $coursecat = $this->getDataGenerator()->create_category();
58
        $coursecatcontext = context_coursecat::instance($coursecat->id);
59
        $course = $this->getDataGenerator()->create_course(['shortname' => 'course01', 'category' => $coursecat->id]);
60
        $coursecontext = context_course::instance($course->id);
61
 
62
        // Create user.
63
        $user = $this->getDataGenerator()->create_user();
64
 
65
        // Create role with capability to upload CSV files, and assign this role to user.
66
        $uploadroleid = create_role('upload role', 'uploadrole', '');
67
        set_role_contextlevels($uploadroleid, [CONTEXT_SYSTEM]);
68
        $systemcontext = context_system::instance();
69
        assign_capability('moodle/site:uploadusers', CAP_ALLOW, $uploadroleid, $systemcontext->id);
70
        $this->getDataGenerator()->role_assign($uploadroleid, $user->id, $systemcontext->id);
71
 
72
        // Create role with some of allowed capabilities to enrol users, and assign this role to user.
73
        $enrolroleid = create_role('enrol role', 'enrolrole', '');
74
        set_role_contextlevels($enrolroleid, [CONTEXT_COURSECAT]);
75
        assign_capability('enrol/manual:enrol', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
76
        assign_capability('moodle/course:enrolreview', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
77
        assign_capability('moodle/role:assign', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
78
        $this->getDataGenerator()->role_assign($enrolroleid, $user->id, $coursecatcontext->id);
79
 
80
        // User makes assignments.
81
        $studentarch = get_archetype_roles('student');
82
        $studentrole = array_shift($studentarch);
83
        core_role_set_assign_allowed($enrolroleid, $studentrole->id);
84
 
85
        // Flush accesslib.
86
        accesslib_clear_all_caches_for_unit_testing();
87
 
88
        // Process CSV file as user.
89
        $csv = <<<EOF
90
username,firstname,lastname,email,course1,role1
91
student1,Student,One,s1@example.com,{$course->shortname},{$studentrole->shortname}
92
student2,Student,Two,s2@example.com,{$course->shortname},teacher
93
EOF;
94
        $this->setUser($user);
95
        $output = $this->process_csv_upload($csv, ['--uutype=' . UU_USER_ADDNEW]);
96
 
97
        $this->assertStringContainsString('Enrolled in "course01" as "student"', $output);
98
        $this->assertStringContainsString('Unknown role "teacher"', $output);
99
 
100
        // Check user creation, enrolment and role assignation.
101
        $this->assertEquals(1, count_enrolled_users($coursecontext));
102
 
103
        $usersasstudent = get_role_users($studentrole->id, $coursecontext);
104
        $this->assertCount(1, $usersasstudent);
105
        $this->assertEquals('student1', reset($usersasstudent)->username);
106
    }
107
 
108
    /**
109
     * Test upload users, enrol and assign default role from manual enrol plugin.
110
     * @covers \tool_uploadusers::process
111
     */
112
    public function test_user_can_upload_with_course_enrolment_default_role(): void {
113
 
114
        $this->resetAfterTest();
115
        set_config('passwordpolicy', 0);
116
        $this->setAdminUser();
117
 
118
        // Create category and courses.
119
        $coursecat = $this->getDataGenerator()->create_category();
120
        $coursecatcontext = context_coursecat::instance($coursecat->id);
121
        $course1 = $this->getDataGenerator()->create_course(['shortname' => 'course01', 'category' => $coursecat->id]);
122
        $course1context = context_course::instance($course1->id);
123
        // Change the default role to 'teacher'.
124
        set_config('roleid', 4, 'enrol_manual');
125
        $course2 = $this->getDataGenerator()->create_course(['shortname' => 'course02', 'category' => $coursecat->id]);
126
        $course2context = context_course::instance($course2->id);
127
 
128
        // Create user.
129
        $user = $this->getDataGenerator()->create_user();
130
 
131
        // Create role with capability to upload CSV files, and assign this role to user.
132
        $uploadroleid = create_role('upload role', 'uploadrole', '');
133
        set_role_contextlevels($uploadroleid, [CONTEXT_SYSTEM]);
134
        $systemcontext = context_system::instance();
135
        assign_capability('moodle/site:uploadusers', CAP_ALLOW, $uploadroleid, $systemcontext->id);
136
        $this->getDataGenerator()->role_assign($uploadroleid, $user->id, $systemcontext->id);
137
 
138
        // Create role with some of allowed capabilities to enrol users, and assign this role to user.
139
        $enrolroleid = create_role('enrol role', 'enrolrole', '');
140
        set_role_contextlevels($enrolroleid, [CONTEXT_COURSECAT]);
141
        assign_capability('enrol/manual:enrol', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
142
        assign_capability('moodle/course:enrolreview', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
143
        assign_capability('moodle/role:assign', CAP_ALLOW, $enrolroleid, $coursecatcontext->id);
144
        $this->getDataGenerator()->role_assign($enrolroleid, $user->id, $coursecatcontext->id);
145
 
146
        // User makes assignments.
147
        $studentarch = get_archetype_roles('student');
148
        $studentrole = array_shift($studentarch);
149
        core_role_set_assign_allowed($enrolroleid, $studentrole->id);
150
 
151
        // Flush accesslib.
152
        accesslib_clear_all_caches_for_unit_testing();
153
 
154
        // Process CSV file (no roles specified) as user.
155
        $csv = <<<EOF
156
username,firstname,lastname,email,course1,role1
157
student1,Student,One,s1@example.com,{$course1->shortname},
158
student2,Student,Two,s2@example.com,{$course2->shortname},
159
EOF;
160
        $this->setUser($user);
161
        $output = $this->process_csv_upload($csv, ['--uutype=' . UU_USER_ADDNEW]);
162
 
163
        $this->assertStringContainsString('Enrolled in "course01" as "student"', $output);
164
        // This $user cannot assign teacher role.
165
        $this->assertStringContainsString('Unknown role "teacher"', $output);
166
 
167
        // Check user creation, enrolment and role assignation.
168
        $this->assertEquals(1, count_enrolled_users($course1context));
169
        // This $user cannot enrol anyone as teacher.
170
        $this->assertEquals(0, count_enrolled_users($course2context));
171
 
172
        // Test user is enrolled as default-manual-enrol-plugin role.
173
        $manualenrolinstance = new stdClass;
174
        $enrolinstances = enrol_get_instances($course1->id, true);
175
        foreach ($enrolinstances as $courseenrolinstance) {
176
            if ($courseenrolinstance->enrol === 'manual') {
177
                $manualenrolinstance = $courseenrolinstance;
178
                break;
179
            }
180
        }
181
        $defaulroleidexpected = $manualenrolinstance->roleid ?? 0;
182
        // The default role of course01 is student, id 5.
183
        $this->assertEquals(5, $defaulroleidexpected);
184
 
185
        $usersasdefaultrole = get_role_users($defaulroleidexpected, $course1context);
186
        $this->assertCount(1, $usersasdefaultrole);
187
        $this->assertEquals('student1', reset($usersasdefaultrole)->username);
188
    }
189
 
190
    /**
191
     * Test that invalid data contained in uploaded CSV triggers appropriate warnings
192
     */
193
    public function test_user_upload_user_validate(): void {
194
        $this->resetAfterTest();
195
        $this->setAdminUser();
196
 
197
        $csv = <<<EOF
198
username,firstname,lastname,email,country
199
student1,Student,One,s1@example.com,Wales
200
EOF;
201
 
202
        $output = $this->process_csv_upload($csv, ['--uutype=' . UU_USER_ADDNEW]);
203
 
204
        // We should get the debugging from the user class itself, as well as warning in the output regarding the same.
205
        $this->assertDebuggingCalled('The property \'country\' has invalid data and has been cleaned.');
206
        $this->assertStringContainsString('Incorrect data (country) found for user student1. ' .
207
            'This data has been corrected or deleted.', $output);
208
    }
209
 
210
    /**
211
     * Generate cli_helper and mock $_SERVER['argv']
212
     *
213
     * @param string $filecontent
214
     * @param array $mockargv
215
     * @return string
216
     */
217
    protected function process_csv_upload(string $filecontent, array $mockargv = []): string {
218
        $filepath = make_request_directory() . '/upload.csv';
219
        file_put_contents($filepath, $filecontent);
220
        $mockargv[] = "--file={$filepath}";
221
 
222
        if (array_key_exists('argv', $_SERVER)) {
223
            $oldservervars = $_SERVER['argv'];
224
        }
225
 
226
        $_SERVER['argv'] = array_merge([''], $mockargv);
227
        $clihelper = new cli_helper(text_progress_tracker::class);
228
 
229
        if (isset($oldservervars)) {
230
            $_SERVER['argv'] = $oldservervars;
231
        } else {
232
            unset($_SERVER['argv']);
233
        }
234
 
235
        ob_start();
236
        $clihelper->process();
237
        $output = ob_get_contents();
238
        ob_end_clean();
239
 
240
        return $output;
241
    }
242
}