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
/**
18
 * Exporter testcase.
19
 *
20
 * @package    core
21
 * @copyright  2015 Damyon Wiese
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
namespace core;
26
 
27
use core_external\external_format_value;
28
use core_external\external_multiple_structure;
29
use core_external\external_settings;
30
use core_external\external_single_structure;
31
use core_external\external_value;
32
use core_external\util;
33
 
34
/**
35
 * Exporter testcase.
36
 *
37
 * @package    core
38
 * @copyright  2015 Damyon Wiese
39
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40
 */
41
class exporter_test extends \advanced_testcase {
42
 
43
    protected $validrelated = null;
44
    protected $invalidrelated = null;
45
    protected $validdata = null;
46
    protected $invaliddata = null;
47
 
48
    public function setUp(): void {
49
        $s = new \stdClass();
50
        $this->validrelated = array(
51
            'simplestdClass' => $s,
52
            'arrayofstdClass' => array($s, $s),
53
            'context' => null,
54
            'aint' => 5,
55
            'astring' => 'valid string',
56
            'abool' => false,
57
            'ints' => []
58
        );
59
        $this->invalidrelated = array(
60
            'simplestdClass' => 'a string',
61
            'arrayofstdClass' => 5,
62
            'context' => null,
63
            'aint' => false,
64
            'astring' => 4,
65
            'abool' => 'not a boolean',
66
            'ints' => null
67
        );
68
 
69
        $this->validdata = array('stringA' => 'A string', 'stringAformat' => FORMAT_HTML, 'intB' => 4);
70
 
71
        $this->invaliddata = array('stringA' => 'A string');
72
    }
73
 
11 efrain 74
    public function test_get_read_structure(): void {
1 efrain 75
        $structure = core_testable_exporter::get_read_structure();
76
 
77
        $this->assertInstanceOf(external_single_structure::class, $structure);
78
        $this->assertInstanceOf(external_value::class, $structure->keys['stringA']);
79
        $this->assertInstanceOf(external_format_value::class, $structure->keys['stringAformat']);
80
        $this->assertInstanceOf(external_value::class, $structure->keys['intB']);
81
        $this->assertInstanceOf(external_value::class, $structure->keys['otherstring']);
82
        $this->assertInstanceOf(external_multiple_structure::class, $structure->keys['otherstrings']);
83
    }
84
 
11 efrain 85
    public function test_get_create_structure(): void {
1 efrain 86
        $structure = core_testable_exporter::get_create_structure();
87
 
88
        $this->assertInstanceOf(external_single_structure::class, $structure);
89
        $this->assertInstanceOf(external_value::class, $structure->keys['stringA']);
90
        $this->assertInstanceOf(external_format_value::class, $structure->keys['stringAformat']);
91
        $this->assertInstanceOf(external_value::class, $structure->keys['intB']);
92
        $this->assertArrayNotHasKey('otherstring', $structure->keys);
93
        $this->assertArrayNotHasKey('otherstrings', $structure->keys);
94
    }
95
 
11 efrain 96
    public function test_get_update_structure(): void {
1 efrain 97
        $structure = core_testable_exporter::get_update_structure();
98
 
99
        $this->assertInstanceOf(external_single_structure::class, $structure);
100
        $this->assertInstanceOf(external_value::class, $structure->keys['stringA']);
101
        $this->assertInstanceOf(external_format_value::class, $structure->keys['stringAformat']);
102
        $this->assertInstanceOf(external_value::class, $structure->keys['intB']);
103
        $this->assertArrayNotHasKey('otherstring', $structure->keys);
104
        $this->assertArrayNotHasKey('otherstrings', $structure->keys);
105
    }
106
 
11 efrain 107
    public function test_invalid_data(): void {
1 efrain 108
        global $PAGE;
109
        $exporter = new core_testable_exporter($this->invaliddata, $this->validrelated);
110
        $output = $PAGE->get_renderer('core');
111
 
112
        // The exception message is a bit misleading, it actually indicates an expected property wasn't found.
113
        $this->expectException(\coding_exception::class);
114
        $this->expectExceptionMessage('Unexpected property stringAformat');
115
        $result = $exporter->export($output);
116
    }
117
 
11 efrain 118
    public function test_invalid_related(): void {
1 efrain 119
        $this->expectException(\coding_exception::class);
120
        $this->expectExceptionMessage('Exporter class is missing required related data: (core\core_testable_exporter) ' .
121
            'simplestdClass => stdClass');
122
        $exporter = new core_testable_exporter($this->validdata, $this->invalidrelated);
123
    }
124
 
11 efrain 125
    public function test_invalid_related_all_cases(): void {
1 efrain 126
        global $PAGE;
127
 
128
        foreach ($this->invalidrelated as $key => $value) {
129
            $data = $this->validrelated;
130
            $data[$key] = $value;
131
 
132
            try {
133
                $exporter = new core_testable_exporter($this->validdata, $data);
134
                $output = $PAGE->get_renderer('core');
135
                $result = $exporter->export($output);
136
            } catch (\coding_exception $e) {
137
                $this->assertNotFalse(strpos($e->getMessage(), $key));
138
            }
139
        }
140
    }
141
 
11 efrain 142
    public function test_valid_data_and_related(): void {
1 efrain 143
        global $PAGE;
144
        $output = $PAGE->get_renderer('core');
145
        $exporter = new core_testable_exporter($this->validdata, $this->validrelated);
146
        $result = $exporter->export($output);
147
        $this->assertSame('>Another string', $result->otherstring);
148
        $this->assertSame(array('String &gt;a', 'String b'), $result->otherstrings);
149
    }
150
 
11 efrain 151
    public function test_format_text(): void {
1 efrain 152
        global $PAGE;
153
 
154
        $this->resetAfterTest();
155
        $course = $this->getDataGenerator()->create_course();
156
        $syscontext = \context_system::instance();
157
        $coursecontext = \context_course::instance($course->id);
158
 
159
        external_settings::get_instance()->set_filter(true);
160
        filter_set_global_state('urltolink', TEXTFILTER_OFF);
161
        filter_set_local_state('urltolink', $coursecontext->id, TEXTFILTER_ON);
162
        set_config('formats', FORMAT_MARKDOWN, 'filter_urltolink');
163
        \filter_manager::reset_caches();
164
 
165
        $data = [
166
            'stringA' => '__Watch out:__ https://moodle.org @@PLUGINFILE@@/test.pdf',
167
            'stringAformat' => FORMAT_MARKDOWN,
168
            'intB' => 1
169
        ];
170
 
171
        // Export simulated in the system context.
172
        $output = $PAGE->get_renderer('core');
173
        $exporter = new core_testable_exporter($data, ['context' => $syscontext] + $this->validrelated);
174
        $result = $exporter->export($output);
175
 
176
        $youtube = 'https://moodle.org';
177
        $fileurl = (new \moodle_url('/webservice/pluginfile.php/' . $syscontext->id . '/test/area/9/test.pdf'))->out(false);
178
        $expected = "<p><strong>Watch out:</strong> $youtube $fileurl</p>\n";
179
        $this->assertEquals($expected, $result->stringA);
180
        $this->assertEquals(FORMAT_HTML, $result->stringAformat);
181
 
182
        // Export simulated in the course context where the filter is enabled.
183
        $exporter = new core_testable_exporter($data, ['context' => $coursecontext] + $this->validrelated);
184
        $result = $exporter->export($output);
185
        $youtube = '<a href="https://moodle.org" class="_blanktarget">https://moodle.org</a>';
186
        $fileurl = (new \moodle_url('/webservice/pluginfile.php/' . $coursecontext->id . '/test/area/9/test.pdf'))->out(false);
187
        $expected = "<p><strong>Watch out:</strong> $youtube <a href=\"$fileurl\" class=\"_blanktarget\">$fileurl</a></p>\n";
188
        $this->assertEquals($expected, $result->stringA);
189
        $this->assertEquals(FORMAT_HTML, $result->stringAformat);
190
    }
191
 
11 efrain 192
    public function test_properties_description(): void {
1 efrain 193
        $properties = core_testable_exporter::read_properties_definition();
194
        // Properties default description.
195
        $this->assertEquals('stringA', $properties['stringA']['description']);
196
        $this->assertEquals('stringAformat', $properties['stringAformat']['description']);
197
        // Properties custom description.
198
        $this->assertEquals('intB description', $properties['intB']['description']);
199
        // Other properties custom description.
200
        $this->assertEquals('otherstring description', $properties['otherstring']['description']);
201
        // Other properties default description.
202
        $this->assertEquals('otherstrings', $properties['otherstrings']['description']);
203
        // Assert nested elements are formatted correctly.
204
        $this->assertEquals('id', $properties['nestedarray']['type']['id']['description']);
205
    }
206
 
207
    /**
208
     * Tests for the handling of the default attribute of format properties in exporters.
209
     *
210
     * @covers \core\external\exporter::export
211
     * @return void
212
     */
213
    public function test_export_format_no_default(): void {
214
        global $PAGE;
215
        $output = $PAGE->get_renderer('core');
216
        $syscontext = \context_system::instance();
217
        $related = [
218
            'context' => $syscontext,
219
        ] + $this->validrelated;
220
 
221
        // Pass a data that does not have the format property for stringA.
222
        $data = [
223
            'stringA' => '__Go to:__ [Moodle.org](https://moodle.org)',
224
            'intB' => 1,
225
        ];
226
 
227
        // Note: For testing purposes only. Never extend exporter implementation. Only extend from the base exporter class!
228
        $testablexporterclass = new class($data, $related) extends core_testable_exporter {
229
            /**
230
             * Properties definition.
231
             */
232
            public static function define_properties(): array {
233
                $properties = parent::define_properties();
234
                $properties['stringAformat']['default'] = FORMAT_MARKDOWN;
235
                return $properties;
236
            }
237
        };
238
        // For a property format with default set, it should be able to export a data even if the property format is not passed.
239
        $result = $testablexporterclass->export($output);
240
        $expected = '<strong>Go to:</strong> <a href="https://moodle.org">Moodle.org</a>';
241
        $this->assertStringContainsString($expected, $result->stringA);
242
        $this->assertEquals(FORMAT_HTML, $result->stringAformat);
243
 
244
        // Passing data to an exporter with a required property format will throw an exception.
245
        $exporter = new core_testable_exporter($data, $related);
246
        $this->expectException(\coding_exception::class);
247
        $exporter->export($output);
248
    }
249
 
250
    /**
251
     * Test the processing of format properties.
252
     *
253
     * @covers \core\external\exporter::get_read_structure
254
     * @return void
255
     */
256
    public function test_format_properties_with_optional(): void {
257
        $testable = new class([]) extends \core\external\exporter {
258
            /**
259
             * Properties definition.
260
             *
261
             * @return array[]
262
             */
263
            public static function define_properties(): array {
264
                return [
265
                    'content' => [
266
                        'type' => PARAM_RAW,
267
                    ],
268
                    'contentformat' => [
269
                        'type' => PARAM_INT,
270
                        'optional' => true,
271
                    ],
272
                    'description' => [
273
                        'type' => PARAM_RAW,
274
                        'optional' => true,
275
                    ],
276
                    'descriptionformat' => [
277
                        'type' => PARAM_INT,
278
                        'default' => FORMAT_MARKDOWN,
279
                    ],
280
                    'summary' => [
281
                        'type' => PARAM_RAW,
282
                    ],
283
                    'summaryformat' => [
284
                        'type' => PARAM_INT,
285
                        'default' => null,
286
                    ],
287
                ];
288
            }
289
        };
290
 
291
        $definition = $testable::get_read_structure();
292
        // Check content and its format.
293
        $this->assertEquals(VALUE_REQUIRED, $definition->keys['content']->required);
294
        $this->assertEquals(VALUE_OPTIONAL, $definition->keys['contentformat']->required);
295
        $this->assertEquals(null, $definition->keys['contentformat']->default);
296
 
297
        // Check description and its format.
298
        $this->assertEquals(VALUE_OPTIONAL, $definition->keys['description']->required);
299
        $this->assertEquals(VALUE_DEFAULT, $definition->keys['descriptionformat']->required);
300
        $this->assertEquals(FORMAT_MARKDOWN, $definition->keys['descriptionformat']->default);
301
 
302
        // Check summary and its format.
303
        $this->assertEquals(VALUE_REQUIRED, $definition->keys['summary']->required);
304
        $this->assertEquals(null, $definition->keys['summary']->default);
305
        $this->assertEquals(VALUE_DEFAULT, $definition->keys['summaryformat']->required);
306
        $this->assertEquals(FORMAT_HTML, $definition->keys['summaryformat']->default);
307
    }
308
 
309
    /**
310
     * Test the processing of format properties when an invalid default format is passed.
311
     *
312
     * @covers \core\external\exporter::get_read_structure
313
     * @return void
314
     */
315
    public function test_optional_format_property_with_invalid_default(): void {
316
        $testable = new class([]) extends \core\external\exporter {
317
            /**
318
             * Properties definition.
319
             *
320
             * @return array[]
321
             */
322
            public static function define_properties(): array {
323
                return [
324
                    'description' => [
325
                        'type' => PARAM_RAW,
326
                    ],
327
                    'descriptionformat' => [
328
                        'type' => PARAM_INT,
329
                        'default' => 999,
330
                    ],
331
                ];
332
            }
333
        };
334
 
335
        $definition = $testable::get_read_structure();
336
        $this->assertDebuggingCalled(null, DEBUG_DEVELOPER);
337
 
338
        // Check description and its format.
339
        $this->assertEquals(VALUE_REQUIRED, $definition->keys['description']->required);
340
        $this->assertEquals(VALUE_DEFAULT, $definition->keys['descriptionformat']->required);
341
        $this->assertEquals(FORMAT_HTML, $definition->keys['descriptionformat']->default);
342
    }
343
}
344
 
