Proyectos de Subversion Moodle

Rev

Rev 11 | | 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
 
1441 ariadna 17
use core_badges\helper;
18
use core_badges\tests\badges_testcase;
19
use core\task\manager;
20
 
1 efrain 21
/**
22
 * Unit tests for badges
23
 *
1441 ariadna 24
 * @package    core_badges
1 efrain 25
 * @copyright  2013 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
26
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27
 * @author     Yuliya Bozhko <yuliya.bozhko@totaralms.com>
28
 */
1441 ariadna 29
final class badgeslib_test extends badges_testcase {
1 efrain 30
    protected $badgeid;
31
    protected $course;
32
    protected $user;
33
    protected $module;
34
    protected $coursebadge;
35
    protected $assertion;
36
 
37
    /** @var $assertion2 to define json format for Open badge version 2 */
38
    protected $assertion2;
39
 
11 efrain 40
    public function test_create_badge(): void {
1 efrain 41
        $badge = new badge($this->badgeid);
42
 
43
        $this->assertInstanceOf('badge', $badge);
44
        $this->assertEquals($this->badgeid, $badge->id);
45
    }
46
 
11 efrain 47
    public function test_clone_badge(): void {
1 efrain 48
        $badge = new badge($this->badgeid);
49
        $newid = $badge->make_clone();
50
        $clonedbadge = new badge($newid);
51
 
52
        $this->assertEquals($badge->description, $clonedbadge->description);
53
        $this->assertEquals($badge->issuercontact, $clonedbadge->issuercontact);
54
        $this->assertEquals($badge->issuername, $clonedbadge->issuername);
55
        $this->assertEquals($badge->issuercontact, $clonedbadge->issuercontact);
56
        $this->assertEquals($badge->issuerurl, $clonedbadge->issuerurl);
57
        $this->assertEquals($badge->expiredate, $clonedbadge->expiredate);
58
        $this->assertEquals($badge->expireperiod, $clonedbadge->expireperiod);
59
        $this->assertEquals($badge->type, $clonedbadge->type);
60
        $this->assertEquals($badge->courseid, $clonedbadge->courseid);
61
        $this->assertEquals($badge->message, $clonedbadge->message);
62
        $this->assertEquals($badge->messagesubject, $clonedbadge->messagesubject);
63
        $this->assertEquals($badge->attachment, $clonedbadge->attachment);
64
        $this->assertEquals($badge->notification, $clonedbadge->notification);
65
        $this->assertEquals($badge->version, $clonedbadge->version);
66
        $this->assertEquals($badge->language, $clonedbadge->language);
67
        $this->assertEquals($badge->imagecaption, $clonedbadge->imagecaption);
68
    }
69
 
11 efrain 70
    public function test_badge_status(): void {
1 efrain 71
        $badge = new badge($this->badgeid);
72
        $old_status = $badge->status;
73
        $badge->set_status(BADGE_STATUS_ACTIVE);
74
        $this->assertNotEquals($old_status, $badge->status);
75
        $this->assertEquals(BADGE_STATUS_ACTIVE, $badge->status);
76
    }
77
 
11 efrain 78
    public function test_delete_badge(): void {
1 efrain 79
        $badge = new badge($this->badgeid);
80
        $badge->delete();
81
        // We don't actually delete badges. We archive them.
82
        $this->assertEquals(BADGE_STATUS_ARCHIVED, $badge->status);
83
    }
84
 
85
    /**
86
     * Really delete the badge.
87
     */
11 efrain 88
    public function test_delete_badge_for_real(): void {
1 efrain 89
        global $DB;
90
 
91
        $badge = new badge($this->badgeid);
92
        // Insert tags for the badge.
93
        core_tag_tag::set_item_tags('core_badges', 'badge', $badge->id, $badge->get_context(), ['tag1', 'tag2']);
94
 
95
        $newid1 = $badge->make_clone();
96
        $newid2 = $badge->make_clone();
97
        $newid3 = $badge->make_clone();
98
 
99
        // Insert related badges to badge 1.
100
        $badge->add_related_badges([$newid1, $newid2, $newid3]);
101
 
102
        // Another badge.
103
        $badge2 = new badge($newid2);
104
        // Make badge 1 related for badge 2.
105
        $badge2->add_related_badges([$this->badgeid]);
106
 
107
        // Confirm that the records about this badge about its relations have been removed as well.
108
        $relatedsql = 'badgeid = :badgeid OR relatedbadgeid = :relatedbadgeid';
109
        $relatedparams = array(
110
            'badgeid' => $this->badgeid,
111
            'relatedbadgeid' => $this->badgeid
112
        );
113
        // Badge 1 has 4 related records. 3 where it's the badgeid, 1 where it's the relatedbadgeid.
114
        $this->assertEquals(4, $DB->count_records_select('badge_related', $relatedsql, $relatedparams));
115
 
116
        // Badge has 2 tag instance records.
117
        $this->assertEquals(2, $DB->count_records('tag_instance', ['itemid' => $this->badgeid]));
118
 
119
        // Delete the badge for real.
120
        $badge->delete(false);
121
 
122
        // Confirm that the badge itself has been removed.
123
        $this->assertFalse($DB->record_exists('badge', ['id' => $this->badgeid]));
124
 
125
        // Confirm that the records about this badge about its relations have been removed as well.
126
        $this->assertFalse($DB->record_exists_select('badge_related', $relatedsql, $relatedparams));
127
 
128
        // Confirm that the tag instance of the badge has been removed.
129
        $this->assertFalse($DB->record_exists('tag_instance', ['itemid' => $this->badgeid]));
130
    }
131
 
11 efrain 132
    public function test_create_badge_criteria(): void {
1 efrain 133
        $badge = new badge($this->badgeid);
134
        $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
135
        $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL));
136
 
137
        $this->assertCount(1, $badge->get_criteria());
138
 
139
        $criteria_profile = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $badge->id));
140
        $params = array('agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address');
141
        $criteria_profile->save($params);
142
 
143
        $this->assertCount(2, $badge->get_criteria());
144
    }
145
 
11 efrain 146
    public function test_add_badge_criteria_description(): void {
1 efrain 147
        $criteriaoverall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $this->badgeid));
148
        $criteriaoverall->save(array(
149
                'agg' => BADGE_CRITERIA_AGGREGATION_ALL,
150
                'description' => 'Overall description',
151
                'descriptionformat' => FORMAT_HTML
152
        ));
153
 
154
        $criteriaprofile = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $this->badgeid));
155
        $params = array(
156
                'agg' => BADGE_CRITERIA_AGGREGATION_ALL,
157
                'field_address' => 'address',
158
                'description' => 'Description',
159
                'descriptionformat' => FORMAT_HTML
160
        );
161
        $criteriaprofile->save($params);
162
 
163
        $badge = new badge($this->badgeid);
164
        $this->assertEquals('Overall description', $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->description);
165
        $this->assertEquals('Description', $badge->criteria[BADGE_CRITERIA_TYPE_PROFILE]->description);
166
    }
167
 
11 efrain 168
    public function test_delete_badge_criteria(): void {
1 efrain 169
        $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $this->badgeid));
170
        $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL));
171
        $badge = new badge($this->badgeid);
172
 
173
        $this->assertInstanceOf('award_criteria_overall', $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
174
 
175
        $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->delete();
176
        $this->assertEmpty($badge->get_criteria());
177
    }
178
 
11 efrain 179
    public function test_badge_awards(): void {
1 efrain 180
        global $DB;
181
        $this->preventResetByRollback(); // Messaging is not compatible with transactions.
182
        $badge = new badge($this->badgeid);
183
        $user1 = $this->getDataGenerator()->create_user();
184
 
185
        $sink = $this->redirectMessages();
186
 
187
        $DB->set_field_select('message_processors', 'enabled', 0, "name <> 'email'");
188
        set_user_preference('message_provider_moodle_badgerecipientnotice_enabled', 'email', $user1);
189
 
190
        $badge->issue($user1->id, false);
191
        $this->assertDebuggingCalled(); // Expect debugging while baking a badge via phpunit.
192
        $this->assertTrue($badge->is_issued($user1->id));
193
 
194
        $messages = $sink->get_messages();
195
        $sink->close();
196
        $this->assertCount(1, $messages);
197
        $message = array_pop($messages);
198
        // Check we have the expected data.
199
        $customdata = json_decode($message->customdata);
200
        $this->assertObjectHasProperty('notificationiconurl', $customdata);
201
        $this->assertObjectHasProperty('hash', $customdata);
202
 
203
        $user2 = $this->getDataGenerator()->create_user();
204
        $badge->issue($user2->id, true);
205
        $this->assertTrue($badge->is_issued($user2->id));
206
 
207
        $this->assertCount(2, $badge->get_awards());
208
    }
209
 
210
    /**
211
     * Test the {@link badges_get_user_badges()} function in lib/badgeslib.php
212
     */
