Proyectos de Subversion Moodle

Rev

Rev 11 | | 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 qbank_columnsortorder;
18
 
19
defined('MOODLE_INTERNAL') || die();
20
 
21
use advanced_testcase;
22
use context_course;
23
use core_question\local\bank\column_base;
24
use core_question\local\bank\question_edit_contexts;
25
use core_question\local\bank\view;
26
use moodle_url;
27
 
28
global $CFG;
29
require_once($CFG->dirroot . '/question/tests/fixtures/testable_core_question_column.php');
30
require_once($CFG->dirroot . '/question/classes/external.php');
31
 
32
/**
33
 * Test class for columnsortorder feature.
34
 *
35
 * @package    qbank_columnsortorder
36
 * @copyright  2021 Catalyst IT Australia Pty Ltd
37
 * @author     Ghaly Marc-Alexandre <marc-alexandreghaly@catalyst-ca.net>
38
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39
 * @covers \qbank_columnsortorder\column_manager
40
 */
1441 ariadna 41
final class column_manager_test extends advanced_testcase {
1 efrain 42
 
43
    /**
44
     * Generate a course and return a question bank view for the course context.
45
     *
46
     * @return view
47
     */
48
    protected static function get_question_bank(): view {
49
        $course = self::getDataGenerator()->create_course();
1441 ariadna 50
        $qbank = self::getDataGenerator()->create_module('qbank', ['course' => $course->id]);
51
        $cm = get_coursemodule_from_id('qbank', $qbank->cmid);
1 efrain 52
        $questionbank = new view(
1441 ariadna 53
            new question_edit_contexts(\context_module::instance($qbank->cmid)),
1 efrain 54
            new moodle_url('/'),
1441 ariadna 55
            $course,
56
            $cm
1 efrain 57
        );
58
        return $questionbank;
59
    }
60
 
61
    /**
62
     * Return an array of visible columns for the question bank.
63
     *
64
     * @return array
65
     */
66
    protected static function get_columns(): array {
67
        $questionbank = self::get_question_bank();
68
        $columns = [];
69
        foreach ($questionbank->get_visiblecolumns() as $column) {
70
            $columns[] = $column->get_column_id();
71
        }
72
        return $columns;
73
    }
74
 
75
    /**
76
     * Provide examples for testing each column setting function, with test data and data format.
77
     *
78
     * @return array[]
79
     */
80
    public static function settings_provider(): array {
81
        return [
82
            'Test set_column_order' => [
83
                'setting' => 'enabledcol',
84
                'function' => 'set_column_order',
85
                'datamethod' => [__CLASS__, 'get_columns'],
86
                'csv' => true,
87
            ],
88
            'Test set_hidden_columns' => [
89
                'setting' => 'hiddencols',
90
                'function' => 'set_hidden_columns',
91
                'datamethod' => [__CLASS__, 'get_columns'],
92
                'csv' => true,
93
            ],
94
            'Test set_column_size' => [
95
                'setting' => 'colsize',
96
                'function' => 'set_column_size',
97
                'datamethod' => 'random_string',
98
                'csv' => false,
99
            ],
100
        ];
101
    }
102
 
103
    /**
104
     * Retrieve data using the specified method.
105
     * This function is used to retrieve data from various data methods defined within this class.
106
     *
107
     * @param array|string $datamethod This can be either a function name or an array containing the class and method name.
108
     * @return array|string The retrieved data as an array or string, depending on the data method used.
109
     */
110
    protected function get_data_from_datamethod(array|string $datamethod): array|string {
111
        return call_user_func($datamethod);
112
    }
113
 
114
 
115
    /**
116
     * Test setting config settings
117
     *
118
     * @dataProvider settings_provider
119
     * @param string $setting The name of the setting being saved
120
     * @param string $function The name of the function being called
121
     * @param array|string $datamethod The property of the test class to pass to the function.
122
     * @param bool $csv True of the data is stored as a comma-separated list.
123
     * @return void
124
     */
125
    public function test_settings(
126
        string $setting,
127
        string $function,
128
        array|string $datamethod,
129
        bool $csv,
130
    ): void {
131
        $data = $this->get_data_from_datamethod($datamethod);
132
        $this->setAdminUser();
133
        $this->resetAfterTest(true);
134
        $this->assertFalse(get_config('qbank_columnsortorder', $setting));
135
        $this->assertEmpty(get_user_preferences('qbank_columnsortorder_' . $setting));
136
        column_manager::{$function}($data, true);
137
        $expected = $csv ? implode(',', $data) : $data;
138
        $this->assertEquals($expected, get_config('qbank_columnsortorder', $setting));
139
        $this->assertEmpty(get_user_preferences('qbank_columnsortorder_' . $setting));
140
    }
141
 
142
    /**
143
     * Test passing null clears the corresponding config setting.
144
     *
145
     * @dataProvider settings_provider
146
     * @param string $setting The name of the setting being saved
147
     * @param string $function The name of the function being called
148
     * @param array|string $datamethod The property of the test class to pass to the function.
149
     * @param bool $csv True of the data is stored as a comma-separated list.
150
     * @return void
151
     */
152
    public function test_reset_settings(
153
        string $setting,
154
        string $function,
155
        array|string $datamethod,
156
        bool $csv,
157
    ): void {
158
        $data = $this->get_data_from_datamethod($datamethod);
159
        $this->setAdminUser();
160
        $this->resetAfterTest(true);
161
        $initial = $csv ? implode(',', $data) : $data;
162
        set_config($setting, $initial, 'qbank_columnsortorder');
163
        $this->assertEquals($initial, get_config('qbank_columnsortorder', $setting));
164
        column_manager::{$function}(null, true);
165
        $this->assertFalse(get_config('qbank_columnsortorder', $setting));
166
    }
167
 
168
    /**
169
     * Test setting user preferences
170
     *
171
     * @dataProvider settings_provider
172
     * @param string $setting The name of the setting being saved
173
     * @param string $function The name of the function being called
174
     * @param array|string $datamethod The property of the test class to pass to the function.
175
     * @param bool $csv True of the data is stored as a comma-separated list.
176
     * @return void
177
     */
178
    public function test_settings_user(
179
        string $setting,
180
        string $function,
181
        array|string $datamethod,
182
        bool $csv,
183
    ): void {
184
        $this->resetAfterTest(true);
185
        $data = $this->get_data_from_datamethod($datamethod);
186
        $this->assertFalse(get_config('qbank_columnsortorder', $setting));
187
        $this->assertEmpty(get_user_preferences('qbank_columnsortorder_' . $setting));
188
        column_manager::{$function}($data);
189
        $expected = $csv ? implode(',', $data) : $data;
190
        $this->assertFalse(get_config('qbank_columnsortorder', $setting));
191
        $this->assertEquals($expected, get_user_preferences('qbank_columnsortorder_' . $setting));
192
    }
193
 
194
    /**
195
     * Test passing null clears the corresponding user preference.
196
     *
197
     * @dataProvider settings_provider
198
     * @param string $setting The name of the setting being saved
199
     * @param string $function The name of the function being called
200
     * @param array|string $datamethod The property of the test class to pass to the function.
201
     * @param bool $csv True of the data is stored as a comma-separated list.
202
     * @return void
203
     */
204
    public function test_reset_user_settings(
205
        string $setting,
206
        string $function,
207
        array|string $datamethod,
208
        bool $csv,
209
    ): void {
210
        $data = $this->get_data_from_datamethod($datamethod);
211
        $this->setAdminUser();
212
        $this->resetAfterTest(true);
213
        $initial = $csv ? implode(',', $data) : $data;
214
        set_user_preference('qbank_columnsortorder_' . $setting, $initial);
215
        $this->assertEquals($initial, get_user_preferences('qbank_columnsortorder_' . $setting));
216
        column_manager::{$function}(null);
217
        $this->assertEmpty(get_user_preferences('qbank_columnsortorder_' . $setting));
218
    }
219
 
220
    /**
221
     * Test function get_columns in helper class, that proper data is returned.
222
     *
223
     * @covers ::get_columns
224
     */
225
    public function test_getcolumns_function(): void {
226
        $this->resetAfterTest(true);
227
        $this->setAdminUser();
228
        $columnmanager = new column_manager(true);
229
        $questionlistcolumns = $columnmanager->get_columns();
230
        $this->assertIsArray($questionlistcolumns);
231
        foreach ($questionlistcolumns as $columnnobject) {
232
            $this->assertObjectHasProperty('class', $columnnobject);
233
            $this->assertObjectHasProperty('name', $columnnobject);
234
            $this->assertObjectHasProperty('colname', $columnnobject);
235
        }
236
    }
237
 
238
    /**
239
     * The get_sorted_columns method should return the provided columns sorted according to enabledcol setting.
240
     *
241
     * @return void
242
     */
243
    public function test_get_sorted_columns(): void {
244
        $this->resetAfterTest(true);
245
        $this->setAdminUser();
246
        $questionbank = $this->get_question_bank();
247
        $columns = $this->get_columns($questionbank);
248
        $neworder = $columns;
249
        shuffle($neworder);
250
        set_config('enabledcol', implode(',', $neworder), 'qbank_columnsortorder');
251
 
252
        $columnmanager = new column_manager(true);
253
        $columnstosort = [];
254
        foreach ($columns as $column) {
255
            $columnstosort[$column] = $column;
256
        }
257
 
258
        $sortedcolumns = $columnmanager->get_sorted_columns($columnstosort);
259
 
260
        $expectedorder = ['core_question\local\bank\checkbox_column' . column_base::ID_SEPARATOR . 'checkbox_column' => 0];
261
        foreach ($neworder as $columnid) {
262
            $expectedorder[$columnid] = $columnid;
263
        }
264
        $this->assertSame($expectedorder, $sortedcolumns);
265
    }
266
 
267
    /**
268
     * Test disabled columns are removed from enabledcol setting and added to disabledcol setting.
269
     *
270
     * @return void
271
     */
272
    public function test_disable_columns(): void {
273
        $this->resetAfterTest(true);
274
        $this->setAdminUser();
275
        $questionbank = $this->get_question_bank();
276
        $columns = $this->get_columns($questionbank);
277
        // Set up enabledcol with all plugins.
278
        set_config('enabledcol', implode(',', $columns), 'qbank_columnsortorder');
279
        $questionbank = $this->get_question_bank();
280
        $columns = $this->get_columns($questionbank);
281
        $columnmanager = new column_manager(true);
282
        $this->assertFalse(get_config('qbank_columnsortorder', 'disabledcol'));
283
 
284
        // Disable a random plugin.
285
        $plugincolumns = array_filter($columns, fn($column) => str_starts_with($column, 'qbank_'));
286
        $randomcolumn = $plugincolumns[array_rand($plugincolumns, 1)];
287
        $randomplugin = explode('\\', $randomcolumn)[0];
288
        $columnmanager->disable_columns($randomplugin);
289
 
290
        // The enabledcol setting should now contain all columns except the disabled plugin.
291
        $expectedconfig = array_filter($columns, fn($column) => !str_starts_with($column, $randomplugin));
292
        sort($expectedconfig);
293
        $newconfig = explode(',', get_config('qbank_columnsortorder', 'enabledcol'));
294
        sort($newconfig);
295
        $this->assertEquals($expectedconfig, $newconfig);
296
        $this->assertNotContains($randomcolumn, $newconfig);
297
        // The disabledcol setting should only contain columns from the disabled plugin.
298
        $disabledconfig = explode(',', get_config('qbank_columnsortorder', 'disabledcol'));
299
        array_walk($disabledconfig, fn($column) => $this->assertStringStartsWith($randomplugin, $column));
300
    }
301
 
302
    /**
303
     * Test enabling and disabling columns through event observers
304
     *
305
     * @covers \qbank_columnsortorder\event\plugin_observer
306
     */
307
    public function test_plugin_enabled_disabled_observers(): void {
308
        $this->resetAfterTest(true);
309
        $this->setAdminUser();
310
        $questionbank = $this->get_question_bank();
311
        $columns = $this->get_columns($questionbank);
312
        $columnmanager = new column_manager(true);
313
        $neworder = $columnmanager->get_sorted_columns($columns);
314
        shuffle($neworder);
315
        $columnmanager::set_column_order($neworder, true);
316
        // Get the list of enabled columns, excluding core columns (we can't disable those).
317
        $currentconfig = get_config('qbank_columnsortorder', 'enabledcol');
318
        $currentconfig = array_filter(explode(',', $currentconfig), fn($class) => !str_starts_with($class, 'core'));
319
        // Pick a column at random and get its plugin name.
320
        $randomcolumnid = $currentconfig[array_rand($currentconfig, 1)];
321
        [$randomcolumnclass] = explode(column_base::ID_SEPARATOR, $randomcolumnid, 2);
322
        [$randomplugintodisable] = explode('\\', $randomcolumnclass);
323
        $olddisabledconfig = get_config('qbank_columnsortorder', 'disabledcol');
324
        \core\event\qbank_plugin_disabled::create_for_plugin($randomplugintodisable)->trigger();
325
        $newdisabledconfig = get_config('qbank_columnsortorder', 'disabledcol');
326
        $this->assertNotEquals($olddisabledconfig, $newdisabledconfig);
327
        \core\event\qbank_plugin_enabled::create_for_plugin($randomplugintodisable)->trigger();
328
        $newdisabledconfig = get_config('qbank_columnsortorder', 'disabledcol');
329
        $this->assertEmpty($newdisabledconfig);
330
        $enabledconfig = get_config('qbank_columnsortorder', 'enabledcol');
331
        $contains = strpos($enabledconfig, $randomplugintodisable);
332
        $this->assertNotFalse($contains);
333
        $this->assertIsInt($contains);
334
    }
335
 
336
    /**
337
     * Test enabled columns are removed from disabledcol setting and added to enabledcol setting.
338
     *
339
     * @return void
340
     */
11 efrain 341
    public function test_enable_columns(): void {
1 efrain 342
        $this->resetAfterTest(true);
343
        $this->setAdminUser();
344
        $questionbank = $this->get_question_bank();
345
        $columns = $this->get_columns($questionbank);
346
        // Set up disablecol with columns from 2 random plugins, and enabledcol with all other columns.
347
        $plugincolumns = array_filter($columns, fn($column) => str_starts_with($column, 'qbank_'));
348
        $plugins = array_unique(array_map(fn($column) => explode('\\', $column)[0], $plugincolumns));
349
        $randomplugins = array_rand($plugins, 2);
350
        $randomplugin1 = $plugins[$randomplugins[0]];
351
        $randomplugin2 = $plugins[$randomplugins[1]];
352
 
353
        $disabledcols = array_filter(
354
            $columns,
355
            fn($column) => str_starts_with($column, $randomplugin1) || str_starts_with($column, $randomplugin2)
356
        );
357
        $enabledcols = array_diff($columns, $disabledcols);
358
 
359
        set_config('enabledcol', implode(',', $enabledcols), 'qbank_columnsortorder');
360
        set_config('disabledcol', implode(',', $disabledcols), 'qbank_columnsortorder');
361
 
362
        // Enable one of the disabled plugins.
363
        $columnmanager = new column_manager(true);
364
        $columnmanager->enable_columns($randomplugin1);
365
        // The enabledcol setting should now contain all columns except the remaining disabled plugin.
366
        $expectedenabled = array_filter($columns, fn($column) => !str_starts_with($column, $randomplugin2));
367
        $expecteddisabled = array_filter($disabledcols, fn($column) => str_starts_with($column, $randomplugin2));
368
        sort($expectedenabled);
369
        sort($expecteddisabled);
370
        $newenabled = explode(',', get_config('qbank_columnsortorder', 'enabledcol'));
371
        sort($newenabled);
372
        $this->assertEquals($expectedenabled, $newenabled);
373
        $this->assertNotContains(reset($expecteddisabled), $newenabled);
374
        // The disabledcol setting should only contain columns from the remaining disabled plugin.
375
        $newdisabled = explode(',', get_config('qbank_columnsortorder', 'disabledcol'));
376
        array_walk($newdisabled, fn($column) => $this->assertStringStartsWith($randomplugin2, $column));
377
    }
378
 
379
    /**
380
     * Test that get_disabled_columns returns names of all the columns in the disabledcol setting
381
     *
382
     * @return void
383
     */
384
    public function test_get_disabled_columns(): void {
385
        $this->resetAfterTest(true);
386
        $this->setAdminUser();
387
        $questionbank = $this->get_question_bank();
388
        $columns = $this->get_columns($questionbank);
389
        // Set up disablecol with columns from 2 random plugins, and enabledcol with all other columns.
390
        $plugincolumns = array_filter($columns, fn($column) => str_starts_with($column, 'qbank_'));
391
        $randomcolumn = $plugincolumns[array_rand($plugincolumns, 1)];
392
        $randomplugin = explode('\\', $randomcolumn)[0];
393
 
394
        $disabledcols = array_filter($columns, fn($column) => str_starts_with($column, $randomplugin));
395
 
396
        set_config('disabledcol', implode(',', $disabledcols), 'qbank_columnsortorder');
397
 
398
        $columnmanager = new column_manager(true);
399
        $expecteddisablednames = [];
400
        foreach ($disabledcols as $disabledcolid) {
401
            [$columnclass, $columnname] = explode(column_base::ID_SEPARATOR, $disabledcolid, 2);
402
            $columnobject = $columnclass::from_column_name($questionbank, $columnname);
403
            $expecteddisablednames[$disabledcolid] = (object) [
404
                'disabledname' => $columnobject->get_title(),
405
            ];
406
        }
407
        $disablednames = $columnmanager->get_disabled_columns();
408
        $this->assertEquals($expecteddisablednames, $disablednames);
409
    }
410
}