345
/**
346
 * Example persistent class.
347
 *
348
 * @package    core
349
 * @copyright  2015 Frédéric Massart - FMCorz.net
350
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
351
 */
352
class core_testable_exporter extends \core\external\exporter {
353
 
354
    protected static function define_related() {
355
        // We cache the context so it does not need to be retrieved from the course.
356
        return array('simplestdClass' => 'stdClass', 'arrayofstdClass' => 'stdClass[]', 'context' => 'context?',
357
            'astring' => 'string', 'abool' => 'bool', 'aint' => 'int', 'ints' => 'int[]');
358
    }
359
 
360
    protected function get_other_values(\renderer_base $output) {
361
        return array(
362
            'otherstring' => '>Another <strong>string</strong>',
363
            'otherstrings' => array('String >a', 'String <strong>b</strong>')
364
        );
365
    }
366
 
367
    public static function define_properties() {
368
        return array(
369
            'stringA' => array(
370
                'type' => PARAM_RAW,
371
            ),
372
            'stringAformat' => array(
373
                'type' => PARAM_INT,
374
            ),
375
            'intB' => array(
376
                'type' => PARAM_INT,
377
                'description' => 'intB description',
378
            )
379
        );
380
    }
381
 
382
    public static function define_other_properties() {
383
        return array(
384
            'otherstring' => array(
385
                'type' => PARAM_TEXT,
386
                'description' => 'otherstring description',
387
            ),
388
            'otherstrings' => array(
389
                'type' => PARAM_TEXT,
390
                'multiple' => true
391
            ),
392
            'nestedarray' => array(
393
                'multiple' => true,
394
                'optional' => true,
395
                'type' => [
396
                    'id' => ['type' => PARAM_INT]
397
                ]
398
            )
399
        );
400
    }
401
 
402
    protected function get_format_parameters_for_stringA() {
403
        return [
404
            // For testing use the passed context if any.
405
            'context' => isset($this->related['context']) ? $this->related['context'] : \context_system::instance(),
406
            'component' => 'test',
407
            'filearea' => 'area',
408
            'itemid' => 9,
409
        ];
410
    }
411
 
412
    protected function get_format_parameters_for_otherstring() {
413
        return [
414
            'context' => \context_system::instance(),
415
            'options' => ['escape' => false]
416
        ];
417
    }
418
 
419
    protected function get_format_parameters_for_otherstrings() {
420
        return [
421
            'context' => \context_system::instance(),
422
        ];
423
    }
424
}