11 efrain 213
    public function test_badges_get_user_badges(): void {
1 efrain 214
        global $DB;
215
 
216
        // Messaging is not compatible with transactions.
217
        $this->preventResetByRollback();
218
 
219
        $badges = array();
220
        $user1 = $this->getDataGenerator()->create_user();
221
        $user2 = $this->getDataGenerator()->create_user();
222
 
223
        // Record the current time, we need to be precise about a couple of things.
224
        $now = time();
225
        // Create 11 badges with which to test.
226
        for ($i = 1; $i <= 11; $i++) {
227
            // Mock up a badge.
228
            $badge = new stdClass();
229
            $badge->id = null;
230
            $badge->name = "Test badge $i";
231
            $badge->description = "Testing badges $i";
232
            $badge->timecreated = $now - 12;
233
            $badge->timemodified = $now - 12;
234
            $badge->usercreated = $user1->id;
235
            $badge->usermodified = $user1->id;
236
            $badge->issuername = "Test issuer";
237
            $badge->issuerurl = "http://issuer-url.domain.co.nz";
238
            $badge->issuercontact = "issuer@example.com";
239
            $badge->expiredate = null;
240
            $badge->expireperiod = null;
241
            $badge->type = BADGE_TYPE_SITE;
242
            $badge->courseid = null;
243
            $badge->messagesubject = "Test message subject for badge $i";
244
            $badge->message = "Test message body for badge $i";
245
            $badge->attachment = 1;
246
            $badge->notification = 0;
247
            $badge->status = BADGE_STATUS_INACTIVE;
248
            $badge->version = "Version $i";
249
            $badge->language = "en";
250
            $badge->imagecaption = "Image caption $i";
251
 
252
            $badgeid = $DB->insert_record('badge', $badge, true);
253
            $badges[$badgeid] = new badge($badgeid);
254
            $badges[$badgeid]->issue($user2->id, true);
255
            // Check it all actually worked.
256
            $this->assertCount(1, $badges[$badgeid]->get_awards());
257
 
258
            // Hack the database to adjust the time each badge was issued.
259
            // The alternative to this is sleep which is a no-no in unit tests.
260
            $DB->set_field('badge_issued', 'dateissued', $now - 11 + $i, array('userid' => $user2->id, 'badgeid' => $badgeid));
261
        }
262
 
263
        // Make sure the first user has no badges.
264
        $result = badges_get_user_badges($user1->id);
265
        $this->assertIsArray($result);
266
        $this->assertCount(0, $result);
267
 
268
        // Check that the second user has the expected 11 badges.
269
        $result = badges_get_user_badges($user2->id);
270
        $this->assertCount(11, $result);
271
 
272
        // Test pagination.
273
        // Ordering is by time issued desc, so things will come out with the last awarded badge first.
274
        $result = badges_get_user_badges($user2->id, 0, 0, 4);
275
        $this->assertCount(4, $result);
276
        $lastbadgeissued = reset($result);
277
        $this->assertSame('Test badge 11', $lastbadgeissued->name);
278
        // Page 2. Expecting 4 results again.
279
        $result = badges_get_user_badges($user2->id, 0, 1, 4);
280
        $this->assertCount(4, $result);
281
        $lastbadgeissued = reset($result);
282
        $this->assertSame('Test badge 7', $lastbadgeissued->name);
283
        // Page 3. Expecting just three results here.
284
        $result = badges_get_user_badges($user2->id, 0, 2, 4);
285
        $this->assertCount(3, $result);
286
        $lastbadgeissued = reset($result);
287
        $this->assertSame('Test badge 3', $lastbadgeissued->name);
288
        // Page 4.... there is no page 4.
289
        $result = badges_get_user_badges($user2->id, 0, 3, 4);
290
        $this->assertCount(0, $result);
291
 
292
        // Test search.
293
        $result = badges_get_user_badges($user2->id, 0, 0, 0, 'badge 1');
294
        $this->assertCount(3, $result);
295
        $lastbadgeissued = reset($result);
296
        $this->assertSame('Test badge 11', $lastbadgeissued->name);
297
        // The term Totara doesn't appear anywhere in the badges.
298
        $result = badges_get_user_badges($user2->id, 0, 0, 0, 'Totara');
299
        $this->assertCount(0, $result);
300
 
301
        // Issue a user with a course badge and verify its returned based on if
302
        // coursebadges are enabled or disabled.
303
        $sitebadgeid = key($badges);
304
        $badges[$sitebadgeid]->issue($this->user->id, true);
305
 
306
        $badge = new stdClass();
307
        $badge->id = null;
308
        $badge->name = "Test course badge";
309
        $badge->description = "Testing course badge";
310
        $badge->timecreated = $now;
311
        $badge->timemodified = $now;
312
        $badge->usercreated = $user1->id;
313
        $badge->usermodified = $user1->id;
314
        $badge->issuername = "Test issuer";
315
        $badge->issuerurl = "http://issuer-url.domain.co.nz";
316
        $badge->issuercontact = "issuer@example.com";
317
        $badge->expiredate = null;
318
        $badge->expireperiod = null;
319
        $badge->type = BADGE_TYPE_COURSE;
320
        $badge->courseid = $this->course->id;
321
        $badge->messagesubject = "Test message subject for course badge";
322
        $badge->message = "Test message body for course badge";
323
        $badge->attachment = 1;
324
        $badge->notification = 0;
325
        $badge->status = BADGE_STATUS_ACTIVE;
326
        $badge->version = "Version $i";
327
        $badge->language = "en";
328
        $badge->imagecaption = "Image caption";
329
 
330
        $badgeid = $DB->insert_record('badge', $badge, true);
331
        $badges[$badgeid] = new badge($badgeid);
332
        $badges[$badgeid]->issue($this->user->id, true);
333
 
334
        // With coursebadges off, we should only get the site badge.
335
        set_config('badges_allowcoursebadges', false);
336
        $result = badges_get_user_badges($this->user->id);
337
        $this->assertCount(1, $result);
338
 
339
        // With it on, we should get both.
340
        set_config('badges_allowcoursebadges', true);
341
        $result = badges_get_user_badges($this->user->id);
342
        $this->assertCount(2, $result);
343
 
344
    }
345
 
1441 ariadna 346
    public static function data_for_message_from_template(): array {
1 efrain 347
        return array(
348
            array(
349
                'This is a message with no variables',
350
                array(), // no params
351
                'This is a message with no variables'
352
            ),
353
            array(
354
                'This is a message with %amissing% variables',
355
                array(), // no params
356
                'This is a message with %amissing% variables'
357
            ),
358
            array(
359
                'This is a message with %one% variable',
360
                array('one' => 'a single'),
361
                'This is a message with a single variable'
362
            ),
363
            array(
364
                'This is a message with %one% %two% %three% variables',
365
                array('one' => 'more', 'two' => 'than', 'three' => 'one'),
366
                'This is a message with more than one variables'
367
            ),
368
            array(
369
                'This is a message with %three% %two% %one%',
370
                array('one' => 'variables', 'two' => 'ordered', 'three' => 'randomly'),
371
                'This is a message with randomly ordered variables'
372
            ),
373
            array(
374
                'This is a message with %repeated% %one% %repeated% of variables',
375
                array('one' => 'and', 'repeated' => 'lots'),
376
                'This is a message with lots and lots of variables'
377
            ),
378
        );
379
    }
380
 
381
    /**
382
     * @dataProvider data_for_message_from_template
383
     */
11 efrain 384
    public function test_badge_message_from_template($message, $params, $result): void {
1 efrain 385
        $this->assertEquals(badge_message_from_template($message, $params), $result);
386
    }
387
 
388
    /**
389
     * Test for working around the 61 tables join limit of mysql in award_criteria_activity in combination with the scheduled task.
390
     *
391
     * @covers \core_badges\badge::review_all_criteria
392
     */
11 efrain 393
    public function test_badge_activity_criteria_with_a_huge_number_of_coursemodules(): void {
1 efrain 394
        global $CFG;
395
        require_once($CFG->dirroot.'/completion/criteria/completion_criteria_activity.php');
396
 
397
        if (!PHPUNIT_LONGTEST) {
398
            $this->markTestSkipped('PHPUNIT_LONGTEST is not defined');
399
        }
400
 
401
        // Messaging is not compatible with transactions.
402
        $this->preventResetByRollback();
403
 
404
        // Create more than 61 modules to potentially trigger an mysql db error.
405
        $assigncount = 75;
406
        $assigns = [];
407
        for ($i = 1; $i <= $assigncount; $i++) {
408
            $assigns[] = $this->getDataGenerator()->create_module('assign', ['course' => $this->course->id], ['completion' => 1]);
409
        }
410
        $assigncmids = array_flip(array_map(fn ($assign) => $assign->cmid, $assigns));
411
        $criteriaactivityarray = array_fill_keys(array_keys($assigncmids), 1);
412
 
413
        // Set completion criteria.
414
        $criteriadata = (object) [
415
            'id' => $this->course->id,
416
            'criteria_activity' => $criteriaactivityarray,
417
        ];
418
        $criterion = new completion_criteria_activity();
419
        $criterion->update_config($criteriadata);
420
 
421
        $badge = new badge($this->coursebadge);
422
 
423
        $criteriaoverall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
424
        $criteriaoverall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
425
        $criteriaactivity = award_criteria::build(['criteriatype' => BADGE_CRITERIA_TYPE_ACTIVITY, 'badgeid' => $badge->id]);
426
 
427
        $modulescrit = ['agg' => BADGE_CRITERIA_AGGREGATION_ALL];
428
        foreach ($assigns as $assign) {
429
            $modulescrit['module_' . $assign->cmid] = $assign->cmid;
430
        }
431
        $criteriaactivity->save($modulescrit);
432
 
433
        // Take one assign to complete it later.
434
        $assigntemp = array_shift($assigns);
435
 
436
        // Mark the user to complete the modules.
437
        foreach ($assigns as $assign) {
438
            $cmassign = get_coursemodule_from_id('assign', $assign->cmid);
439
            $completion = new \completion_info($this->course);
440
            $completion->update_state($cmassign, COMPLETION_COMPLETE, $this->user->id);
441
        }
442
 
443
        // Run the scheduled task to issue the badge. But the badge should not be issued.
444
        ob_start();
445
        $task = manager::get_scheduled_task('core\task\badges_cron_task');
446
        $task->execute();
447
        ob_end_clean();
448
 
449
        $this->assertFalse($badge->is_issued($this->user->id));
450
 
451
        // Now complete the last uncompleted module.
452
        $cmassign = get_coursemodule_from_id('assign', $assigntemp->cmid);
453
        $completion = new \completion_info($this->course);
454
        $completion->update_state($cmassign, COMPLETION_COMPLETE, $this->user->id);
455
 
456
        // Run the scheduled task to issue the badge. Now the badge schould be issued.
457
        ob_start();
458
        $task = manager::get_scheduled_task('core\task\badges_cron_task');
459
        $task->execute();
460
        ob_end_clean();
461
 
462
        $this->assertDebuggingCalled('Error baking badge image!');
463
        $this->assertTrue($badge->is_issued($this->user->id));
464
    }
