Proyectos de Subversion Moodle

Rev

| 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
declare(strict_types=1);
18
 
19
namespace core_files\reportbuilder\datasource;
20
 
21
use core\context\{course, coursecat, user};
22
use core_reportbuilder_generator;
23
use core_reportbuilder_testcase;
24
use core_reportbuilder\local\filters\{boolean_select, date, filesize, select, text};
25
 
26
defined('MOODLE_INTERNAL') || die();
27
 
28
global $CFG;
29
require_once("{$CFG->dirroot}/reportbuilder/tests/helpers.php");
30
 
31
/**
32
 * Unit tests for files datasource
33
 *
34
 * @package     core_files
35
 * @covers      \core_files\reportbuilder\datasource\files
36
 * @copyright   2022 Paul Holden <paulh@moodle.com>
37
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38
 */
39
class files_test extends core_reportbuilder_testcase {
40
 
41
    /**
42
     * Test default datasource
43
     */
44
    public function test_datasource_default(): void {
45
        $this->resetAfterTest();
46
 
47
        $course = $this->getDataGenerator()->create_course();
48
        $coursecontext = course::instance($course->id);
49
 
50
        $user = $this->getDataGenerator()->create_user();
51
        $usercontext = user::instance($user->id);
52
 
53
        $this->setUser($user);
54
 
55
        $this->generate_test_files($coursecontext);
56
 
57
        /** @var core_reportbuilder_generator $generator */
58
        $generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
59
        $report = $generator->create_report(['name' => 'Files', 'source' => files::class, 'default' => 1]);
60
 
61
        $content = $this->get_custom_report_content($report->get('id'));
62
        $content = $this->filter_custom_report_content($content, static function(array $row): bool {
63
            return $row['c0_ctxid'] !== 'System';
64
        });
65
 
66
        $this->assertCount(2, $content);
67
 
68
        // Default columns are context, user, name, type, size, time created. Sorted by context and time created.
69
        [$contextname, $userfullname, $filename, $mimetype, $filesize, $timecreated] = array_values($content[0]);
70
        $this->assertEquals($coursecontext->get_context_name(), $contextname);
71
        $this->assertEquals(fullname($user), $userfullname);
72
        $this->assertEquals('Hello.txt', $filename);
73
        $this->assertEquals('Text file', $mimetype);
74
        $this->assertEquals("5\xc2\xa0bytes", $filesize);
75
        $this->assertNotEmpty($timecreated);
76
 
77
        [$contextname, $userfullname, $filename, $mimetype, $filesize, $timecreated] = array_values($content[1]);
78
        $this->assertEquals($usercontext->get_context_name(), $contextname);
79
        $this->assertEquals(fullname($user), $userfullname);
80
        $this->assertEquals('Hello.txt', $filename);
81
        $this->assertEquals('Text file', $mimetype);
82
        $this->assertEquals("5\xc2\xa0bytes", $filesize);
83
        $this->assertNotEmpty($timecreated);
84
    }
85
 
86
    /**
87
     * Test datasource columns that aren't added by default
88
     */
89
    public function test_datasource_non_default_columns(): void {
90
        global $OUTPUT;
91
 
92
        $this->resetAfterTest();
93
 
94
        $category = $this->getDataGenerator()->create_category();
95
        $categorycontext = coursecat::instance($category->id);
96
 
97
        $course = $this->getDataGenerator()->create_course(['category' => $category->id]);
98
        $coursecontext = course::instance($course->id);
99
 
100
        $user = $this->getDataGenerator()->create_user();
101
        $usercontext = user::instance($user->id);
102
 
103
        $this->setUser($user);
104
 
105
        $draftitemid = $this->generate_test_files($coursecontext);
106
 
107
        /** @var core_reportbuilder_generator $generator */
108
        $generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
109
        $report = $generator->create_report(['name' => 'Files', 'source' => files::class, 'default' => 0]);
110
 
111
        // Consistent order, sorted by context and content hash.
112
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'context:link',
113
            'sortenabled' => 1, 'sortorder' => 1]);
114
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'context:name']);
115
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'context:level']);
116
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'context:path']);
117
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'context:parent']);
118
 
119
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'file:icon']);
120
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'file:path']);
121
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'file:author']);
122
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'file:license']);
123
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'file:contenthash',
124
            'sortenabled' => 1, 'sortorder' => 2]);
125
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'file:component']);
126
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'file:area']);
127
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'file:itemid']);
128
 
129
        $content = $this->get_custom_report_content($report->get('id'));
130
        $content = $this->filter_custom_report_content($content, static function(array $row): bool {
131
            return stripos($row['c0_ctxid'], 'System') === false;
132
        });
133
 
134
        // There should be two entries (directory & file) for each context.
