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 state webservice.
35
 *
36
 * @package    core_xapi
37
 * @covers     \core_xapi\external\get_state
38
 * @since      Moodle 4.2
39
 * @copyright  2023 Sara Arjona (sara@moodle.com)
40
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41
 */
1441 ariadna 42
final class get_state_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
     * Testing different component names on valid states.
55
     *
56
     * @dataProvider components_provider
57
     * @param string $component component name
58
     * @param string|null $expected expected results
59
     */
60
    public function test_component_names(string $component, ?string $expected): void {
61
        $this->resetAfterTest();
62
 
63
        // Scenario.
64
        $this->setAdminUser();
65
 
66
        // Add, at least, one xAPI state record to database.
67
        $data = test_helper::create_state([], true);
68
 
69
        // Perform test.
70
        $this->get_state_data($component, $data, $expected);
71
    }
72
 
73
    /**
74
     * Data provider for the test_component_names tests.
75
     *
76
     * @return  array
77
     */
1441 ariadna 78
    public static function components_provider(): array {
1 efrain 79
        return [
80
            'Inexistent component' => [
81
                'component' => 'inexistent_component',
82
                'expected' => null,
83
            ],
84
            'Compatible component' => [
85
                'component' => 'fake_component',
86
                'expected' => 'true',
87
            ],
88
            'Incompatible component' => [
89
                'component' => 'core_xapi',
90
                'expected' => null,
91
            ],
92
        ];
93
    }
94
 
95
    /**
96
     * Testing invalid agent for get_state.
97
     *
98
     */
99
    public function test_invalid_agent(): void {
100
        $this->resetAfterTest();
101
 
102
        // Scenario.
103
        $this->setAdminUser();
104
        $other = $this->getDataGenerator()->create_user();
105
 
106
        // Invalid agent (use different user, instead of the current one).
107
        $info = [
108
            'agent' => item_agent::create_from_user($other),
109
        ];
110
        $data = test_helper::create_state($info, true);
111
        $this->get_state_data('fake_component', $data, null);
112
    }
113
 
114
    /**
115
     * Testing valid/invalid state.
116
     *
117
     * @dataProvider states_provider
118
     * @param array $info The xAPI state information (to override default values).
119
     * @param string $expected Expected results.
120
     */
121
    public function test_get_state(array $info, string $expected): void {
122
        $this->resetAfterTest();
123
 
124
        // Scenario.
125
        $this->setAdminUser();
126
        $component = $info['component'] ?? 'fake_component';
127
        $params = [];
128
        if ($component === 'mod_h5pactivity') {
129
            // For the mod_h5pactivity component, the activity needs to be created too.
130
            $course = $this->getDataGenerator()->create_course();
131
            $user = $this->getDataGenerator()->create_and_enrol($course, 'student');
132
            $activity = $this->getDataGenerator()->create_module('h5pactivity', ['course' => $course]);
133
 
134
            $activitycontext = \context_module::instance($activity->cmid);
135
            $info['activity'] = item_activity::create_from_id($activitycontext->id);
136
            $params['activity'] = $info['activity'];
137
            $this->setUser($user);
138
        }
139
 
140
        // Add, at least, one xAPI state record to database (with the default values).
141
        test_helper::create_state($params, true);
142
 
143
        // Perform test.
144
        $data = test_helper::create_state($info);
145
        $component = $info['component'] ?? 'fake_component';
146
        $this->get_state_data($component, $data, $expected);
147
    }
148
 
149
    /**
150
     * Data provider for the test_get_state tests.
151
     *
152
     * @return array
153
     */
1441 ariadna 154
    public static function states_provider(): array {
1 efrain 155
        return [
156
            'Existing and valid state' => [
157
                'info' => [],
158
                'expected' => 'true',
159
            ],
160
            'No state (wrong activityid)' => [
161
                'info' => ['activity' => item_activity::create_from_id('1')],
162
                'expected' => 'false',
163
            ],
164
            'No state (wrong stateid)' => [
165
                'info' => ['stateid' => 'food'],
166
                'expected' => 'false',
167
            ],
168
            'No state (wrong component)' => [
169
                'info' => ['component' => 'mod_h5pactivity'],
170
                'expected' => 'false',
171
            ],
172
        ];
173
    }
174
 
175
    /**
176
     * Return a xAPI external webservice class to operate.
177
     *
178
     * The test needs to fake a component in order to test without
179
     * using a real one. This way if in the future any component
180
     * implement it's xAPI handler this test will continue working.
181
     *
182
     * @return get_state the external class
183
     */
184
    private function get_external_class(): get_state {
185
        $ws = new class extends get_state {
186
            /**
187
             * Method to override validate_component.
188
             *
189
             * @param string $component  The component name in frankenstyle.
190
             */
191
            protected static function validate_component(string $component): void {
192
                if ($component != 'fake_component') {
193
                    parent::validate_component($component);
194
                }
195
            }
196
        };
197
        return $ws;
198
    }
199
 
200
    /**
201
     * This function do all checks from a standard get_state request.
202
     *
203
     * The reason for this function is because states crafting (special in error
204
     * scenarios) is complicated to do via data providers because every test need a specific
205
     * testing conditions. For this reason alls tests creates a scenario and then uses this
206
     * function to check the results.
207
     *
208
     * @param string $component component name
209
     * @param state $data data to encode and send to get_state
210
     * @param string $expected expected results (if null an exception is expected)
211
     */
212
    private function get_state_data(string $component, state $data, ?string $expected): void {
213
        // When no result is expected, an exception will be incurred.
214
        if (is_null($expected)) {
215
            $this->expectException(xapi_exception::class);
216
        }
217
 
218
        $external = $this->get_external_class();
219
        $result = $external::execute(
220
            $component,
221
            iri::generate($data->get_activity_id(), 'activity'),
222
            json_encode($data->get_agent()),
223
            $data->get_state_id(),
224
            $data->get_registration()
225
        );
226
        $result = external_api::clean_returnvalue($external::execute_returns(), $result);
227
 
228
        // Check the returned state has the expected values.
229
        if ($expected === 'true') {
230
            $this->assertEquals(json_encode($data->jsonSerialize()), $result);
231
        } else {
232
            $this->assertNull($result);
233
        }
234
    }
235
}