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
// This program 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
// This program 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 does not match PSR. But Moodle likes it this way.
20
namespace mod_edusharing;
21
 
22
use core\moodle_database_for_testing;
23
use dml_exception;
24
use EduSharingApiClient\CurlHandler as EdusharingCurlHandler;
25
use EduSharingApiClient\CurlResult;
26
use EduSharingApiClient\EduSharingAuthHelper;
27
use EduSharingApiClient\EduSharingHelperBase;
28
use EduSharingApiClient\EduSharingNodeHelper;
29
use EduSharingApiClient\EduSharingNodeHelperConfig;
30
use EduSharingApiClient\NodeDeletedException;
31
use EduSharingApiClient\UrlHandling;
32
use EduSharingApiClient\Usage;
33
use EduSharingApiClient\UsageDeletedException;
34
use Exception;
35
use JsonException;
36
use stdClass;
37
use testUtils\FakeConfig;
38
 
39
/**
40
 * Class EdusharingServiceTest
41
 *
42
 * @author Marian Ziegler <ziegler@edu-sharing.net>
43
 * @package mod_edusharing
44
 * @covers \mod_edusharing\EduSharingService
45
 */
46
class edusharing_service_test extends \advanced_testcase {
47
 
48
    /**
49
     * Function test_if_get_ticket_returns_existing_ticket_if_cached_ticket_is_new
50
     *
51
     * @return void
52
     *
53
     * @throws Exception
54
     */
55
    public function test_if_get_ticket_returns_existing_ticket_if_cached_ticket_is_new(): void {
56
        $this->resetAfterTest();
57
        global $USER, $CFG;
58
        require_once($CFG->dirroot . '/mod/edusharing/tests/testUtils/FakeConfig.php');
59
        $fakeconfig = new FakeConfig();
60
        $fakeconfig->set_entries([
61
            'application_cc_gui_url'  => 'www.url.de',
62
            'application_private_key' => 'pkey123',
63
            'application_appid'       => 'appid123',
64
        ]);
65
        $utils                                   = new UtilityFunctions($fakeconfig);
66
        $service                                 = new EduSharingService(utils: $utils);
67
        $USER->edusharing_userticket             = 'testTicket';
68
        $USER->edusharing_userticketvalidationts = time();
69
        $this->assertEquals('testTicket', $service->get_ticket());
70
    }
71
 
72
    /**
73
     * Function test_if_get_ticket_returns_existing_ticket_if_auth_info_is_ok
74
     *
75
     * @return void
76
     *
77
     * @throws dml_exception
78
     * @throws Exception
79
     */
80
    public function test_if_get_ticket_returns_existing_ticket_if_auth_info_is_ok(): void {
81
        $this->resetAfterTest();
82
        global $USER;
83
        unset($USER->edusharing_userticketvalidationts);
84
        $USER->edusharing_userticket = 'testTicket';
85
        $basehelper                  = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
86
        $authmock                    = $this->getMockBuilder(EduSharingAuthHelper::class)
87
            ->setConstructorArgs([$basehelper])
88
            ->onlyMethods(['getTicketAuthenticationInfo'])
89
            ->getMock();
90
        $authmock->expects($this->once())
91
            ->method('getTicketAuthenticationInfo')
92
            ->will($this->returnValue(['statusCode' => 'OK']));
93
        $nodeconfig  = new EduSharingNodeHelperConfig(new UrlHandling(true));
94
        $nodehandler = new EduSharingNodeHelper($basehelper, $nodeconfig);
95
        $service     = new EduSharingService($authmock, $nodehandler);
96
        $this->assertEquals('testTicket', $service->get_ticket());
97
        $this->assertTrue(time() - $USER->edusharing_userticketvalidationts < 10);
98
    }
99
 
100
    /**
101
     * Function test_if_getT_ticket_returns_ticket_from_auth_helper_if_no_cached_ticket_exists
102
     *
103
     * @return void
104
     * @throws dml_exception
105
     */
106
    public function test_if_get_ticket_returns_ticket_from_auth_helper_if_no_cached_ticket_exists(): void {
107
        $this->resetAfterTest();
108
        global $USER;
109
        unset($USER->edusharing_userticket);
110
        $USER->firstname = 'Max';
111
        $USER->lastname  = 'Mustermann';
112
        $USER->email     = 'max@mustermann.de';
113
        $basehelper      = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
114
        $authmock        = $this->getMockBuilder(EduSharingAuthHelper::class)
115
            ->setConstructorArgs([$basehelper])
116
            ->onlyMethods(['getTicketForUser', 'getTicketAuthenticationInfo'])
117
            ->getMock();
118
        $authmock->expects($this->once())
119
            ->method('getTicketForUser')
120
            ->will($this->returnValue('ticketForUser'));
121
        $utilsmock = $this->getMockBuilder(UtilityFunctions::class)
122
            ->onlyMethods(['get_auth_key'])
123
            ->getMock();
124
        $utilsmock->expects($this->once())
125
            ->method('get_auth_key')
126
            ->will($this->returnValue('neverMind'));
127
        $nodeconfig  = new EduSharingNodeHelperConfig(new UrlHandling(true));
128
        $nodehandler = new EduSharingNodeHelper($basehelper, $nodeconfig);
129
        $service     = new EduSharingService($authmock, $nodehandler, $utilsmock);
130
        $this->assertEquals('ticketForUser', $service->get_ticket());
131
        $USER->edusharing_userticket = 'testTicket';
132
    }
133
 
134
    /**
135
     * Function test_if_get_ticket_returns_ticket_from_auth_helper_if_ticket_is_too_old_and_auth_info_call_fails
136
     *
137
     * @return void
138
     * @throws dml_exception
139
     */
140
    public function test_if_get_ticket_returns_ticket_from_auth_helper_if_ticket_is_too_old_and_auth_info_call_fails(): void {
141
        $this->resetAfterTest();
142
        global $USER;
143
        $USER->edusharing_userticket             = 'testTicket';
144
        $USER->edusharing_userticketvalidationts = 1689769393;
145
        $USER->firstname                         = 'Max';
146
        $USER->lastname                          = 'Mustermann';
147
        $USER->email                             = 'max@mustermann.de';
148
        $basehelper                              = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
149
        $authmock                                = $this->getMockBuilder(EduSharingAuthHelper::class)
150
            ->setConstructorArgs([$basehelper])
151
            ->onlyMethods(['getTicketForUser', 'getTicketAuthenticationInfo'])
152
            ->getMock();
153
        $authmock->expects($this->once())
154
            ->method('getTicketForUser')
155
            ->will($this->returnValue('ticketForUser'));
156
        $authmock->expects($this->once())
157
            ->method('getTicketAuthenticationInfo')
158
            ->will($this->returnValue(['statusCode' => 'NOT_OK']));
159
        $utilsmock = $this->getMockBuilder(UtilityFunctions::class)
160
            ->onlyMethods(['get_auth_key'])
161
            ->getMock();
162
        $utilsmock->expects($this->once())
163
            ->method('get_auth_key')
164
            ->will($this->returnValue('neverMind'));
165
        $nodeconfig  = new EduSharingNodeHelperConfig(new UrlHandling(true));
166
        $nodehandler = new EduSharingNodeHelper($basehelper, $nodeconfig);
167
        $service     = new EduSharingService($authmock, $nodehandler, $utilsmock);
168
        $this->assertEquals('ticketForUser', $service->get_ticket());
169
        $USER->edusharing_userticket = 'testTicket';
170
    }
171
 
172
    /**
173
     * Function test_if_create_usage_calls_node_helper_method_with_correct_params
174
     */
175
    public function test_if_create_usage_calls_node_helper_method_with_correct_params(): void {
176
        $usageobject              = new stdClass();
177
        $usageobject->containerId = 'containerIdTest';
178
        $usageobject->resourceId  = 'resourceIdTest';
179
        $usageobject->nodeId      = 'nodeIdTest';
180
        $usageobject->nodeVersion = 'nodeVersion';
181
        $basehelper               = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
182
        $nodeconfig               = new EduSharingNodeHelperConfig(new UrlHandling(true));
183
        $authhelper               = new EduSharingAuthHelper($basehelper);
184
        $nodehelpermock           = $this->getMockBuilder(EduSharingNodeHelper::class)
185
            ->onlyMethods(['createUsage'])
186
            ->setConstructorArgs([$basehelper, $nodeconfig])
187
            ->getMock();
188
        $nodehelpermock->expects($this->once())
189
            ->method('createUsage')
190
            ->with('ticketTest', 'containerIdTest', 'resourceIdTest', 'nodeIdTest', 'nodeVersion');
191
        $servicemock = $this->getMockBuilder(EduSharingService::class)
192
            ->onlyMethods(['get_ticket'])
193
            ->setConstructorArgs([$authhelper, $nodehelpermock])
194
            ->getMock();
195
        $servicemock->expects($this->once())
196
            ->method('get_ticket')
197
            ->will($this->returnValue('ticketTest'));
198
        $servicemock->create_usage($usageobject);
199
    }
200
 
201
    /**
202
     * Function test_if_get_usage_id_calls_node_helper_method_with_correct_params_and_returns_result
203
     *
204
     * @return void
205
     * @throws dml_exception
206
     */
207
    public function test_if_get_usage_id_calls_node_helper_method_with_correct_params_and_returns_result(): void {
208
        $usageobject              = new stdClass();
209
        $usageobject->containerId = 'containerIdTest';
210
        $usageobject->resourceId  = 'resourceIdTest';
211
        $usageobject->nodeId      = 'nodeIdTest';
212
        $usageobject->ticket      = 'ticketTest';
213
        $basehelper               = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
214
        $nodeconfig               = new EduSharingNodeHelperConfig(new UrlHandling(true));
215
        $authhelper               = new EduSharingAuthHelper($basehelper);
216
        $nodehelpermock           = $this->getMockBuilder(EduSharingNodeHelper::class)
217
            ->onlyMethods(['getUsageIdByParameters'])
218
            ->setConstructorArgs([$basehelper, $nodeconfig])
219
            ->getMock();
220
        $nodehelpermock->expects($this->once())
221
            ->method('getUsageIdByParameters')
222
            ->with('ticketTest', 'nodeIdTest', 'containerIdTest', 'resourceIdTest')
223
            ->will($this->returnValue('expectedId'));
224
        $service = new EduSharingService($authhelper, $nodehelpermock);
225
        $id      = $service->get_usage_id($usageobject);
226
        $this->assertEquals('expectedId', $id);
227
    }
228
 
229
    /**
230
     * Function test_if_get_usage_id_throws_exception_if_node_helper_method_returns_null
231
     *
232
     * @return void
233
     * @throws dml_exception
234
     */
235
    public function test_if_get_usage_id_throws_exception_if_node_helper_method_returns_null(): void {
236
        $usageobject              = new stdClass();
237
        $usageobject->containerId = 'containerIdTest';
238
        $usageobject->resourceId  = 'resourceIdTest';
239
        $usageobject->nodeId      = 'nodeIdTest';
240
        $usageobject->ticket      = 'ticketTest';
241
        $basehelper               = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
242
        $nodeconfig               = new EduSharingNodeHelperConfig(new UrlHandling(true));
243
        $authhelper               = new EduSharingAuthHelper($basehelper);
244
        $nodehelpermock           = $this->getMockBuilder(EduSharingNodeHelper::class)
245
            ->onlyMethods(['getUsageIdByParameters'])
246
            ->setConstructorArgs([$basehelper, $nodeconfig])
247
            ->getMock();
248
        $nodehelpermock->expects($this->once())
249
            ->method('getUsageIdByParameters')
250
            ->with('ticketTest', 'nodeIdTest', 'containerIdTest', 'resourceIdTest')
251
            ->will($this->returnValue(null));
252
        $service = new EduSharingService($authhelper, $nodehelpermock);
253
        $this->expectException(Exception::class);
254
        $this->expectExceptionMessage('No usage found');
255
        $service->get_usage_id($usageobject);
256
    }
257
 
258
    /**
259
     * Function test_if_delete_usage_calls_node_helper_method_with_proper_params
260
     *
261
     * @return void
262
     * @throws dml_exception
263
     */
264
    public function test_if_delete_usage_calls_node_helper_method_with_proper_params(): void {
265
        $usageobject          = new stdClass();
266
        $usageobject->nodeId  = 'nodeIdTest';
267
        $usageobject->usageId = 'usageIdTest';
268
        $basehelper           = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
269
        $nodeconfig           = new EduSharingNodeHelperConfig(new UrlHandling(true));
270
        $authhelper           = new EduSharingAuthHelper($basehelper);
271
        $nodehelpermock       = $this->getMockBuilder(EduSharingNodeHelper::class)
272
            ->onlyMethods(['deleteUsage'])
273
            ->setConstructorArgs([$basehelper, $nodeconfig])
274
            ->getMock();
275
        $nodehelpermock->expects($this->once())
276
            ->method('deleteUsage')
277
            ->with('nodeIdTest', 'usageIdTest');
278
        $service = new EduSharingService($authhelper, $nodehelpermock);
279
        $service->delete_usage($usageobject);
280
    }
281
 
282
    /**
283
     * Function test_if_get_node_calls_node_helper_method_with_proper_params
284
     *
285
     * @return void
286
     * @throws JsonException
287
     * @throws NodeDeletedException
288
     * @throws UsageDeletedException
289
     * @throws dml_exception
290
     */
291
    public function test_if_get_node_calls_node_helper_method_with_proper_params(): void {
292
        $usage          = new Usage('nodeIdTest', 'nodeVersionTest',
293
            'containerIdTest', 'resourceIdTest', 'usageIdTest');
294
        $basehelper     = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
295
        $nodeconfig     = new EduSharingNodeHelperConfig(new UrlHandling(true));
296
        $authhelper     = new EduSharingAuthHelper($basehelper);
297
        $nodehelpermock = $this->getMockBuilder(EduSharingNodeHelper::class)
298
            ->onlyMethods(['getNodeByUsage'])
299
            ->setConstructorArgs([$basehelper, $nodeconfig])
300
            ->getMock();
301
        $nodehelpermock->expects($this->once())
302
            ->method('getNodeByUsage')
303
            ->with($usage);
304
        $service = new EduSharingService($authhelper, $nodehelpermock);
305
        $service->get_node($usage);
306
    }
307
 
308
    /**
309
     * test_if_update_instance_calls_db_methods_and_calls_creation_method_with_proper_params
310
     *
311
     * @return void
312
     */
313
    public function test_if_update_instance_calls_db_methods_and_calls_creation_method_with_proper_params(): void {
314
        $this->resetAfterTest();
315
        require_once('lib/dml/tests/dml_test.php');
316
        $currenttime                   = time();
317
        $eduobject                     = new stdClass();
318
        $eduobject->object_url         = 'inputUrl';
319
        $eduobject->course             = 'containerIdTest';
320
        $eduobject->object_version     = 'nodeVersionTest';
321
        $eduobject->id                 = 'resourceIdTest';
322
        $eduobjectupdate               = clone($eduobject);
323
        $eduobjectupdate->usage_id     = '2';
324
        $eduobjectupdate->timecreated  = $currenttime;
325
        $eduobjectupdate->timeupdated  = $currenttime;
326
        $eduobjectupdate->options      = '';
327
        $eduobjectupdate->popup_window = '';
328
        $eduobjectupdate->tracking     = 0;
329
        $usagedata                     = new stdClass();
330
        $usagedata->containerId        = 'containerIdTest';
331
        $usagedata->resourceId         = 'resourceIdTest';
332
        $usagedata->nodeId             = 'outputUrl';
333
        $usagedata->nodeVersion        = 'nodeVersionTest';
334
        $usagedata->ticket             = 'ticketTest';
335
        $memento                       = new stdClass();
336
        $memento->id                   = 'someId';
337
        $basehelper                    = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
338
        $nodeconfig                    = new EduSharingNodeHelperConfig(new UrlHandling(true));
339
        $authhelper                    = new EduSharingAuthHelper($basehelper);
340
        $nodehelper                    = new EduSharingNodeHelper($basehelper, $nodeconfig);
341
        $utilsmock                     = $this->getMockBuilder(UtilityFunctions::class)
342
            ->onlyMethods(['get_object_id_from_url'])
343
            ->getMock();
344
        $utilsmock->expects($this->once())
345
            ->method('get_object_id_from_url')
346
            ->with('inputUrl')
347
            ->will($this->returnValue('outputUrl'));
348
        $servicemock = $this->getMockBuilder(EduSharingService::class)
349
            ->onlyMethods(['create_usage', 'get_ticket'])
350
            ->setConstructorArgs([$authhelper, $nodehelper, $utilsmock])
351
            ->getMock();
352
        $servicemock->expects($this->once())
353
            ->method('get_ticket')
354
            ->will($this->returnValue('ticketTest'));
355
        $servicemock->expects($this->once())
356
            ->method('create_usage')
357
            ->with($usagedata)
358
            ->will($this->returnValue(new Usage('whatever', 'whatever', 'whatever', 'whatever', '2')));
359
        $dbmock = $this->getMockBuilder(moodle_database_for_testing::class)
360
            ->onlyMethods(['get_record', 'update_record'])
361
            ->getMock();
362
        $dbmock->expects($this->once())
363
            ->method('get_record')
364
            ->with('edusharing', ['id' => 'resourceIdTest'], '*', MUST_EXIST)
365
            ->will($this->returnValue($memento));
366
        $dbmock->expects($this->once())
367
            ->method('update_record')
368
            ->with('edusharing', $eduobjectupdate);
369
        // phpcs:ignore -- GLOBALS is supposed to be all caps.
370
        $GLOBALS['DB'] = $dbmock;
371
        $this->assertEquals(true, $servicemock->update_instance($eduobject, $currenttime));
372
    }
373
 
374
    /**
375
     * Function test_if_update_instance_resets_data_and_returns_false_on_update_error
376
     *
377
     * @return void
378
     */
379
    public function test_if_update_instance_resets_data_and_returns_false_on_update_error(): void {
380
        $this->resetAfterTest();
381
        require_once('lib/dml/tests/dml_test.php');
382
        $currenttime                   = time();
383
        $eduobject                     = new stdClass();
384
        $eduobject->object_url         = 'inputUrl';
385
        $eduobject->course             = 'containerIdTest';
386
        $eduobject->object_version     = 'nodeVersionTest';
387
        $eduobject->id                 = 'resourceIdTest';
388
        $eduobjectupdate               = clone($eduobject);
389
        $eduobjectupdate->usage_id     = '2';
390
        $eduobjectupdate->timecreated  = $currenttime;
391
        $eduobjectupdate->timeupdated  = $currenttime;
392
        $eduobjectupdate->options      = '';
393
        $eduobjectupdate->popup_window = '';
394
        $eduobjectupdate->tracking     = 0;
395
        $usagedata                     = new stdClass();
396
        $usagedata->containerId        = 'containerIdTest';
397
        $usagedata->resourceId         = 'resourceIdTest';
398
        $usagedata->nodeId             = 'outputUrl';
399
        $usagedata->nodeVersion        = 'nodeVersionTest';
400
        $usagedata->ticket             = 'ticketTest';
401
        $memento                       = new stdClass();
402
        $memento->id                   = 'someId';
403
        $basehelper                    = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
404
        $nodeconfig                    = new EduSharingNodeHelperConfig(new UrlHandling(true));
405
        $authhelper                    = new EduSharingAuthHelper($basehelper);
406
        $nodehelper                    = new EduSharingNodeHelper($basehelper, $nodeconfig);
407
        $utilsmock                     = $this->getMockBuilder(UtilityFunctions::class)
408
            ->onlyMethods(['get_object_id_from_url'])
409
            ->getMock();
410
        $utilsmock->expects($this->once())
411
            ->method('get_object_id_from_url')
412
            ->with('inputUrl')
413
            ->will($this->returnValue('outputUrl'));
414
        $servicemock = $this->getMockBuilder(EduSharingService::class)
415
            ->onlyMethods(['create_usage', 'get_ticket'])
416
            ->setConstructorArgs([$authhelper, $nodehelper, $utilsmock])
417
            ->getMock();
418
        $servicemock->expects($this->once())
419
            ->method('get_ticket')
420
            ->will($this->returnValue('ticketTest'));
421
        $servicemock->expects($this->once())
422
            ->method('create_usage')
423
            ->with($usagedata)
424
            ->willThrowException(new Exception(''));
425
        $dbmock = $this->getMockBuilder(moodle_database_for_testing::class)
426
            ->onlyMethods(['get_record', 'update_record'])
427
            ->getMock();
428
        $dbmock->expects($this->once())
429
            ->method('get_record')
430
            ->with('edusharing', ['id' => 'resourceIdTest'], '*', MUST_EXIST)
431
            ->will($this->returnValue($memento));
432
        $dbmock->expects($this->once())
433
            ->method('update_record')
434
            ->with('edusharing', $memento);
435
        // phpcs:ignore -- GLOBALS is supposed to be all caps.
436
        $GLOBALS['DB'] = $dbmock;
437
        $this->assertEquals(false, $servicemock->update_instance($eduobject, $currenttime));
438
    }
439
 
440
    /**
441
     * Function test_if_add_instance_calls_db_functions_and_service_method_with_correct_parameters
442
     *
443
     * @return void
444
     */
445
    public function test_if_add_instance_calls_db_functions_and_service_method_with_correct_parameters(): void {
446
        $this->resetAfterTest();
447
        require_once('lib/dml/tests/dml_test.php');
448
        $currenttime                        = time();
449
        $eduobject                          = new stdClass();
450
        $eduobject->object_url              = 'inputUrl';
451
        $eduobject->course                  = 'containerIdTest';
452
        $eduobject->object_version          = '1.0';
453
        $eduobject->id                      = 'resourceIdTest';
454
        $processededuobject                 = clone($eduobject);
455
        $processededuobject->object_version = '1.0';
456
        $processededuobject->timecreated    = $currenttime;
457
        $processededuobject->timemodified   = $currenttime;
458
        $processededuobject->timeupdated    = $currenttime;
459
        $processededuobject->options        = '';
460
        $processededuobject->popup_window   = '';
461
        $processededuobject->tracking       = 0;
462
        $insertededuobject                  = clone($processededuobject);
463
        $insertededuobject->id              = 3;
464
        $insertededuobject->usage_id        = 4;
465
        $insertededuobject->object_version  = '1.0';
466
        $usagedata                          = new stdClass();
467
        $usagedata->containerId             = 'containerIdTest';
468
        $usagedata->resourceId              = 3;
469
        $usagedata->nodeId                  = 'outputUrl';
470
        $usagedata->nodeVersion             = '1.0';
471
        $dbmock                             = $this->getMockBuilder(moodle_database_for_testing::class)
472
            ->onlyMethods(['insert_record', 'update_record', 'delete_records'])
473
            ->getMock();
474
        $dbmock->expects($this->once())
475
            ->method('insert_record')
476
            ->with('edusharing', $processededuobject)
477
            ->will($this->returnValue(3));
478
        $dbmock->expects($this->once())
479
            ->method('update_record')
480
            ->with('edusharing', $insertededuobject);
481
        // phpcs:ignore -- GLOBALS is supposed to be all caps.
482
        $GLOBALS['DB'] = $dbmock;
483
        $utilsmock     = $this->getMockBuilder(UtilityFunctions::class)
484
            ->onlyMethods(['get_object_id_from_url'])
485
            ->getMock();
486
        $utilsmock->expects($this->once())
487
            ->method('get_object_id_from_url')
488
            ->with('inputUrl')
489
            ->will($this->returnValue('outputUrl'));
490
        $basehelper  = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
491
        $nodeconfig  = new EduSharingNodeHelperConfig(new UrlHandling(true));
492
        $authhelper  = new EduSharingAuthHelper($basehelper);
493
        $nodehelper  = new EduSharingNodeHelper($basehelper, $nodeconfig);
494
        $servicemock = $this->getMockBuilder(EduSharingService::class)
495
            ->onlyMethods(['create_usage', 'get_ticket'])
496
            ->setConstructorArgs([$authhelper, $nodehelper, $utilsmock])
497
            ->getMock();
498
        $servicemock->expects($this->once())
499
            ->method('create_usage')
500
            ->with($usagedata)
501
            ->will($this->returnValue(new Usage('whatever', 'nodeVersionTest', 'whatever', 'whatever', '4')));
502
        $this->assertEquals(3, $servicemock->add_instance($eduobject));
503
    }
504
 
505
    /**
506
     * Function test_if_add_instance_returns_false_and_resets_data_on_creation_failure
507
     *
508
     * @return void
509
     */
510
    public function test_if_add_instance_returns_false_and_resets_data_on_creation_failure(): void {
511
        $this->resetAfterTest();
512
        require_once('lib/dml/tests/dml_test.php');
513
        $currenttime                        = time();
514
        $eduobject                          = new stdClass();
515
        $eduobject->object_url              = 'inputUrl';
516
        $eduobject->course                  = 'containerIdTest';
517
        $eduobject->object_version          = '1';
518
        $eduobject->id                      = 'resourceIdTest';
519
        $processededuobject                 = clone($eduobject);
520
        $processededuobject->object_version = '1';
521
        $processededuobject->timecreated    = $currenttime;
522
        $processededuobject->timemodified   = $currenttime;
523
        $processededuobject->timeupdated    = $currenttime;
524
        $processededuobject->options        = '';
525
        $processededuobject->popup_window   = '';
526
        $processededuobject->tracking       = 0;
527
        $insertededuobject                  = clone($processededuobject);
528
        $insertededuobject->id              = 3;
529
        $insertededuobject->usage_id        = 4;
530
        $insertededuobject->object_version  = 'nodeVersionTest';
531
        $usagedata                          = new stdClass();
532
        $usagedata->containerId             = 'containerIdTest';
533
        $usagedata->resourceId              = 3;
534
        $usagedata->nodeId                  = 'outputUrl';
535
        $usagedata->nodeVersion             = '1';
536
        $dbmock                             = $this->getMockBuilder(moodle_database_for_testing::class)
537
            ->onlyMethods(['insert_record', 'update_record', 'delete_records'])
538
            ->getMock();
539
        $dbmock->expects($this->once())
540
            ->method('insert_record')
541
            ->with('edusharing', $processededuobject)
542
            ->will($this->returnValue(3));
543
        $dbmock->expects($this->never())
544
            ->method('update_record');
545
        $dbmock->expects($this->once())
546
            ->method('delete_records')
547
            ->with('edusharing', ['id' => 3]);
548
        // phpcs:ignore -- GLOBALS is supposed to be all caps.
549
        $GLOBALS['DB'] = $dbmock;
550
        $utilsmock     = $this->getMockBuilder(UtilityFunctions::class)
551
            ->onlyMethods(['get_object_id_from_url'])
552
            ->getMock();
553
        $utilsmock->expects($this->once())
554
            ->method('get_object_id_from_url')
555
            ->with('inputUrl')
556
            ->will($this->returnValue('outputUrl'));
557
        $basehelper  = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
558
        $nodeconfig  = new EduSharingNodeHelperConfig(new UrlHandling(true));
559
        $authhelper  = new EduSharingAuthHelper($basehelper);
560
        $nodehelper  = new EduSharingNodeHelper($basehelper, $nodeconfig);
561
        $servicemock = $this->getMockBuilder(EduSharingService::class)
562
            ->onlyMethods(['create_usage', 'get_ticket'])
563
            ->setConstructorArgs([$authhelper, $nodehelper, $utilsmock])
564
            ->getMock();
565
        $servicemock->expects($this->once())
566
            ->method('create_usage')
567
            ->with($usagedata)
568
            ->willThrowException(new Exception(''));
569
        $this->assertEquals(false, $servicemock->add_instance($eduobject));
570
    }
571
 
572
    /**
573
     * Function test_if_delete_usage_throwsexception_if_provided_object_has_no_usage_id
574
     *
575
     * @return void
576
     * @throws dml_exception
577
     */
578
    public function test_if_delete_usage_throwsexception_if_provided_object_has_no_usage_id(): void {
579
        $usageobject         = new stdClass();
580
        $usageobject->nodeId = 'nodeIdTest';
581
        $basehelper          = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
582
        $nodeconfig          = new EduSharingNodeHelperConfig(new UrlHandling(true));
583
        $authhelper          = new EduSharingAuthHelper($basehelper);
584
        $nodehelpermock      = $this->getMockBuilder(EduSharingNodeHelper::class)
585
            ->onlyMethods(['deleteUsage'])
586
            ->setConstructorArgs([$basehelper, $nodeconfig])
587
            ->getMock();
588
        $nodehelpermock->expects($this->never())
589
            ->method('deleteUsage');
590
        $service = new EduSharingService($authhelper, $nodehelpermock);
591
        $this->expectException(Exception::class);
592
        $this->expectExceptionMessage('No usage id provided, deletion cannot be performed');
593
        $service->delete_usage($usageobject);
594
    }
595
 
596
    /**
597
     * Function test_if_delete_instance_calls_database_with_proper_params
598
     *
599
     * @return void
600
     * @throws dml_exception
601
     */
602
    public function test_if_delete_instance_calls_database_with_proper_params(): void {
603
        $this->resetAfterTest();
604
        require_once('lib/dml/tests/dml_test.php');
605
        $dbrecord             = new stdClass();
606
        $dbrecord->id         = 'edusharingId123';
607
        $dbrecord->object_url = 'test.de';
608
        $dbrecord->course     = 'container123';
609
        $dbrecord->resourceId = 'resource123';
610
        $id                   = 1;
611
        $dbmock               = $this->getMockBuilder(moodle_database_for_testing::class)
612
            ->onlyMethods(['get_record', 'delete_records'])
613
            ->getMock();
614
        $dbmock->expects($this->once())
615
            ->method('get_record')
616
            ->with('edusharing', ['id' => $id], '*', MUST_EXIST)
617
            ->will($this->returnValue($dbrecord));
618
        $dbmock->expects($this->once())
619
            ->method('delete_records')
620
            ->with('edusharing', ['id' => 'edusharingId123']);
621
        // phpcs:ignore -- GLOBALS is supposed to be all caps.
622
        $GLOBALS['DB'] = $dbmock;
623
        $basehelper    = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
624
        $authhelper    = new EduSharingAuthHelper($basehelper);
625
        $nodeconfig    = new EduSharingNodeHelperConfig(new UrlHandling(true));
626
        $nodehelper    = new EduSharingNodeHelper($basehelper, $nodeconfig);
627
        $utilsmock     = $this->getMockBuilder(UtilityFunctions::class)
628
            ->onlyMethods(['get_object_id_from_url'])
629
            ->getMock();
630
        $utilsmock->expects($this->once())
631
            ->method('get_object_id_from_url')
632
            ->with('test.de')
633
            ->will($this->returnValue('myNodeId123'));
634
        $servicemock = $this->getMockBuilder(EduSharingService::class)
635
            ->setConstructorArgs([$authhelper, $nodehelper, $utilsmock])
636
            ->onlyMethods(['get_ticket', 'get_usage_id', 'delete_usage'])
637
            ->getMock();
638
        $servicemock->expects($this->once())
639
            ->method('get_ticket')
640
            ->will($this->returnValue('ticket123'));
641
        $servicemock->expects($this->once())
642
            ->method('get_usage_id')
643
            ->will($this->returnValue('usage123'));
644
        $servicemock->delete_instance((string)$id);
645
    }
646
 
647
    /**
648
     * Function test_if_import_metadata_calls_curl_with_the_correct_params
649
     *
650
     * @return void
651
     * @throws dml_exception
652
     */
653
    public function test_if_import_metadata_calls_curl_with_the_correct_params(): void {
654
        $this->resetAfterTest();
655
        global $_SERVER;
656
        $_SERVER['HTTP_USER_AGENT'] = 'testAgent';
657
        $url                        = 'http://test.de';
658
        $expectedoptions            = [
659
            CURLOPT_SSL_VERIFYPEER => false,
660
            CURLOPT_SSL_VERIFYHOST => false,
661
            CURLOPT_FOLLOWLOCATION => 1,
662
            CURLOPT_HEADER         => 0,
663
            CURLOPT_RETURNTRANSFER => 1,
664
            CURLOPT_USERAGENT      => 'testAgent',
665
        ];
666
        $curl                       = new CurlResult('testContent', 0, []);
667
        $basemock                   = $this->getMockBuilder(EduSharingHelperBase::class)
668
            ->setConstructorArgs(['www.url.de', 'pkey123', 'appid123'])
669
            ->onlyMethods(['handleCurlRequest'])
670
            ->getMock();
671
        $basemock->expects($this->once())
672
            ->method('handleCurlRequest')
673
            ->with($url, $expectedoptions)
674
            ->will($this->returnValue($curl));
675
        $nodeconfig = new EduSharingNodeHelperConfig(new UrlHandling(true));
676
        $authhelper = new EduSharingAuthHelper($basemock);
677
        $nodehelper = new EduSharingNodeHelper($basemock, $nodeconfig);
678
        $service    = new EduSharingService($authhelper, $nodehelper);
679
        $this->assertEquals($curl, $service->import_metadata($url));
680
    }
681
 
682
    /**
683
     * Function test_if_validate_session_calls_curl_with_the_correct_params
684
     *
685
     * @return void
686
     * @throws dml_exception
687
     */
688
    public function test_if_validate_session_calls_curl_with_the_correct_params(): void {
689
        $url             = 'http://test.de';
690
        $headers         = [
691
            'Content-Type: application/json',
692
            'Accept: application/json',
693
            'Authorization: Basic ' . base64_encode('testAuth'),
694
        ];
695
        $expectedoptions = [
696
            CURLOPT_RETURNTRANSFER => 1,
697
            CURLOPT_HTTPHEADER     => $headers,
698
        ];
699
        $curl            = new CurlResult('testContent', 0, []);
700
        $basemock        = $this->getMockBuilder(EduSharingHelperBase::class)
701
            ->setConstructorArgs(['www.url.de', 'pkey123', 'appid123'])
702
            ->onlyMethods(['handleCurlRequest'])
703
            ->getMock();
704
        $basemock->expects($this->once())
705
            ->method('handleCurlRequest')
706
            ->with($url . '/rest/authentication/v1/validateSession', $expectedoptions)
707
            ->will($this->returnValue($curl));
708
        $nodeconfig = new EduSharingNodeHelperConfig(new UrlHandling(true));
709
        $authhelper = new EduSharingAuthHelper($basemock);
710
        $nodehelper = new EduSharingNodeHelper($basemock, $nodeconfig);
711
        $service    = new EduSharingService($authhelper, $nodehelper);
712
        $this->assertEquals($curl, $service->validate_session($url, 'testAuth'));
713
    }
714
 
715
    /**
716
     * Function test_if_register_plugin_calls_curl_with_the_correct_options
717
     *
718
     * @return void
719
     * @throws dml_exception
720
     */
721
    public function test_if_register_plugin_calls_curl_with_the_correct_options(): void {
722
        $url         = 'http://test.de';
723
        $delimiter   = 'delimiterTest';
724
        $body        = 'bodyTest';
725
        $auth        = 'authTest';
726
        $headers     = [
727
            'Content-Type: multipart/form-data; boundary=' . $delimiter,
728
            'Content-Length: ' . strlen($body),
729
            'Accept: application/json',
730
            'Authorization: Basic ' . base64_encode($auth),
731
        ];
732
        $curloptions = [
733
            CURLOPT_RETURNTRANSFER => 1,
734
            CURLOPT_HTTPHEADER     => $headers,
735
            CURLOPT_POSTFIELDS     => $body,
736
        ];
737
        $curl        = new CurlResult('testContent', 0, []);
738
        $basehelper  = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
739
        $curlmock    = $this->getMockBuilder(MoodleCurlHandler::class)
740
            ->onlyMethods(['handleCurlRequest', 'setMethod'])
741
            ->getMock();
742
        $curlmock->expects($this->once())
743
            ->method('setMethod')
744
            ->with(EdusharingCurlHandler::METHOD_PUT);
745
        $curlmock->expects($this->once())
746
            ->method('handleCurlRequest')
747
            ->with($url . '/rest/admin/v1/applications/xml', $curloptions)
748
            ->will($this->returnValue($curl));
749
        $basehelper->registerCurlHandler($curlmock);
750
        $nodeconfig = new EduSharingNodeHelperConfig(new UrlHandling(true));
751
        $authhelper = new EduSharingAuthHelper($basehelper);
752
        $nodehelper = new EduSharingNodeHelper($basehelper, $nodeconfig);
753
        $service    = new EduSharingService($authhelper, $nodehelper);
754
        $this->assertEquals($curl, $service->register_plugin($url, $delimiter, $body, $auth));
755
    }
756
 
757
    /**
758
     * Function test_if_sign_calls_base_helper_method_with_correct_params_and_returns_its_returned_value
759
     *
760
     * @return void
761
     * @throws dml_exception
762
     */
763
    public function test_if_sign_calls_base_helper_method_with_correct_params_and_returns_its_returned_value(): void {
764
        $basemock = $this->getMockBuilder(EduSharingHelperBase::class)
765
            ->setConstructorArgs(['www.url.de', 'pkey123', 'appid123'])
766
            ->onlyMethods(['sign'])
767
            ->getMock();
768
        $basemock->expects($this->once())
769
            ->method('sign')
770
            ->with('testInput')
771
            ->will($this->returnValue('testOutput'));
772
        $nodeconfig = new EduSharingNodeHelperConfig(new UrlHandling(true));
773
        $authhelper = new EduSharingAuthHelper($basemock);
774
        $nodehelper = new EduSharingNodeHelper($basemock, $nodeconfig);
775
        $service    = new EduSharingService($authhelper, $nodehelper);
776
        $this->assertEquals('testOutput', $service->sign('testInput'));
777
    }
778
 
779
    /**
780
     * Function test_get_render_html_calls_curl_handler_with_correct_params_and_returns_content_on_success
781
     *
782
     * @return void
783
     * @throws dml_exception
784
     */
785
    public function test_get_render_html_calls_curl_handler_with_correct_params_and_returns_content_on_success(): void {
786
        $this->resetAfterTest();
787
        global $_SERVER;
788
        $_SERVER['HTTP_USER_AGENT'] = 'testAgent';
789
        $basehelper                 = new EduSharingHelperBase(
790
            'www.url.de',
791
            'pkey123',
792
            'appid123');
793
        $curloptions                = [
794
            CURLOPT_SSL_VERIFYPEER => false,
795
            CURLOPT_SSL_VERIFYHOST => false,
796
            CURLOPT_FOLLOWLOCATION => 1,
797
            CURLOPT_HEADER         => 0,
798
            CURLOPT_RETURNTRANSFER => 1,
799
            CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],
800
        ];
801
        $curlmock                   = $this->getMockBuilder(MoodleCurlHandler::class)
802
            ->onlyMethods(['handleCurlRequest'])
803
            ->getMock();
804
        $curlmock->expects($this->once())
805
            ->method('handleCurlRequest')
806
            ->with('www.testUrl.de', $curloptions)
807
            ->will($this->returnValue(new CurlResult('expectedContent', 0, [])));
808
        $basehelper->registerCurlHandler($curlmock);
809
        $nodeconfig = new EduSharingNodeHelperConfig(new UrlHandling(true));
810
        $authhelper = new EduSharingAuthHelper($basehelper);
811
        $nodehelper = new EduSharingNodeHelper($basehelper, $nodeconfig);
812
        $service    = new EduSharingService($authhelper, $nodehelper);
813
        $this->assertEquals('expectedContent', $service->get_render_html('www.testUrl.de'));
814
    }
