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 core_xapi\external;
18
 
19
use core_xapi\xapi_exception;
20
use core_xapi\local\statement\item_agent;
21
use externallib_advanced_testcase;
22
use core_external\external_api;
23
use core_xapi\iri;
24
use core_xapi\local\state;
25
use core_xapi\local\statement\item_activity;
26
use core_xapi\test_helper;
27
 
28
defined('MOODLE_INTERNAL') || die();
29
 
30
global $CFG;
31
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
32
 
33
/**
34
 * Unit tests for xAPI get states webservice.
35
 *
36
 * @package    core_xapi
37
 * @covers     \core_xapi\external\get_states
38
 * @since      Moodle 4.2
39
 * @copyright  2023 Ferran Recio <ferran@moodle.com>
40
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41
 */
1441 ariadna 42
final class get_states_test extends externallib_advanced_testcase {
1 efrain 43
 
44
    /**
45
     * Setup to ensure that fixtures are loaded.
46
     */
47
    public static function setUpBeforeClass(): void {
48
        global $CFG;
49
        require_once($CFG->dirroot . '/lib/xapi/tests/helper.php');
1441 ariadna 50
        parent::setUpBeforeClass();
1 efrain 51
    }
52
 
53
    /**
54
     * Execute the get_states service from a generate state.
55
     *
56
     * @param string $component component name
57
     * @param state $data the original state to extract the params
58
     * @param string|null $since the formated timestamp or ISO 8601 date
59
     * @param array $override overridden params
60
     * @return string[] array of state ids
61
     */
62
    private function execute_service(
63
        string $component,
64
        state $data,
65
        ?string $since = null,
66
        array $override = []
67
    ): array {
68
        // Apply overrides.
69
        $activityiri = $override['activityiri'] ?? iri::generate($data->get_activity_id(), 'activity');
70
        $registration = $override['registration'] ?? $data->get_registration();
71
        $agent = $override['agent'] ?? $data->get_agent();
72
        if (!empty($override['user'])) {
73
            $agent = item_agent::create_from_user($override['user']);
74
        }
75
 
76
        $external = $this->get_external_class();
77
        $result = $external::execute(
78
            $component,
79
            $activityiri,
80
            json_encode($agent),
81
            $registration,
82
            $since
83
        );
84
        $result = external_api::clean_returnvalue($external::execute_returns(), $result);
85
 
86
        // Sorting result to make them comparable.
87
        sort($result);
88
        return $result;
89
    }
90
 
91
    /**
92
     * Return a xAPI external webservice class to operate.
93
     *
94
     * The test needs to fake a component in order to test without
95
     * using a real one. This way if in the future any component
96
     * implement it's xAPI handler this test will continue working.
97
     *
98
     * @return get_states the external class
99
     */
100
    private function get_external_class(): get_states {
101
        $ws = new class extends get_states {
102
            /**
103
             * Method to override validate_component.
104
             *
105
             * @param string $component  The component name in frankenstyle.
106
             */
107
            protected static function validate_component(string $component): void {
108
                if ($component != 'fake_component') {
109
                    parent::validate_component($component);
110
                }
111
            }
112
        };
113
        return $ws;
114
    }
115
 
116
    /**
117
     * Testing different component names on valid states.
118
     *
119
     * @dataProvider components_provider
120
     * @param string $component component name
121
     * @param string|null $exception expect exception
122
     */
123
    public function test_component_names(string $component, ?bool $exception): void {
124
        $this->resetAfterTest();
125
 
126
        // Scenario.
127
        $this->setAdminUser();
128
 
129
        // Add, at least, one xAPI state record to database.
130
        $data = test_helper::create_state(
131
            ['activity' => item_activity::create_from_id('1'), 'stateid' => 'aa'],
132
            true
133
        );
134
 
135
        // If no result is expected we will just incur in exception.
136
        if ($exception) {
137
            $this->expectException(xapi_exception::class);
138
        }
139
 
140
        $result = $this->execute_service($component, $data);
141
        $this->assertEquals(['aa'], $result);
142
    }
143
 
144
    /**
145
     * Data provider for the test_component_names tests.
146
     *
147
     * @return  array
148
     */
1441 ariadna 149
    public static function components_provider(): array {
1 efrain 150
        return [
151
            'Inexistent component' => [
152
                'component' => 'inexistent_component',
153
                'exception' => true,
154
            ],
155
            'Compatible component' => [
156
                'component' => 'fake_component',
157
                'exception' => false,
158
            ],
159
            'Incompatible component' => [
160
                'component' => 'core_xapi',
161
                'exception' => true,
162
            ],
163
        ];
164
    }
165
 
166
    /**
167
     * Testing different since date formats.
168
     *
169
     * @dataProvider since_formats_provider
170
     * @param string|null $since the formatted timestamps
171
     * @param string[]|null $expected expected results
172
     * @param bool $exception expect exception
173
     */
174
    public function test_since_formats(?string $since, ?array $expected, bool $exception = false): void {
175
        $this->resetAfterTest();
176
        $this->setAdminUser();
177
 
178
        $states = $this->generate_states();
179
 
180
        if ($exception) {
181
            $this->expectException(xapi_exception::class);
182
        }
183
 
184
        $result = $this->execute_service('fake_component', $states['aa'], $since);
185
        $this->assertEquals($expected, $result);
186
    }
187
 
188
    /**
189
     * Data provider for the test_since_formats tests.
190
     *
191
     * @return  array
192
     */
1441 ariadna 193
    public static function since_formats_provider(): array {
1 efrain 194
        return [
195
            'Null date' => [
196
                'since' => null,
197
                'expected' => ['aa', 'bb', 'cc', 'dd'],
198
                'exception' => false,
199
            ],
200
            'Numeric timestamp' => [
201
                'since' => '1651100399',
202
                'expected' => ['aa', 'bb'],
203
                'exception' => false,
204
            ],
205
            'ISO 8601 format 1' => [
206
                'since' => '2022-04-28T06:59',
207
                'expected' => ['aa', 'bb'],
208
                'exception' => false,
209
            ],
210
            'ISO 8601 format 2' => [
211
                'since' => '2022-04-28T06:59:59',
212
                'expected' => ['aa', 'bb'],
213
                'exception' => false,
214
            ],
215
            'Wrong format' => [
216
                'since' => 'Spanish omelette without onion',
217
                'expected' => null,
218
                'exception' => true,
219
            ],
220
        ];
221
    }
222
 
223
    /**
224
     * Testing different activity IRI values.
225
     *
226
     * @dataProvider activity_iri_provider
227
     * @param string|null $activityiri
228
     * @param string[]|null $expected expected results
229
     */
230
    public function test_activity_iri(?string $activityiri, ?array $expected): void {
231
        $this->resetAfterTest();
232
        $this->setAdminUser();
233
 
234
        $states = $this->generate_states();
235
 
236
        $override = ['activityiri' => $activityiri];
237
        $result = $this->execute_service('fake_component', $states['aa'], null, $override);
238
        $this->assertEquals($expected, $result);
239
    }
240
 
241
    /**
242
     * Data provider for the test_activity_iri tests.
243
     *
244
     * @return  array
245
     */
1441 ariadna 246
    public static function activity_iri_provider(): array {
1 efrain 247
        return [
248
            'Activity with several states' => [
249
                'activityiri' => iri::generate('1', 'activity'),
250
                'expected' => ['aa', 'bb', 'cc', 'dd'],
251
            ],
252
            'Activity with one state' => [
253
                'activityiri' => iri::generate('2', 'activity'),
254
                'expected' => ['ee'],
255
            ],
256
            'Inexistent activity' => [
257
                'activityiri' => iri::generate('3', 'activity'),
258
                'expected' => [],
259
            ],
260
        ];
261
    }
262
 
263
    /**
264
     * Testing different agent values.
265
     *
266
     * @dataProvider agent_values_provider
267
     * @param string|null $agentreference the used agent reference
268
     * @param string[]|null $expected expected results
269
     * @param bool $exception expect exception
270
     */
271
    public function test_agent_values(?string $agentreference, ?array $expected, bool $exception = false): void {
272
        $this->resetAfterTest();
273
        $this->setAdminUser();
274
 
275
        $states = $this->generate_states();
276
 
277
        if ($exception) {
278
            $this->expectException(xapi_exception::class);
279
        }
280
 
281
        $userreferences = [
282
            'current' => $states['aa']->get_user(),
283
            'other' => $this->getDataGenerator()->create_user(),
284
        ];
285
 
286
        $override = [
287
            'user' => $userreferences[$agentreference],
288
        ];
289
        $result = $this->execute_service('fake_component', $states['aa'], null, $override);
290
        $this->assertEquals($expected, $result);
291
    }
292
 
293
    /**
294
     * Data provider for the test_agent_values tests.
295
     *
296
     * @return  array
297
     */
1441 ariadna 298
    public static function agent_values_provider(): array {
1 efrain 299
        return [
300
            'Current user' => [
301
                'agentreference' => 'current',
302
                'expected' => ['aa', 'bb', 'cc', 'dd'],
303
                'exception' => false,
304
            ],
305
            'Other user' => [
306
                'agentreference' => 'other',
307
                'expected' => null,
308
                'exception' => true,
309
            ],
310
        ];
311
    }
312
 
313
    /**
314
     * Testing different registration values.
315
     *
316
     * @dataProvider registration_values_provider
317
     * @param string|null $registration
318
     * @param string[]|null $expected expected results
319
     */
320
    public function test_registration_values(?string $registration, ?array $expected): void {
321
        $this->resetAfterTest();
322
        $this->setAdminUser();
323
 
324
        $states = $this->generate_states();
325
 
326
        $override = ['registration' => $registration];
327
        $result = $this->execute_service('fake_component', $states['aa'], null, $override);
328
        $this->assertEquals($expected, $result);
329
    }
330
 
331
    /**
332
     * Data provider for the test_registration_values tests.
333
     *
334
     * @return  array
335
     */
1441 ariadna 336
    public static function registration_values_provider(): array {
1 efrain 337
        return [
338
            'Null registration' => [
339
                'registration' => null,
340
                'expected' => ['aa', 'bb', 'cc', 'dd'],
341
            ],
342
            'Registration with one state id' => [
343
                'registration' => 'reg2',
344
                'expected' => ['cc'],
345
            ],
346
            'Registration with two state ids' => [
347
                'registration' => 'reg',
348
                'expected' => ['bb', 'dd'],
349
            ],
350
            'Registration with no state ids' => [
351
                'registration' => 'invented',
352
                'expected' => [],
353
            ],
354
        ];
355
    }
356
 
357
    /**
358
     * Generate the state for the testing scenarios.
359
     *
360
     * Generate a variaty of states from several components, registrations and state ids.
361
     * Some of the states are registered as they are done in 27-04-2022 07:00:00 while others
362
     * are updated in 28-04-2022 07:00:00.
363
     *
364
     * @return state[]
365
     */
366
    private function generate_states(): array {
367
        global $DB;
368
 
369
        $testdate = \DateTime::createFromFormat('d-m-Y H:i:s', '28-04-2022 07:00:00');
370
        // Unix timestamp: 1651100400.
371
        $currenttime = $testdate->getTimestamp();
372
 
373
        $result = [];
374
 
375
        // Add a few xAPI state records to database.
376
        $states = [
377
            ['activity' => item_activity::create_from_id('1'), 'stateid' => 'aa'],
378
            ['activity' => item_activity::create_from_id('1'), 'registration' => 'reg', 'stateid' => 'bb'],
379
            ['activity' => item_activity::create_from_id('1'), 'registration' => 'reg2', 'stateid' => 'cc'],
380
            ['activity' => item_activity::create_from_id('1'), 'registration' => 'reg', 'stateid' => 'dd'],
381
            ['activity' => item_activity::create_from_id('2'), 'stateid' => 'ee'],
382
            ['activity' => item_activity::create_from_id('3'), 'component' => 'other', 'stateid' => 'gg'],
383
            ['activity' => item_activity::create_from_id('3'), 'component' => 'other', 'registration' => 'reg', 'stateid' => 'ff'],
384
        ];
385
        foreach ($states as $state) {
386
            $result[$state['stateid']] = test_helper::create_state($state, true);
387
        }
388
 
389
        $timepast = $currenttime - DAYSECS;
390
        $DB->set_field('xapi_states', 'timecreated', $timepast);
391
        $DB->set_field('xapi_states', 'timemodified', $timepast);
392
        $DB->set_field('xapi_states', 'timemodified', $currenttime, ['stateid' => 'aa']);
393
        $DB->set_field('xapi_states', 'timemodified', $currenttime, ['stateid' => 'bb']);
394
        $DB->set_field('xapi_states', 'timemodified', $currenttime, ['stateid' => 'ee']);
395
 
396
        return $result;
397
    }
398
}