135
        $this->assertEquals([
136
            [
137
                "<a href=\"{$coursecontext->get_url()}\">{$coursecontext->get_context_name()}</a>",
138
                $coursecontext->get_context_name(),
139
                'Course',
140
                $coursecontext->path,
141
                $categorycontext->get_context_name(),
142
                '<img class="icon iconsize-medium" alt="Directory" title="Directory" src="' .
143
                    $OUTPUT->image_url('f/folder')->out() . '" />',
144
                '/',
145
                null,
146
                '',
147
                'da39a3ee5e6b4b0d3255bfef95601890afd80709',
148
                'course',
149
                'summary',
150
                0,
151
            ],
152
            [
153
                "<a href=\"{$coursecontext->get_url()}\">{$coursecontext->get_context_name()}</a>",
154
                $coursecontext->get_context_name(),
155
                'Course',
156
                $coursecontext->path,
157
                $categorycontext->get_context_name(),
158
                '<img class="icon iconsize-medium" alt="Text file" title="Text file" src="' .
159
                    $OUTPUT->image_url('f/text')->out() . '" />',
160
                '/',
161
                null,
162
                '',
163
                'f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0',
164
                'course',
165
                'summary',
166
                0,
167
            ],
168
            [
169
                "<a href=\"{$usercontext->get_url()}\">{$usercontext->get_context_name()}</a>",
170
                $usercontext->get_context_name(),
171
                'User',
172
                $usercontext->path,
173
                'System',
174
                '<img class="icon iconsize-medium" alt="Directory" title="Directory" src="' .
175
                    $OUTPUT->image_url('f/folder')->out() . '" />',
176
                '/',
177
                null,
178
                '',
179
                'da39a3ee5e6b4b0d3255bfef95601890afd80709',
180
                'user',
181
                'draft',
182
                $draftitemid,
183
            ],
184
            [
185
                "<a href=\"{$usercontext->get_url()}\">{$usercontext->get_context_name()}</a>",
186
                $usercontext->get_context_name(),
187
                'User',
188
                $usercontext->path,
189
                'System',
190
                '<img class="icon iconsize-medium" alt="Text file" title="Text file" src="' .
191
                    $OUTPUT->image_url('f/text')->out() . '" />',
192
                '/',
193
                null,
194
                '',
195
                'f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0',
196
                'user',
197
                'draft',
198
                $draftitemid,
199
            ],
200
        ], array_map('array_values', $content));
201
    }
202
 
203
    /**
204
     * Data provider for {@see test_datasource_filters}
205
     *
206
     * @return array[]
207
     */
208
    public function datasource_filters_provider(): array {
209
        return [
210
            // File.
211
            'Filter directory' => ['file:directory', [
212
                'file:directory_operator' => boolean_select::CHECKED,
213
            ], 2],
214
            'Filter draft' => ['file:draft', [
215
                'file:draft_operator' => boolean_select::CHECKED,
216
            ], 2],
217
            'Filter name' => ['file:name', [
218
                'file:name_operator' => text::IS_EQUAL_TO,
219
                'file:name_value' => 'Hello.txt',
220
            ], 2],
221
            'Filter size' => ['file:size', [
222
                'file:size_operator' => filesize::GREATER_THAN,
223
                'file:size_value1' => 2,
224
                'file:size_unit' => filesize::SIZE_UNIT_BYTE,
225
            ], 2],
226
            'Filter type' => ['file:type', [
227
                'file:type_operator' => select::EQUAL_TO,
228
                'file:type_value' => 'text/plain',
229
            ], 2],
230
            'Filter type (non match)' => ['file:type', [
231
                'file:type_operator' => select::EQUAL_TO,
232
                'file:type_value' => 'image/png',
233
            ], 0],
234
            'Filter license' => ['file:license', [
235
                'file:license_operator' => select::EQUAL_TO,
236
                'file:license_value' => 'unknown',
237
            ], 4],
238
            'Filter license (non match)' => ['file:license', [
239
                'file:license_operator' => select::EQUAL_TO,
240
                'file:license_value' => 'public',
241
            ], 0],
242
            'Filter content hash' => ['file:contenthash', [
243
                'file:contenthash_operator' => text::IS_EQUAL_TO,
244
                'file:contenthash_value' => 'f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0',
245
            ], 2],
246
            'Filter content hash (no match)' => ['file:contenthash', [
247
                'file:contenthash_operator' => text::IS_EQUAL_TO,
248
                'file:contenthash_value' => 'f00f',
249
            ], 0],
250
            'Filter time created' => ['file:timecreated', [
251
                'file:timecreated_operator' => date::DATE_RANGE,
252
                'file:timecreated_from' => 1622502000,
253
            ], 4],
254
            'Filter time created (non match)' => ['file:timecreated', [
255
                'file:timecreated_operator' => date::DATE_RANGE,
256
                'file:timecreated_to' => 1622502000,
257
            ], 0],
258
 
259
            // Context.
260
            'Context level' => ['context:level', [
261
                'context:level_operator' => select::EQUAL_TO,
262
                'context:level_value' => CONTEXT_COURSE,
263
            ], 2],
264
            'Context level (no match)' => ['context:level', [
265
                'context:level_operator' => select::EQUAL_TO,
266
                'context:level_value' => CONTEXT_BLOCK,
267
            ], 0],
268
            'Context path' => ['context:path', [
269
                'context:path_operator' => text::STARTS_WITH,
270
                'context:path_value' => '/1/',
271
            ], 4],
272
            'Context path (no match)' => ['context:path', [
273
                'context:path_operator' => text::STARTS_WITH,
274
                'context:path_value' => '/1/2/3/',
275
            ], 0],
276
 
277
            // User.
278
            'Filter user' => ['user:username', [
279
                'user:username_operator' => text::IS_EQUAL_TO,
280
                'user:username_value' => 'alfie',
281
            ], 4],
282
            'Filter user (no match)' => ['user:username', [
283
                'user:username_operator' => text::IS_EQUAL_TO,
284
                'user:username_value' => 'lionel',
285
            ], 0],
286
        ];
287
    }