465
 
466
    /**
467
     * Test badges observer when course module completion event id fired.
468
     */
11 efrain 469
    public function test_badges_observer_course_module_criteria_review(): void {
1 efrain 470
        $this->preventResetByRollback(); // Messaging is not compatible with transactions.
471
        $badge = new badge($this->coursebadge);
472
        $this->assertFalse($badge->is_issued($this->user->id));
473
 
474
        $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
475
        $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
476
        $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_ACTIVITY, 'badgeid' => $badge->id));
477
        $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'module_'.$this->module->cmid => $this->module->cmid));
478
 
479
        // Assert the badge will not be issued to the user as is.
480
        $badge = new badge($this->coursebadge);
481
        $badge->review_all_criteria();
482
        $this->assertFalse($badge->is_issued($this->user->id));
483
 
484
        // Set completion for forum activity.
485
        $c = new completion_info($this->course);
486
        $activities = $c->get_activities();
487
        $this->assertEquals(1, count($activities));
488
        $this->assertTrue(isset($activities[$this->module->cmid]));
489
        $this->assertEquals($activities[$this->module->cmid]->name, $this->module->name);
490
 
491
        $current = $c->get_data($activities[$this->module->cmid], false, $this->user->id);
492
        $current->completionstate = COMPLETION_COMPLETE;
493
        $current->timemodified = time();
494
        $sink = $this->redirectEmails();
495
        $c->internal_set_data($activities[$this->module->cmid], $current);
496
        $this->assertCount(1, $sink->get_messages());
497
        $sink->close();
498
 
499
        // Check if badge is awarded.
500
        $this->assertDebuggingCalled('Error baking badge image!');
501
        $this->assertTrue($badge->is_issued($this->user->id));
502
    }
503
 
504
    /**
505
     * Test badges observer when course_completed event is fired.
506
     */
11 efrain 507
    public function test_badges_observer_course_criteria_review(): void {
1 efrain 508
        $this->preventResetByRollback(); // Messaging is not compatible with transactions.
509
        $badge = new badge($this->coursebadge);
510
        $this->assertFalse($badge->is_issued($this->user->id));
511
 
512
        $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
513
        $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
514
        $criteria_overall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_COURSE, 'badgeid' => $badge->id));
515
        $criteria_overall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'course_'.$this->course->id => $this->course->id));
516
 
517
        $ccompletion = new completion_completion(array('course' => $this->course->id, 'userid' => $this->user->id));
518
 
519
        // Assert the badge will not be issued to the user as is.
520
        $badge = new badge($this->coursebadge);
521
        $badge->review_all_criteria();
522
        $this->assertFalse($badge->is_issued($this->user->id));
523
 
524
        // Mark course as complete.
525
        $sink = $this->redirectMessages();
526
        $ccompletion->mark_complete();
527
        // Two messages are generated: One for the course completed and the other one for the badge awarded.
528
        $messages = $sink->get_messages();
529
        $this->assertCount(2, $messages);
530
        $this->assertEquals('badgerecipientnotice', $messages[0]->eventtype);
531
        $this->assertEquals('coursecompleted', $messages[1]->eventtype);
532
        $sink->close();
533
 
534
        // Check if badge is awarded.
535
        $this->assertDebuggingCalled('Error baking badge image!');
536
        $this->assertTrue($badge->is_issued($this->user->id));
537
    }
538
 
539
    /**
540
     * Test badges observer when user_updated event is fired.
541
     */
11 efrain 542
    public function test_badges_observer_profile_criteria_review(): void {
1 efrain 543
        global $CFG, $DB;
544
        require_once($CFG->dirroot.'/user/profile/lib.php');
545
 
546
        // Add a custom field of textarea type.
547
        $customprofileid = $this->getDataGenerator()->create_custom_profile_field(array(
548
            'shortname' => 'newfield', 'name' => 'Description of new field',
549
            'datatype' => 'textarea'))->id;
550
 
551
        $this->preventResetByRollback(); // Messaging is not compatible with transactions.
552
        $badge = new badge($this->coursebadge);
553
 
554
        $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
555
        $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
556
        $criteria_overall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $badge->id));
557
        $criteria_overall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address',
558
            'field_department' => 'department', 'field_' . $customprofileid => $customprofileid));
559
 
560
        // Assert the badge will not be issued to the user as is.
561
        $badge = new badge($this->coursebadge);
562
        $badge->review_all_criteria();
563
        $this->assertFalse($badge->is_issued($this->user->id));
564
 
565
        // Set the required fields and make sure the badge got issued.
566
        $this->user->address = 'Test address';
567
        $this->user->department = 'sillywalks';
568
        $sink = $this->redirectEmails();
569
        profile_save_data((object)array('id' => $this->user->id, 'profile_field_newfield' => 'X'));
570
        user_update_user($this->user, false);
571
        $this->assertCount(1, $sink->get_messages());
572
        $sink->close();
573
        // Check if badge is awarded.
574
        $this->assertDebuggingCalled('Error baking badge image!');
575
        $this->assertTrue($badge->is_issued($this->user->id));
576
    }
577
 
578
    /**
579
     * Test badges observer when cohort_member_added event is fired and user required to belong to any cohort.
580
     *
581
     * @covers \award_criteria_cohort
582
     */
11 efrain 583
    public function test_badges_observer_any_cohort_criteria_review(): void {
1 efrain 584
        global $CFG;
585
 
586
        require_once("$CFG->dirroot/cohort/lib.php");
587
 
588
        $cohort1 = $this->getDataGenerator()->create_cohort();
589
        $cohort2 = $this->getDataGenerator()->create_cohort();
590
 
591
        $this->preventResetByRollback(); // Messaging is not compatible with transactions.
592
 
593
        $badge = new badge($this->badgeid);
594
        $this->assertFalse($badge->is_issued($this->user->id));
595
        $this->assertSame(0, $badge->review_all_criteria()); // Verify award_criteria_cohort->get_completed_criteria_sql().
596
 
597
        // Set up the badge criteria.
598
        $criteriaoverall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
599
        $criteriaoverall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
600
        $criteriaoverall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_COHORT, 'badgeid' => $badge->id));
601
        $criteriaoverall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY,
602
            'cohort_cohorts' => array('0' => $cohort1->id, '1' => $cohort2->id)));
603
        $badge->set_status(BADGE_STATUS_ACTIVE);
604
 
605
        // Reload it to contain criteria.
606
        $badge = new badge($this->badgeid);
607
        $this->assertFalse($badge->is_issued($this->user->id));
608
        $this->assertSame(0, $badge->review_all_criteria()); // Verify award_criteria_cohort->get_completed_criteria_sql().
609
 
610
        // Add the user to the cohort.
611
        cohort_add_member($cohort2->id, $this->user->id);
612
        $this->assertDebuggingCalled();
613
 
614
        // Verify that the badge was awarded.
615
        $this->assertTrue($badge->is_issued($this->user->id));
616
        // As the badge has been awarded to user because core_badges_observer been called when the member has been added to the
617
        // cohort, there are no other users that can award this badge.
618
        $this->assertSame(0, $badge->review_all_criteria()); // Verify award_criteria_cohort->get_completed_criteria_sql().
619
    }
620
 
621
    /**
11 efrain 622
     * Test badges observer when user_updated event is fired.
623
     * @covers \award_criteria_courseset
624
     */
