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 delete state webservice.
35
 *
36
 * @package    core_xapi
37
 * @covers     \core_xapi\external\delete_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 delete_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
 
62
        $this->resetAfterTest();
63
 
64
        // Scenario.
65
        $this->setAdminUser();
66
 
67
        // Perform test.
68
        $data = test_helper::create_state([], true);
69
        $this->delete_state_data($component, $data, $expected);
70
    }
71
 
72
    /**
73
     * Data provider for the test_component_names tests.
74
     *
75
     * @return  array
76
     */
1441 ariadna 77
    public static function components_provider(): array {
1 efrain 78
        return [
79
            'Inexistent component' => [
80
                'component' => 'inexistent_component',
81
                'expected' => null,
82
            ],
83
            'Compatible component' => [
84
                'component' => 'fake_component',
85
                'expected' => 'true',
86
            ],
87
            'Incompatible component' => [
88
                'component' => 'core_xapi',
89
                'expected' => null,
90
            ],
91
        ];
92
    }
93
 
94
    /**
95
     * Testing invalid agent.
96
     *
97
     */
98
    public function test_invalid_agent(): void {
99
        $this->resetAfterTest();
100
 
101
        // Scenario.
102
        $this->setAdminUser();
103
        $other = $this->getDataGenerator()->create_user();
104
 
105
        // Invalid agent (use different user, instead of the current one).
106
        $info = [
107
            'agent' => item_agent::create_from_user($other),
108
        ];
109
        $data = test_helper::create_state($info, true);
110
        $this->delete_state_data('fake_component', $data, null);
111
    }
112
 
113
    /**
114
     * Testing valid/invalid state.
115
     *
116
     * @dataProvider states_provider
117
     * @param array $info array of overriden state data.
118
     * @param string|null $expected Expected results.
119
     * @return void
120
     */
121
    public function test_delete_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
 
146
        $this->delete_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 delete_state the external class
183
     */
184
    private function get_external_class(): delete_state {
185
        $ws = new class extends delete_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 delete_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 delete_state
210
     * @param string $expected expected results (if null an exception is expected)
211
     */
212
    private function delete_state_data(string $component, state $data, ?string $expected): void {
213
        global $DB;
214
 
215
        // Get current states in database.
216
        $currentstates = $DB->count_records('xapi_states');
217
 
218
        // When no result is expected, an exception will be incurred.
219
        if (is_null($expected)) {
220
            $this->expectException(xapi_exception::class);
221
        }
222
 
223
        $external = $this->get_external_class();
224
        $result = $external::execute(
225
            $component,
226
            iri::generate($data->get_activity_id(), 'activity'),
227
            json_encode($data->get_agent()),
228
            $data->get_state_id(),
229
            $data->get_registration()
230
        );
231
        $result = external_api::clean_returnvalue($external::execute_returns(), $result);
232
 
233
        // Check the state has been removed.
234
        $records = $DB->get_records('xapi_states');
235
        $this->assertTrue($result);
236
        if ($expected === 'true') {
237
            $this->assertCount($currentstates - 1, $records);
238
        } else if ($expected === 'false') {
239
            $this->assertCount($currentstates, $records);
240
        }
241
    }
242
}