288
 
289
    /**
290
     * Test datasource filters
291
     *
292
     * @param string $filtername
293
     * @param array $filtervalues
294
     * @param int $expectmatchcount
295
     *
296
     * @dataProvider datasource_filters_provider
297
     */
298
    public function test_datasource_filters(
299
        string $filtername,
300
        array $filtervalues,
301
        int $expectmatchcount
302
    ): void {
303
        $this->resetAfterTest();
304
        $this->setAdminUser();
305
 
306
        $user = $this->getDataGenerator()->create_user(['username' => 'alfie']);
307
        $this->setUser($user);
308
 
309
        $course = $this->getDataGenerator()->create_course();
310
        $coursecontext = course::instance($course->id);
311
 
312
        $this->generate_test_files($coursecontext);
313
 
314
        /** @var core_reportbuilder_generator $generator */
315
        $generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
316
 
317
        // Create report containing single column, and given filter.
318
        $report = $generator->create_report(['name' => 'Files', 'source' => files::class, 'default' => 0]);
319
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'context:name']);
320
 
321
        // Add filter, set it's values.
322
        $generator->create_filter(['reportid' => $report->get('id'), 'uniqueidentifier' => $filtername]);
323
        $content = $this->get_custom_report_content($report->get('id'), 0, $filtervalues);
324
        $content = $this->filter_custom_report_content($content, static function(array $row): bool {
325
            return stripos($row['c0_ctxid'], 'System') === false;
326
        });
327
 
328
        $this->assertCount($expectmatchcount, $content);
329
    }
330
 
331
    /**
332
     * Stress test datasource
333
     *
334
     * In order to execute this test PHPUNIT_LONGTEST should be defined as true in phpunit.xml or directly in config.php
335
     */
336
    public function test_stress_datasource(): void {
337
        if (!PHPUNIT_LONGTEST) {
338
            $this->markTestSkipped('PHPUNIT_LONGTEST is not defined');
339
        }
340
 
341
        $this->resetAfterTest();
342
        $this->setAdminUser();
343
 
344
        $course = $this->getDataGenerator()->create_course();
345
        $coursecontext = course::instance($course->id);
346
 
347
        $this->generate_test_files($coursecontext);
348
 
349
        $this->datasource_stress_test_columns(files::class);
350
        $this->datasource_stress_test_columns_aggregation(files::class);
351
        $this->datasource_stress_test_conditions(files::class, 'file:path');
352
    }
353
 
354
    /**
355
     * Ensuring report content only includes files we have explicitly created within the test
356
     *
357
     * @param array $content
358
     * @param callable $callback
359
     * @return array
360
     */
361
    protected function filter_custom_report_content(array $content, callable $callback): array {
362
        $content = array_filter($content, $callback);
363
        return array_values($content);
364
    }
365
 
366
    /**
367
     * Helper method to generate some test files (a user draft and course summary file) for reporting on
368
     *
369
     * @param course $context
370
     * @return int Draft item ID
371
     */
372
    protected function generate_test_files(course $context): int {
373
        global $USER;
374
 
375
        $draftitemid = file_get_unused_draft_itemid();
376
 
377
        // Populate user draft.
378
        get_file_storage()->create_file_from_string([
379
            'contextid' => user::instance($USER->id)->id,
380
            'userid' => $USER->id,
381
            'component' => 'user',
382
            'filearea' => 'draft',
383
            'itemid' => $draftitemid,
384
            'filepath' => '/',
385
            'filename' => 'Hello.txt',
386
        ], 'Hello');
387
 
388
        // Save draft to course summary file area.
389
        file_save_draft_area_files($draftitemid, $context->id, 'course', 'summary', 0);
390
 
391
        return $draftitemid;
392
    }
393
}