625
    public function test_badges_observer_courseset_criteria_review(): void {
626
        $this->preventResetByRollback(); // Messaging is not compatible with transactions.
627
        $badge = new badge($this->coursebadge);
628
        $this->assertFalse($badge->is_issued($this->user->id));
629
 
630
        $additionalcourse = $this->getDataGenerator()->create_course(['enablecompletion' => true]);
631
        $this->getDataGenerator()->enrol_user($this->user->id, $additionalcourse->id);
632
 
633
        $criteriaoverall = award_criteria::build(['criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id]);
634
        $criteriaoverall->save(['agg' => BADGE_CRITERIA_AGGREGATION_ANY]);
635
        $criteriaoverall1 = award_criteria::build(['criteriatype' => BADGE_CRITERIA_TYPE_COURSESET, 'badgeid' => $badge->id]);
636
        $criteriaoverall1->save(['agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'course_' . $this->course->id => $this->course->id,
637
            'course_' . $additionalcourse->id => $additionalcourse->id]);
638
 
639
        $ccompletion = new completion_completion(['course' => $this->course->id, 'userid' => $this->user->id]);
640
        $ccompletion2 = new completion_completion(['course' => $additionalcourse->id, 'userid' => $this->user->id]);
641
        // Assert the badge will not be issued to the user as is.
642
        $badge = new badge($this->coursebadge);
643
        $badge->review_all_criteria();
644
        $this->assertFalse($badge->is_issued($this->user->id));
645
 
646
        // Mark course as complete.
647
        $sink = $this->redirectMessages();
648
        $ccompletion->mark_complete();
649
        $ccompletion2->mark_complete();
650
        // Thee messages are generated: Two for the course completed and the other one for the badge awarded.
651
        $messages = $sink->get_messages();
652
        $this->assertCount(3, $messages);
653
        $this->assertEquals('badgerecipientnotice', $messages[0]->eventtype);
654
        $this->assertEquals('coursecompleted', $messages[1]->eventtype);
655
        $sink->close();
656
 
657
        // Check if badge is awarded.
658
        $this->assertDebuggingCalled('Error baking badge image!');
659
        $this->assertTrue($badge->is_issued($this->user->id));
660
    }
661
 
662
    /**
663
     * Test the criteria review method for courseset
664
     * @covers \award_criteria_courseset::review
665
     */
666
    public function test_badges_courseset_criteria_review_empty_courseset(): void {
667
        $this->preventResetByRollback(); // Messaging is not compatible with transactions.
668
        $badge = new badge($this->coursebadge);
669
        $this->assertFalse($badge->is_issued($this->user->id));
670
 
671
        $criteriaoverall = award_criteria::build(['criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id]);
672
        $criteriaoverall->save(['agg' => BADGE_CRITERIA_AGGREGATION_ANY]);
673
        $criteriaoverall1 = award_criteria::build(['criteriatype' => BADGE_CRITERIA_TYPE_COURSESET, 'badgeid' => $badge->id]);
674
        $criteriaoverall1->save();
675
        // Assert the badge will not be issued to the user as is.
676
        $badge = new badge($this->coursebadge);
677
        $badge->review_all_criteria();
678
        $this->assertFalse($badge->is_issued($this->user->id));
679
    }
680
 
681
    /**
1 efrain 682
     * Test badges observer when cohort_member_added event is fired and user required to belong to multiple (all) cohorts.
683
     *
684
     * @covers \award_criteria_cohort
685
     */
11 efrain 686
    public function test_badges_observer_all_cohort_criteria_review(): void {
1 efrain 687
        global $CFG;
688
 
689
        require_once("$CFG->dirroot/cohort/lib.php");
690
 
691
        $cohort1 = $this->getDataGenerator()->create_cohort();
692
        $cohort2 = $this->getDataGenerator()->create_cohort();
693
        $cohort3 = $this->getDataGenerator()->create_cohort();
694
 
695
        // Add user2 to cohort1 and cohort3.
696
        $user2 = $this->getDataGenerator()->create_user();
697
        cohort_add_member($cohort3->id, $user2->id);
698
        cohort_add_member($cohort1->id, $user2->id);
699
 
700
        // Add user3 to cohort1, cohort2 and cohort3.
701
        $user3 = $this->getDataGenerator()->create_user();
702
        cohort_add_member($cohort1->id, $user3->id);
703
        cohort_add_member($cohort2->id, $user3->id);
704
        cohort_add_member($cohort3->id, $user3->id);
705
 
706
        $this->preventResetByRollback(); // Messaging is not compatible with transactions.
707
 
708
        // Cohort criteria are used in site badges.
709
        $badge = new badge($this->badgeid);
710
 
711
        $this->assertFalse($badge->is_issued($this->user->id));
712
        $this->assertSame(0, $badge->review_all_criteria()); // Verify award_criteria_cohort->get_completed_criteria_sql().
713
 
714
        // Set up the badge criteria.
715
        $criteriaoverall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
716
        $criteriaoverall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
717
        $criteriaoverall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_COHORT, 'badgeid' => $badge->id));
718
        $criteriaoverall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL,
719
            'cohort_cohorts' => array('0' => $cohort1->id, '1' => $cohort2->id, '2' => $cohort3->id)));
720
        $badge->set_status(BADGE_STATUS_ACTIVE);
721
 
722
        // Reload it to contain criteria.
723
        $badge = new badge($this->badgeid);
724
 
725
        // Verify that the badge was not awarded yet (ALL cohorts are needed and review_all_criteria has to be called).
726
        $this->assertFalse($badge->is_issued($this->user->id));
727
        $this->assertFalse($badge->is_issued($user2->id));
728
        $this->assertFalse($badge->is_issued($user3->id));
729
 
730
        // Verify that after calling review_all_criteria, users with the criteria (user3) award the badge instantly.
731
        $this->assertSame(1, $badge->review_all_criteria()); // Verify award_criteria_cohort->get_completed_criteria_sql().
732
        $this->assertFalse($badge->is_issued($this->user->id));
733
        $this->assertFalse($badge->is_issued($user2->id));
734
        $this->assertTrue($badge->is_issued($user3->id));
735
        $this->assertDebuggingCalled();
736
 
737
        // Add the user to the cohort1.
738
        cohort_add_member($cohort1->id, $this->user->id);
739
 
740
        // Verify that the badge was not awarded yet (ALL cohorts are needed).
741
        $this->assertFalse($badge->is_issued($this->user->id));
742
        $this->assertSame(0, $badge->review_all_criteria()); // Verify award_criteria_cohort->get_completed_criteria_sql().
743
 
744
        // Add the user to the cohort3.
745
        cohort_add_member($cohort3->id, $this->user->id);
746
 
747
        // Verify that the badge was not awarded yet (ALL cohorts are needed).
748
        $this->assertFalse($badge->is_issued($this->user->id));
749
        $this->assertSame(0, $badge->review_all_criteria()); // Verify award_criteria_cohort->get_completed_criteria_sql().
750
 
751
        // Add user to cohort2.
752
        cohort_add_member($cohort2->id, $this->user->id);
753
        $this->assertDebuggingCalled();
754
 
755
        // Verify that the badge was awarded (ALL cohorts).
756
        $this->assertTrue($badge->is_issued($this->user->id));
757
        // As the badge has been awarded to user because core_badges_observer been called when the member has been added to the
758
        // cohort, there are no other users that can award this badge.
759
        $this->assertSame(0, $badge->review_all_criteria()); // Verify award_criteria_cohort->get_completed_criteria_sql().
760
    }
761
 
762
    /**
763
     * Test badges assertion generated when a badge is issued.
764
     */
