Proyectos de Subversion Moodle

Rev

Ir a la última revisión | | Ultima modificación | Ver Log |

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