815
 
816
    /**
817
     * Function test_get_render_html_returns_error_message_if_curl_result_has_error
818
     *
819
     * @return void
820
     * @throws dml_exception
821
     */
822
    public function test_get_render_html_returns_error_message_if_curl_result_has_error(): void {
823
        $this->resetAfterTest();
824
        global $_SERVER;
825
        $_SERVER['HTTP_USER_AGENT'] = 'testAgent';
826
        $basehelper                 = new EduSharingHelperBase('www.url.de', 'pkey123', 'appid123');
827
        $curloptions                = [
828
            CURLOPT_SSL_VERIFYPEER => false,
829
            CURLOPT_SSL_VERIFYHOST => false,
830
            CURLOPT_FOLLOWLOCATION => 1,
831
            CURLOPT_HEADER         => 0,
832
            CURLOPT_RETURNTRANSFER => 1,
833
            CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],
834
        ];
835
        $curlmock                   = $this->getMockBuilder(MoodleCurlHandler::class)
836
            ->onlyMethods(['handleCurlRequest'])
837
            ->getMock();
838
        $curlmock->expects($this->once())
839
            ->method('handleCurlRequest')
840
            ->with('www.testUrl.de', $curloptions)
841
            ->will($this->returnValue(new CurlResult('expectedContent', 1, ['message' => 'error'])));
842
        $basehelper->registerCurlHandler($curlmock);
843
        $nodeconfig = new EduSharingNodeHelperConfig(new UrlHandling(true));
844
        $authhelper = new EduSharingAuthHelper($basehelper);
845
        $nodehelper = new EduSharingNodeHelper($basehelper, $nodeconfig);
846
        $service    = new EduSharingService($authhelper, $nodehelper);
847
        $this->assertEquals('Unexpected Error', $service->get_render_html('www.testUrl.de'));
848
    }
849
}