11 efrain 765
    public function test_badges_assertion(): void {
1 efrain 766
        $this->preventResetByRollback(); // Messaging is not compatible with transactions.
767
        $badge = new badge($this->coursebadge);
768
        $this->assertFalse($badge->is_issued($this->user->id));
769
 
1441 ariadna 770
        $criteriaoverall = award_criteria::build(['criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id]);
771
        $criteriaoverall->save(['agg' => BADGE_CRITERIA_AGGREGATION_ANY]);
772
        $criteriaoverall1 = award_criteria::build(['criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $badge->id]);
773
        $criteriaoverall1->save(['agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address']);
1 efrain 774
 
775
        $this->user->address = 'Test address';
776
        $sink = $this->redirectEmails();
777
        user_update_user($this->user, false);
778
        $this->assertCount(1, $sink->get_messages());
779
        $sink->close();
780
        // Check if badge is awarded.
781
        $this->assertDebuggingCalled('Error baking badge image!');
782
        $awards = $badge->get_awards();
783
        $this->assertCount(1, $awards);
784
 
1441 ariadna 785
        // Test Openbadge specification version 2.0.
1 efrain 786
        // Get assertion version 2.
787
        $award = reset($awards);
788
        $assertion2 = new core_badges_assertion($award->uniquehash, OPEN_BADGES_V2);
789
        $testassertion2 = $this->assertion2;
790
 
791
        // Make sure JSON strings have the same structure.
792
        $this->assertStringMatchesFormat($testassertion2->badge, json_encode($assertion2->get_badge_assertion()));
793
        $this->assertStringMatchesFormat($testassertion2->class, json_encode($assertion2->get_badge_class()));
794
        $this->assertStringMatchesFormat($testassertion2->issuer, json_encode($assertion2->get_issuer()));
795
 
796
        // Test Openbadge specification version 2.1. It has the same format as OBv2.0.
797
        // Get assertion version 2.1.
798
        $award = reset($awards);
799
        $assertion2 = new core_badges_assertion($award->uniquehash, OPEN_BADGES_V2P1);
800
 
801
        // Make sure JSON strings have the same structure.
802
        $this->assertStringMatchesFormat($testassertion2->badge, json_encode($assertion2->get_badge_assertion()));
803
        $this->assertStringMatchesFormat($testassertion2->class, json_encode($assertion2->get_badge_class()));
804
        $this->assertStringMatchesFormat($testassertion2->issuer, json_encode($assertion2->get_issuer()));
805
    }
806
 
807
    /**
808
     * Tests the core_badges_myprofile_navigation() function.
809
     */
11 efrain 810
    public function test_core_badges_myprofile_navigation(): void {
1 efrain 811
        // Set up the test.
812
        $tree = new \core_user\output\myprofile\tree();
813
        $this->setAdminUser();
814
        $badge = new badge($this->badgeid);
815
        $badge->issue($this->user->id, true);
816
        $iscurrentuser = true;
817
        $course = null;
818
 
819
        // Enable badges.
820
        set_config('enablebadges', true);
821
 
822
        // Check the node tree is correct.
823
        core_badges_myprofile_navigation($tree, $this->user, $iscurrentuser, $course);
824
        $reflector = new ReflectionObject($tree);
825
        $nodes = $reflector->getProperty('nodes');
826
        $this->assertArrayHasKey('localbadges', $nodes->getValue($tree));
827
    }
828
 
829
    /**
830
     * Tests the core_badges_myprofile_navigation() function with badges disabled..
831
     */
11 efrain 832
    public function test_core_badges_myprofile_navigation_badges_disabled(): void {
1 efrain 833
        // Set up the test.
834
        $tree = new \core_user\output\myprofile\tree();
835
        $this->setAdminUser();
836
        $badge = new badge($this->badgeid);
837
        $badge->issue($this->user->id, true);
838
        $iscurrentuser = false;
839
        $course = null;
840
 
841
        // Disable badges.
842
        set_config('enablebadges', false);
843
 
844
        // Check the node tree is correct.
845
        core_badges_myprofile_navigation($tree, $this->user, $iscurrentuser, $course);
846
        $reflector = new ReflectionObject($tree);
847
        $nodes = $reflector->getProperty('nodes');
848
        $this->assertArrayNotHasKey('localbadges', $nodes->getValue($tree));
849
    }
850
 
851
    /**
852
     * Tests the core_badges_myprofile_navigation() function with a course badge.
853
     */
11 efrain 854
    public function test_core_badges_myprofile_navigation_with_course_badge(): void {
1 efrain 855
        // Set up the test.
856
        $tree = new \core_user\output\myprofile\tree();
857
        $this->setAdminUser();
858
        $badge = new badge($this->coursebadge);
859
        $badge->issue($this->user->id, true);
860
        $iscurrentuser = false;
861
 
862
        // Check the node tree is correct.
863
        core_badges_myprofile_navigation($tree, $this->user, $iscurrentuser, $this->course);
864
        $reflector = new ReflectionObject($tree);
865
        $nodes = $reflector->getProperty('nodes');
866
        $this->assertArrayHasKey('localbadges', $nodes->getValue($tree));
867
    }
868
 
869
    /**
870
     * Test insert and update endorsement with a site badge.
871
     */
11 efrain 872
    public function test_badge_endorsement(): void {
1 efrain 873
        $badge = new badge($this->badgeid);
874
 
875
        // Insert Endorsement.
876
        $endorsement = new stdClass();
877
        $endorsement->badgeid = $this->badgeid;
878
        $endorsement->issuername = "Issuer 123";
879
        $endorsement->issueremail = "issuer123@email.com";
880
        $endorsement->issuerurl = "https://example.org/issuer-123";
881
        $endorsement->dateissued = 1524567747;
882
        $endorsement->claimid = "https://example.org/robotics-badge.json";
883
        $endorsement->claimcomment = "Test endorser comment";
884
 
885
        $badge->save_endorsement($endorsement);
886
        $endorsement1 = $badge->get_endorsement();
887
        $this->assertEquals($endorsement->badgeid, $endorsement1->badgeid);
888
        $this->assertEquals($endorsement->issuername, $endorsement1->issuername);
889
        $this->assertEquals($endorsement->issueremail, $endorsement1->issueremail);
890
        $this->assertEquals($endorsement->issuerurl, $endorsement1->issuerurl);
891
        $this->assertEquals($endorsement->dateissued, $endorsement1->dateissued);
892
        $this->assertEquals($endorsement->claimid, $endorsement1->claimid);
893
        $this->assertEquals($endorsement->claimcomment, $endorsement1->claimcomment);
894
 
895
        // Update Endorsement.
896
        $endorsement1->issuername = "Issuer update";
897
        $badge->save_endorsement($endorsement1);
898
        $endorsement2 = $badge->get_endorsement();
899
        $this->assertEquals($endorsement1->id, $endorsement2->id);
900
        $this->assertEquals($endorsement1->issuername, $endorsement2->issuername);
901
    }
902
 
903
    /**
904
     * Test insert and delete related badge with a site badge.
905
     */
11 efrain 906
    public function test_badge_related(): void {
1 efrain 907
        $badge = new badge($this->badgeid);
908
        $newid1 = $badge->make_clone();
909
        $newid2 = $badge->make_clone();
910
        $newid3 = $badge->make_clone();
911
 
912
        // Insert an related badge.
913
        $badge->add_related_badges([$newid1, $newid2, $newid3]);
914
        $this->assertCount(3, $badge->get_related_badges());
915
 
916
        // Only get related is active.
917
        $clonedbage1 = new badge($newid1);
918
        $clonedbage1->status = BADGE_STATUS_ACTIVE;
919
        $clonedbage1->save();
920
        $this->assertCount(1, $badge->get_related_badges(true));
921
 
922
        // Delete an related badge.
923
        $badge->delete_related_badge($newid2);
924
        $this->assertCount(2, $badge->get_related_badges());
925
    }
926
 
927
    /**
928
     * Test insert, update, delete alignment with a site badge.
929
     */
11 efrain 930
    public function test_alignments(): void {
1 efrain 931
        $badge = new badge($this->badgeid);
932
 
933
        // Insert a alignment.
934
        $alignment1 = new stdClass();
935
        $alignment1->badgeid = $this->badgeid;
936
        $alignment1->targetname = 'CCSS.ELA-Literacy.RST.11-12.3';
937
        $alignment1->targeturl = 'http://www.corestandards.org/ELA-Literacy/RST/11-12/3';
938
        $alignment1->targetdescription = 'Test target description';
939
        $alignment1->targetframework = 'CCSS.RST.11-12.3';
940
        $alignment1->targetcode = 'CCSS.RST.11-12.3';
941
        $alignment2 = clone $alignment1;
942
        $newid1 = $badge->save_alignment($alignment1);
943
        $newid2 = $badge->save_alignment($alignment2);
944
        $alignments1 = $badge->get_alignments();
945
        $this->assertCount(2, $alignments1);
946
 
947
        $this->assertEquals($alignment1->badgeid, $alignments1[$newid1]->badgeid);
948
        $this->assertEquals($alignment1->targetname, $alignments1[$newid1]->targetname);
949
        $this->assertEquals($alignment1->targeturl, $alignments1[$newid1]->targeturl);
950
        $this->assertEquals($alignment1->targetdescription, $alignments1[$newid1]->targetdescription);
951
        $this->assertEquals($alignment1->targetframework, $alignments1[$newid1]->targetframework);
952
        $this->assertEquals($alignment1->targetcode, $alignments1[$newid1]->targetcode);
953
 
954
        // Update aligment.
955
        $alignments1[$newid1]->targetname = 'CCSS.ELA-Literacy.RST.11-12.3 update';
956
        $badge->save_alignment($alignments1[$newid1], $alignments1[$newid1]->id);
957
        $alignments2 = $badge->get_alignments();
958
        $this->assertEquals($alignments1[$newid1]->id, $alignments2[$newid1]->id);
959
        $this->assertEquals($alignments1[$newid1]->targetname, $alignments2[$newid1]->targetname);
960
 
961
        // Delete alignment.
962
        $badge->delete_alignment($alignments1[$newid2]->id);
963
        $this->assertCount(1, $badge->get_alignments());
964
    }
965
 
966
    /**
967
     * Test badges_delete_site_backpack().
968
     *
969
     */
970
    public function test_badges_delete_site_backpack(): void {
971
        global $DB;
972
 
973
        $this->setAdminUser();
974
 
975
        // Create one backpack.
976
        $total = $DB->count_records('badge_external_backpack');
977
        $this->assertEquals(1, $total);
978
 
979
        $data = new \stdClass();
980
        $data->apiversion = OPEN_BADGES_V2P1;
981
        $data->backpackapiurl = 'https://dc.imsglobal.org/obchost/ims/ob/v2p1';
982
        $data->backpackweburl = 'https://dc.imsglobal.org';
983
        badges_create_site_backpack($data);
984
        $backpack = $DB->get_record('badge_external_backpack', ['backpackweburl' => $data->backpackweburl]);
985
        $user1 = $this->getDataGenerator()->create_user();
986
        $user2 = $this->getDataGenerator()->create_user();
987
        // User1 is connected to the backpack to be removed and has 2 collections.
988
        $backpackuser1 = helper::create_fake_backpack(['userid' => $user1->id, 'externalbackpackid' => $backpack->id]);
989
        helper::create_fake_backpack_collection(['backpackid' => $backpackuser1->id]);
990
        helper::create_fake_backpack_collection(['backpackid' => $backpackuser1->id]);
991
        // User2 is connected to a different backpack and has 1 collection.
992
        $backpackuser2 = helper::create_fake_backpack(['userid' => $user2->id]);
993
        helper::create_fake_backpack_collection(['backpackid' => $backpackuser2->id]);
994
 
995
        $total = $DB->count_records('badge_external_backpack');
996
        $this->assertEquals(2, $total);
997
        $total = $DB->count_records('badge_backpack');
998
        $this->assertEquals(2, $total);
999
        $total = $DB->count_records('badge_external');
1000
        $this->assertEquals(3, $total);
1001
 
1002
        // Remove the backpack created previously.
1003
        $result = badges_delete_site_backpack($backpack->id);
1004
        $this->assertTrue($result);
1005
 
1006
        $total = $DB->count_records('badge_external_backpack');
1007
        $this->assertEquals(1, $total);
1008
 
1009
        $total = $DB->count_records('badge_backpack');
1010
        $this->assertEquals(1, $total);
1011
 
1012
        $total = $DB->count_records('badge_external');
1013
        $this->assertEquals(1, $total);
1014
 
1015
        // Try to remove an non-existent backpack.
1016
        $result = badges_delete_site_backpack($backpack->id);
1017
        $this->assertFalse($result);
1018
    }
1019
 
1020
    /**
1021
     * Test to validate badges_save_backpack_credentials.
1022
     *
1023
     * @dataProvider save_backpack_credentials_provider
1024
     * @param  bool $addbackpack True if backpack data has to be created; false otherwise (empty data will be used then).
1025
     * @param  string|null  $mail  Backpack mail address.
1026
     * @param  string|null  $password  Backpack password.
1027
     */
11 efrain 1028
    public function test_save_backpack_credentials(bool $addbackpack = true, ?string $mail = null, ?string $password = null): void {
1 efrain 1029
        global $DB;
1030
 
1031
        $this->resetAfterTest();
1032
        $this->setAdminUser();
1033
 
1034
        $data = [];
1035
        if ($addbackpack) {
1036
            $data = new \stdClass();
1037
            $data->apiversion = OPEN_BADGES_V2P1;
1038
            $data->backpackapiurl = 'https://dc.imsglobal.org/obchost/ims/ob/v2p1';
1039
            $data->backpackweburl = 'https://dc.imsglobal.org';
1040
            badges_create_site_backpack($data);
1041
            $backpack = $DB->get_record('badge_external_backpack', ['backpackweburl' => $data->backpackweburl]);
1042
            $user = $this->getDataGenerator()->create_user();
1043
 
1044
            $data = [
1045
                'externalbackpackid' => $backpack->id,
1046
                'userid' => $user->id,
1047
            ];
1048
 
1049
            if (!empty($mail)) {
1050
                $data['backpackemail'] = $mail;
1051
            }
1052
            if (!empty($password)) {
1053
                $data['password'] = $password;
1054
            }
1055
        }
1056
 
1057
        $return = badges_save_backpack_credentials((object) $data);
1058
        if (array_key_exists('userid', $data)) {
1059
            $record = $DB->get_record('badge_backpack', ['userid' => $user->id]);
1060
        } else {
1061
            $record = $DB->get_records('badge_backpack');
1062
        }
1063
 
1064
        if (!empty($mail) && !empty($password)) {
1065
            // The backpack credentials are created if the given information is right.
1066
            $this->assertNotEmpty($record);
1067
            $this->assertEquals($data['externalbackpackid'], $return);
1068
        } else if ($addbackpack) {
1069
            // If no email and password are given, no backpack is created/modified.
1070
            $this->assertEmpty($record);
1071
            $this->assertEquals($data['externalbackpackid'], $return);
1072
        } else {
1073
            // There weren't fields to add to the backpack so no DB change is expected.
1074
            $this->assertEmpty($record);
1075
            $this->assertEquals(0, $return);
1076
        }
1077
 
1078
        // Confirm the existing backpack credential can be updated (if it has been created).
1079
        if (!empty($record)) {
1080
            $data['backpackemail'] = 'modified_' . $mail;
1081
            $data['id'] = $record->id;
1082
            $return = badges_save_backpack_credentials((object) $data);
1083
            $record = $DB->get_record('badge_backpack', ['userid' => $user->id]);
1084
 
1085
            $this->assertNotEmpty($record);
1086
            $this->assertEquals($data['backpackemail'], $record->email);
1087
            $this->assertEquals($data['externalbackpackid'], $return);
1088
        }
1089
    }
1090
 
1091
    /**
1092
     * Data provider for test_create_backpack_credentials().
1093
     *
1094
     * @return array
1095
     */
1441 ariadna 1096
    public static function save_backpack_credentials_provider(): array {
1 efrain 1097
        return [
1098
            'Empty fields' => [
1099
                false,
1100
            ],
1101
            'No backpack mail or password are defined' => [
1102
                true,
1103
            ],
1104
            'Both backpack mail and password are defined' => [
1105
                true, 'test@test.com', '1234',
1106
            ],
1107
            'Only backpack mail is defined (no password is given)' => [
1108
                true, 'test@test.com', null,
1109
            ],
1110
            'Only backpack password is defined (no mail is given)' => [
1111
                true, null, '1234'
1112
            ],
1113
        ];
1114
    }
1115
 
1116
    /**
1117
     * Test badges_save_external_backpack.
1118
     *
1119
     * @dataProvider badges_save_external_backpack_provider
1120
     * @param  array $data  Backpack data to save.
1121
     * @param  bool $adduser True if a real user has to be used for creating the backpack; false otherwise.
1122
     * @param  bool $duplicates True if duplicates has to be tested too; false otherwise.
1123
     */
11 efrain 1124
    public function test_badges_save_external_backpack(array $data, bool $adduser, bool $duplicates): void {
1 efrain 1125
        global $DB;
1126
 
1127
        $this->resetAfterTest();
1128
 
1129
        $userid = 0;
1130
        if ($adduser) {
1131
            $user = $this->getDataGenerator()->create_user();
1132
            $userid = $user->id;
1133
            $data['userid'] = $user->id;
1134
        }
1135
 
1136
        $result = badges_save_external_backpack((object) $data);
1137
        $this->assertNotEquals(0, $result);
1138
        $record = $DB->get_record('badge_external_backpack', ['id' => $result]);
1139
        $this->assertEquals($record->backpackweburl, $data['backpackweburl']);
1140
        $this->assertEquals($record->backpackapiurl, $data['backpackapiurl']);
1141
 
1142
        $record = $DB->get_record('badge_backpack', ['externalbackpackid' => $result]);
1143
        if (!array_key_exists('backpackemail', $data) && !array_key_exists('password', $data)) {
1144
            $this->assertEmpty($record);
1145
            $total = $DB->count_records('badge_backpack');
1146
            $this->assertEquals(0, $total);
1147
        } else {
1148
            $this->assertNotEmpty($record);
1149
            $this->assertEquals($record->userid, $userid);
1150
        }
1151
 
1152
        if ($duplicates) {
1153
            // We shouldn't be able to insert multiple external_backpacks with the same values.
1154
            $this->expectException('dml_write_exception');
1155
            $result = badges_save_external_backpack((object)$data);
1156
        }
1157
    }
1158
 
1159
    /**
1160
     * Provider for test_badges_save_external_backpack
1161
     *
1162
     * @return array
1163
     */
1441 ariadna 1164
    public static function badges_save_external_backpack_provider(): array {
1 efrain 1165
        $data = [
1166
            'apiversion' => 2,
1167
            'backpackapiurl' => 'https://api.ca.badgr.io/v2',
1168
            'backpackweburl' => 'https://ca.badgr.io',
1169
        ];
1170
        return [
1171
            'Test without user and auth details. Check duplicates too' => [
1172
                'data' => $data,
1173
                'adduser' => false,
1174
                'duplicates' => true,
1175
            ],
1176
            'Test without user and auth details. No duplicates' => [
1177
                'data' => $data,
1178
                'adduser' => false,
1179
                'duplicates' => false,
1180
            ],
1181
            'Test with user and without auth details' => [
1182
                'data' => $data,
1183
                'adduser' => true,
1184
                'duplicates' => false,
1185
            ],
1186
            'Test with user and without auth details. Check duplicates too' => [
1187
                'data' => $data,
1188
                'adduser' => true,
1189
                'duplicates' => true,
1190
            ],
1191
            'Test with empty backpackemail, password and id' => [
1192
                'data' => array_merge($data, [
1193
                    'backpackemail' => '',
1194
                    'password' => '',
1195
                    'id' => 0,
1196
                ]),
1197
                'adduser' => false,
1198
                'duplicates' => false,
1199
            ],
1200
            'Test with empty backpackemail, password and id but with user' => [
1201
                'data' => array_merge($data, [
1202
                    'backpackemail' => '',
1203
                    'password' => '',
1204
                    'id' => 0,
1205
                ]),
1206
                'adduser' => true,
1207
                'duplicates' => false,
1208
            ],
1209
            'Test with auth details but without user' => [
1210
                'data' => array_merge($data, [
1211
                    'backpackemail' => 'test@test.com',
1212
                    'password' => 'test',
1213
                ]),
1214
                'adduser' => false,
1215
                'duplicates' => false,
1216
            ],
1217
            'Test with auth details and user' => [
1218
                'data' => array_merge($data, [
1219
                    'backpackemail' => 'test@test.com',
1220
                    'password' => 'test',
1221
                ]),
1222
                'adduser' => true,
1223
                'duplicates' => false,
1224
            ],
1225
        ];
1226
    }
1227
 
1228
    /**
1229
     * Test backpack creation/update with auth details provided
1230
     *
1231
     * @param boolean $isadmin
1232
     * @param boolean $updatetest
1233
     * @dataProvider badges_create_site_backpack_provider
1234
     */
11 efrain 1235
    public function test_badges_create_site_backpack($isadmin, $updatetest): void {
1 efrain 1236
        global $DB;
1237
        $this->resetAfterTest();
1238
 
1239
        $data = [
1240
            'apiversion' => 2,
1241
            'backpackapiurl' => 'https://api.ca.badgr.io/v2',
1242
            'backpackweburl' => 'https://ca.badgr.io',
1243
        ];
1244
 
1245
        $data['backpackemail'] = 'test@test.com';
1246
        $data['password'] = 'test';
1247
        if ($isadmin || $updatetest) {
1248
            $this->setAdminUser();
1249
            $lastmax = $DB->get_field_sql('SELECT MAX(sortorder) FROM {badge_external_backpack}');
1250
            $backpack = badges_create_site_backpack((object) $data);
1251
        }
1252
 
1253
        if ($isadmin) {
1254
            if ($updatetest) {
1255
                $record = $DB->get_record('badge_backpack', ['userid' => 0]);
1256
                $data['badgebackpack'] = $record->id;
1257
                $data['backpackapiurl'] = 'https://api.ca.badgr.io/v3';
1258
                badges_update_site_backpack($backpack, (object)$data);
1259
            }
1260
            $record = $DB->get_record('badge_external_backpack', ['id' => $backpack]);
1261
            $this->assertEquals($data['backpackweburl'], $record->backpackweburl);
1262
            $this->assertEquals($data['backpackapiurl'], $record->backpackapiurl);
1263
            $this->assertEquals($lastmax + 1, $record->sortorder);
1264
            $record = $DB->get_record('badge_backpack', ['userid' => 0]);
1265
            $this->assertNotEmpty($record);
1266
        } else {
1267
            $user = $this->getDataGenerator()->create_user();
1268
            $this->setUser($user);
1269
            $this->expectException('required_capability_exception');
1270
            if ($updatetest) {
1271
                $result = badges_update_site_backpack($backpack, (object) $data);
1272
            } else {
1273
                $result = badges_create_site_backpack((object)$data);
1274
            }
1275
        }
1276
    }
1277
 
1278
    /**
1279
     * Provider for test_badges_(create/update)_site_backpack
1280
     */
1441 ariadna 1281
    public static function badges_create_site_backpack_provider(): array {
1 efrain 1282
        return [
1283
            "Test as admin user - creation test" => [true, true],
1284
            "Test as admin user - update test" => [true, false],
1285
            "Test as normal user - creation test" => [false, true],
1286
            "Test as normal user - update test" => [false, false],
1287
        ];
1288
    }
1289
 
1290
    /**
1291
     * Test the badges_open_badges_backpack_api with different backpacks
1292
     */
11 efrain 1293
    public function test_badges_open_badges_backpack_api(): void {
1 efrain 1294
        $this->resetAfterTest();
1295
 
1296
        $data = [
1297
            'apiversion' => 2,
1298
            'backpackapiurl' => 'https://api.ca.badgr.io/v2',
1299
            'backpackweburl' => 'https://ca.badgr.io',
1300
            'sortorder' => 2,
1301
        ];
1302
 
1303
        // Given a complete set of unique data, a new backpack and auth records should exist in the tables.
1304
        $data['backpackemail'] = 'test@test.com';
1305
        $data['password'] = 'test';
1306
        $backpack1 = badges_save_external_backpack((object) $data);
1307
        $data['backpackweburl'] = 'https://eu.badgr.io';
1308
        $data['backpackapiurl'] = 'https://api.eu.badgr.io/v2';
1309
        $data['apiversion'] = '2.1';
1310
        $data['sortorder'] = 3;
1311
        $backpack2 = badges_save_external_backpack((object) $data);
1312
 
1313
        // Move backpack2 to the first position to set it as primary site backpack.
1314
        $this->move_backpack_to_first_position($backpack2);
1315
 
1316
        // The default response should check the default site backpack api version.
1317
        $this->assertEquals(2.1, badges_open_badges_backpack_api());
1318
        // Check the api version for the other backpack created.
1319
        $this->assertEquals(2, badges_open_badges_backpack_api($backpack1));
1320
        $this->assertEquals(2.1, badges_open_badges_backpack_api($backpack2));
1321
    }
1322
 
1323
    /**
1324
     * Test the badges_get_site_backpack function
1325
     */
11 efrain 1326
    public function test_badges_get_site_backpack(): void {
1 efrain 1327
        $this->resetAfterTest();
1328
        $user = $this->getDataGenerator()->create_user();
1329
        $data = [
1330
            'apiversion' => '2',
1331
            'backpackapiurl' => 'https://api.ca.badgr.io/v2',
1332
            'backpackweburl' => 'https://ca.badgr.io',
1333
        ];
1334
        $backpack1 = badges_save_external_backpack((object) $data);
1335
        $data2 = array_merge($data, [
1336
            'backpackapiurl' => 'https://api.eu.badgr.io/v2',
1337
            'backpackweburl' => 'https://eu.badgr.io',
1338
            'backpackemail' => 'test@test.com',
1339
            'password' => 'test',
1340
        ]);
1341
        $backpack2 = badges_save_external_backpack((object) $data2);
1342
        $data3 = array_merge($data2, [
1343
            'userid' => $user->id,
1344
            'externalbackpackid' => $backpack2,
1345
            'backpackemail' => 'test2@test.com'
1346
        ]);
1347
        // In the following case, the id returned below equals backpack2. So we aren't storing it.
1348
        badges_save_backpack_credentials((object) $data3);
1349
        unset($data3['userid']);
1350
 
1351
        // Get a site back based on the id returned from creation and no user id provided.
1352
        $this->assertEquals($data, array_intersect($data, (array) badges_get_site_backpack($backpack1)));
1353
        $this->assertEquals($data2, array_intersect($data2, (array) badges_get_site_backpack($backpack2)));
1354
        $this->assertEquals($data2, array_intersect($data2, (array) badges_get_site_backpack($backpack2, 0)));
1355
        $this->assertEquals($data3, array_intersect($data3, (array) badges_get_site_backpack($backpack2, $user->id)));
1356
 
1357
        // Non-existent user backpack should return only configuration details and not auth details.
1358
        $userbackpack = badges_get_site_backpack($backpack1, $user->id);
1359
        $this->assertNull($userbackpack->badgebackpack);
1360
        $this->assertNull($userbackpack->password);
1361
        $this->assertNull($userbackpack->backpackemail);
1362
    }
1363
 
1364
    /**
1365
     * Test the badges_get_user_backpack function
1366
     */
11 efrain 1367
    public function test_badges_get_user_backpack(): void {
1 efrain 1368
        $this->resetAfterTest();
1369
        $user = $this->getDataGenerator()->create_user();
1370
        $data = [
1371
            'apiversion' => '2',
1372
            'backpackapiurl' => 'https://api.ca.badgr.io/v2',
1373
            'backpackweburl' => 'https://ca.badgr.io',
1374
        ];
1375
        $backpack1 = badges_save_external_backpack((object) $data);
1376
        $data2 = array_merge($data, [
1377
            'backpackapiurl' => 'https://api.eu.badgr.io/v2',
1378
            'backpackweburl' => 'https://eu.badgr.io',
1379
            'backpackemail' => 'test@test.com',
1380
            'password' => 'test',
1381
        ]);
1382
        $backpack2 = badges_save_external_backpack((object) $data2);
1383
        $data3 = array_merge($data2, [
1384
            'userid' => $user->id,
1385
            'externalbackpackid' => $backpack2,
1386
            'backpackemail' => 'test2@test.com'
1387
        ]);
1388
        // In the following case, the id returned below equals backpack2. So we aren't storing it.
1389
        badges_save_backpack_credentials((object) $data3);
1390
        unset($data3['userid']);
1391
 
1392
        // Currently logged in as admin.
1393
        $this->assertEquals($data2, array_intersect($data2, (array) badges_get_user_backpack()));
1394
        $this->assertEquals($data2, array_intersect($data2, (array) badges_get_user_backpack(0)));
1395
        $this->assertEquals($data3, array_intersect($data3, (array) badges_get_user_backpack($user->id)));
1396
 
1397
        // Non-existent user backpack should return nothing.
1398
        $this->assertFalse(badges_get_user_backpack($backpack1, $user->id));
1399
 
1400
        // Login as user.
1401
        $this->setUser($user);
1402
        $this->assertEquals($data3, array_intersect($data3, (array) badges_get_user_backpack()));
1403
    }
1404
 
1405
    /**
1406
     * Test the badges_get_site_primary_backpack function
1407
     *
1408
     * @param boolean $withauth Testing with authentication or not.
1409
     * @dataProvider badges_get_site_primary_backpack_provider
1410
     */
11 efrain 1411
    public function test_badges_get_site_primary_backpack($withauth): void {
1 efrain 1412
        $data = [
1413
            'apiversion' => '2',
1414
            'backpackapiurl' => 'https://api.ca.badgr.io/v2',
1415
            'backpackweburl' => 'https://ca.badgr.io',
1416
            'sortorder' => '2',
1417
        ];
1418
        if ($withauth) {
1419
            $data = array_merge($data, [
1420
                'backpackemail' => 'test@test.com',
1421
                'password' => 'test',
1422
            ]);
1423
        }
1424
        $backpack = badges_save_external_backpack((object) $data);
1425
 
1426
        // Check the backpack created is not the primary one.
1427
        $sitebackpack = badges_get_site_primary_backpack();
1428
        $this->assertNotEquals($backpack, $sitebackpack->id);
1429
 
1430
        // Move backpack to the first position to set it as primary site backpack.
1431
        $this->move_backpack_to_first_position($backpack);
1432
 
1433
        $sitebackpack = badges_get_site_primary_backpack();
1434
        $this->assertEquals($backpack, $sitebackpack->id);
1435
 
1436
        if ($withauth) {
1437
            $this->assertEquals($data, array_intersect($data, (array) $sitebackpack));
1438
            $this->assertEquals($data['password'], $sitebackpack->password);
1439
            $this->assertEquals($data['backpackemail'], $sitebackpack->backpackemail);
1440
        } else {
1441
            $this->assertNull($sitebackpack->badgebackpack);
1442
            $this->assertNull($sitebackpack->password);
1443
            $this->assertNull($sitebackpack->backpackemail);
1444
        }
1445
    }
1446
 
1447
    /**
1448
     * Test the test_badges_get_site_primary_backpack function.
1449
     *
1450
     * @return array
1451
     */
1441 ariadna 1452
    public static function badges_get_site_primary_backpack_provider(): array {
1 efrain 1453
        return [
1454
            "Test with auth details" => [true],
1455
            "Test without auth details" => [false],
1456
        ];
1457
    }
1458
 
1459
    /**
1460
     * Test badges_change_sortorder_backpacks().
1461
     *
1462
     * @dataProvider badges_change_sortorder_backpacks_provider
1463
     * @covers ::badges_change_sortorder_backpacks
1464
     *
1465
     * @param int $backpacktomove Backpack index to move (from 0 to 5).
1466
     * @param int $direction Direction to move the backpack.
1467
     * @param int|null $expectedsortorder Expected sortorder or null if an exception is expected.
1468
     */
1469
    public function test_badges_change_sortorder_backpacks(int $backpacktomove, int $direction, ?int $expectedsortorder): void {
1470
        global $DB;
1471
 
1472
        $this->resetAfterTest();
1473
        $this->setAdminUser();
1474
 
1475
        // Create 5 more backpacks.
1476
        for ($i = 0; $i < 5; $i++) {
1477
            $data = new \stdClass();
1478
            $data->apiversion = OPEN_BADGES_V2P1;
1479
            $data->backpackapiurl = "https://myurl$i.cat/ob/v2p1";
1480
            $data->backpackweburl = "https://myurl$i.cat";
1481
            badges_create_site_backpack($data);
1482
        }
1483
 
1484
        // Check there are 6 backpacks (1 pre-existing + 5 news).
1485
        $total = $DB->count_records('badge_external_backpack');
1486
        $this->assertEquals(6, $total);
1487
        $backpacks = array_values(badges_get_site_backpacks());
1488
 
1489
        if (is_null($expectedsortorder)) {
1490
            $this->expectException('moodle_exception');
1491
        }
1492
 
1493
        // Move the backpack.
1494
        badges_change_sortorder_backpacks($backpacks[$backpacktomove]->id, $direction);
1495
 
1496
        if (!is_null($expectedsortorder)) {
1497
            $backpack = badges_get_site_backpack($backpacks[$backpacktomove]->id);
1498
            $this->assertEquals($expectedsortorder, $backpack->sortorder);
1499
        }
1500
    }
1501
 
1502
    /**
1503
     * Provider for test_badges_change_sortorder_backpacks.
1504
     *
1505
     * @return array
1506
     */
1441 ariadna 1507
    public static function badges_change_sortorder_backpacks_provider(): array {
1508
        static::load_requirements();
1 efrain 1509
        return [
1510
            "Test up" => [
1511
                'backpacktomove' => 1,
1512
                'direction' => BACKPACK_MOVE_UP,
1513
                'expectedsortorder' => 1,
1514
            ],
1515
            "Test down" => [
1516
                'backpacktomove' => 1,
1517
                'direction' => BACKPACK_MOVE_DOWN,
1518
                'expectedsortorder' => 3,
1519
            ],
1520
            "Test up the very first element" => [
1521
                'backpacktomove' => 0,
1522
                'direction' => BACKPACK_MOVE_UP,
1523
                'expectedsortorder' => 1,
1524
            ],
1525
            "Test down the very last element" => [
1526
                'backpacktomove' => 5,
1527
                'direction' => BACKPACK_MOVE_DOWN,
1528
                'expectedsortorder' => 6,
1529
            ],
1530
            "Test with an invalid direction value" => [
1531
                'backpacktomove' => 1,
1532
                'direction' => 10,
1533
                'expectedsortorder' => null,
1534
            ],
1535
        ];
1536
    }
1537
 
1538
    /**
1539
     * Test the Badgr URL generator function
1540
     *
1541
     * @param mixed $type Type corresponding to the badge entites
1542
     * @param string $expected Expected string result
1543
     * @dataProvider badgr_open_url_generator
1544
     */
11 efrain 1545
    public function test_badges_generate_badgr_open_url($type, $expected): void {
1 efrain 1546
        $data = [
1547
            'apiversion' => '2',
1548
            'backpackapiurl' => 'https://api.ca.badgr.io/v2',
1549
            'backpackweburl' => 'https://ca.badgr.io',
1550
            'backpackemail' => 'test@test.com',
1551
            'password' => 'test',
1552
        ];
1553
        $backpack2 = badges_save_external_backpack((object) $data);
1554
        $backpack = badges_get_site_backpack($backpack2);
1555
        $this->assertEquals($expected, badges_generate_badgr_open_url($backpack, $type, 123455));
1556
    }
1557
 
1558
    /**
1559
     * Data provider for test_badges_generate_badgr_open_url
1560
     * @return array
1561
     */
1441 ariadna 1562
    public static function badgr_open_url_generator(): array {
1563
        static::load_requirements();
1564
 
1 efrain 1565
        return [
1566
            'Badgr Assertion URL test' => [
1567
                OPEN_BADGES_V2_TYPE_ASSERTION, "https://api.ca.badgr.io/public/assertions/123455"
1568
            ],
1569
            'Badgr Issuer URL test' => [
1570
                OPEN_BADGES_V2_TYPE_ISSUER, "https://api.ca.badgr.io/public/issuers/123455"
1571
            ],
1572
            'Badgr Badge URL test' => [
1573
                OPEN_BADGES_V2_TYPE_BADGE, "https://api.ca.badgr.io/public/badges/123455"
1574
            ]
1575
        ];
1576
    }
1577
 
1578
    /**
1579
     * Test badges_external_get_mapping function
1580
     *
1581
     * @param int $internalid The internal id of the mapping
1582
     * @param int $externalid The external / remote ref to the mapping
1583
     * @param mixed $expected The expected result from the function
1584
     * @param string|null $field The field we are passing to the function. Null if we don't want to pass anything.ss
1585
     *
1586
     * @dataProvider badges_external_get_mapping_provider
1587
     */
11 efrain 1588
    public function test_badges_external_get_mapping($internalid, $externalid, $expected, $field = null): void {
1 efrain 1589
        $data = [
1590
            'apiversion' => '2',
1591
            'backpackapiurl' => 'https://api.ca.badgr.io/v2',
1592
            'backpackweburl' => 'https://ca.badgr.io',
1593
            'backpackemail' => 'test@test.com',
1594
            'password' => 'test',
1595
        ];
1596
        $backpack2 = badges_save_external_backpack((object) $data);
1597
        badges_external_create_mapping($backpack2, OPEN_BADGES_V2_TYPE_BADGE, $internalid, $externalid);
1598
        $expected = $expected == "id" ? $backpack2 : $expected;
1599
        if ($field) {
1600
            $this->assertEquals($expected, badges_external_get_mapping($backpack2, OPEN_BADGES_V2_TYPE_BADGE, $internalid, $field));
1601
        } else {
1602
            $this->assertEquals($expected, badges_external_get_mapping($backpack2, OPEN_BADGES_V2_TYPE_BADGE, $internalid));
1603
        }
1604
    }
1605
 
1606
    /**
1607
     * Data provider for badges_external_get_mapping_provider
1608
     *
1609
     * @return array
1610
     */
1441 ariadna 1611
    public static function badges_external_get_mapping_provider(): array {
1 efrain 1612
        return [
1613
            "Get the site backpack value" => [
1614
                1234, 4321, 'id', 'sitebackpackid'
1615
            ],
1616
            "Get the type of the mapping" => [
1617
                1234, 4321, OPEN_BADGES_V2_TYPE_BADGE, 'type'
1618
            ],
1619
            "Get the externalid of the mapping" => [
1620
                1234, 4321, 4321, 'externalid'
1621
            ],
1622
            "Get the externalid of the mapping without providing a param" => [
1623
                1234, 4321, 4321, null
1624
            ],
1625
            "Get the internalid of the mapping" => [
1626
                1234, 4321, 1234, 'internalid'
1627
            ]
1628
        ];
1629
    }
1630
 
1631
    /**
1632
     * Move the backpack to the first position, to set it as primary site backpack.
1633
     *
1634
     * @param int $backpackid The backpack identifier.
1635
     */
1636
    private function move_backpack_to_first_position(int $backpackid): void {
1637
        $backpack = badges_get_site_backpack($backpackid);
1638
        while ($backpack->sortorder > 1) {
1639
            badges_change_sortorder_backpacks($backpackid, BACKPACK_MOVE_UP);
1640
            $backpack = badges_get_site_backpack($backpackid);
1641
        }
1642
    }
1643
 
1644
    /**
1645
     * Testing function test_badge_get_tagged_badges - search tagged badges
1646
     *
1647
     * @covers ::badge_get_tagged_badges
1648
     */
11 efrain 1649
    public function test_badge_get_tagged_badges(): void {
1 efrain 1650
        $this->resetAfterTest();
1651
        $this->setAdminUser();
1652
 
1653
        // Setup test data.
1654
        $badge = new badge($this->coursebadge);
1655
        \core_tag_tag::set_item_tags('core_badges', 'badge', $this->badgeid, $badge->get_context(),
1656
            ['Cats', 'Dogs']);
1657
 
1658
        $tag = \core_tag_tag::get_by_name(0, 'Cats');
1659
 
1660
        $res = badge_get_tagged_badges($tag, false, 0, 0, 1, 0);
1661
        $this->assertStringContainsString("Test badge with 'apostrophe' and other friends (<>&@#)", $res->content);
1662
    }
1663
}