MDL-58454 badges: Open Badges Specification Version 2.0 Changes
[moodle.git] / badges / tests / badgeslib_test.php
CommitLineData
27806552
YB
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
27defined('MOODLE_INTERNAL') || die();
28
29global $CFG;
30require_once($CFG->libdir . '/badgeslib.php');
bef0d6b0 31require_once($CFG->dirroot . '/badges/lib.php');
27806552 32
f007e899 33class core_badges_badgeslib_testcase extends advanced_testcase {
27806552 34 protected $badgeid;
cdc54199
RT
35 protected $course;
36 protected $user;
37 protected $module;
38 protected $coursebadge;
853e506a 39 protected $assertion;
27806552 40
d363a5c2
TT
41 /** @var $assertion2 to define json format for Open badge version 2 */
42 protected $assertion2;
43
27806552 44 protected function setUp() {
cdc54199 45 global $DB, $CFG;
27806552 46 $this->resetAfterTest(true);
7fbe33fc 47 $CFG->enablecompletion = true;
27806552 48 $user = $this->getDataGenerator()->create_user();
27806552
YB
49 $fordb = new stdClass();
50 $fordb->id = null;
d77a6026 51 $fordb->name = "Test badge with 'apostrophe' and other friends (<>&@#)";
27806552
YB
52 $fordb->description = "Testing badges";
53 $fordb->timecreated = time();
54 $fordb->timemodified = time();
55 $fordb->usercreated = $user->id;
56 $fordb->usermodified = $user->id;
27806552
YB
57 $fordb->issuername = "Test issuer";
58 $fordb->issuerurl = "http://issuer-url.domain.co.nz";
853e506a 59 $fordb->issuercontact = "issuer@example.com";
27806552
YB
60 $fordb->expiredate = null;
61 $fordb->expireperiod = null;
62 $fordb->type = BADGE_TYPE_SITE;
d363a5c2
TT
63 $fordb->version = 1;
64 $fordb->language = 'en';
27806552
YB
65 $fordb->courseid = null;
66 $fordb->messagesubject = "Test message subject";
67 $fordb->message = "Test message body";
68 $fordb->attachment = 1;
69 $fordb->notification = 0;
d363a5c2
TT
70 $fordb->imageauthorname = "Image Author 1";
71 $fordb->imageauthoremail = "author@example.com";
72 $fordb->imageauthorurl = "http://author-url.example.com";
73 $fordb->imagecaption = "Test caption image";
27806552
YB
74 $fordb->status = BADGE_STATUS_INACTIVE;
75
76 $this->badgeid = $DB->insert_record('badge', $fordb, true);
cdc54199
RT
77
78 // Create a course with activity and auto completion tracking.
7fbe33fc 79 $this->course = $this->getDataGenerator()->create_course(array('enablecompletion' => true));
cdc54199
RT
80 $this->user = $this->getDataGenerator()->create_user();
81 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
82 $this->assertNotEmpty($studentrole);
83
84 // Get manual enrolment plugin and enrol user.
85 require_once($CFG->dirroot.'/enrol/manual/locallib.php');
86 $manplugin = enrol_get_plugin('manual');
87 $maninstance = $DB->get_record('enrol', array('courseid' => $this->course->id, 'enrol' => 'manual'), '*', MUST_EXIST);
88 $manplugin->enrol_user($maninstance, $this->user->id, $studentrole->id);
89 $this->assertEquals(1, $DB->count_records('user_enrolments'));
cdc54199
RT
90 $completionauto = array('completion' => COMPLETION_TRACKING_AUTOMATIC);
91 $this->module = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id), $completionauto);
92
93 // Build badge and criteria.
94 $fordb->type = BADGE_TYPE_COURSE;
95 $fordb->courseid = $this->course->id;
96 $fordb->status = BADGE_STATUS_ACTIVE;
cdc54199 97 $this->coursebadge = $DB->insert_record('badge', $fordb, true);
d363a5c2
TT
98
99 // Insert Endorsement.
100 $endorsement = new stdClass();
101 $endorsement->badgeid = $this->coursebadge;
102 $endorsement->issuername = "Issuer 123";
103 $endorsement->issueremail = "issuer123@email.com";
104 $endorsement->issuerurl = "https://example.org/issuer-123";
105 $endorsement->dateissued = 1524567747;
106 $endorsement->claimid = "https://example.org/robotics-badge.json";
107 $endorsement->claimcomment = "Test endorser comment";
108 $DB->insert_record('badge_endorsement', $endorsement, true);
109
110 // Insert related badges.
111 $badge = new badge($this->coursebadge);
112 $clonedid = $badge->make_clone();
113 $badgeclone = new badge($clonedid);
114 $badgeclone->status = BADGE_STATUS_ACTIVE;
115 $badgeclone->save();
116
117 $relatebadge = new stdClass();
118 $relatebadge->badgeid = $this->coursebadge;
119 $relatebadge->relatedbadgeid = $clonedid;
120 $relatebadge->relatedid = $DB->insert_record('badge_related', $relatebadge, true);
121
122 // Insert a competency aligment.
123 $competency = new stdClass();
124 $competency->badgeid = $this->coursebadge;
125 $competency->targetname = 'CCSS.ELA-Literacy.RST.11-12.3';
126 $competency->targeturl = 'http://www.corestandards.org/ELA-Literacy/RST/11-12/3';
127 $competency->targetdescription = 'Test target description';
128 $competency->targetframework = 'CCSS.RST.11-12.3';
129 $competency->targetcode = 'CCSS.RST.11-12.3';
130 $DB->insert_record('badge_competencies', $competency, true);
131
853e506a
Y
132 $this->assertion = new stdClass();
133 $this->assertion->badge = '{"uid":"%s","recipient":{"identity":"%s","type":"email","hashed":true,"salt":"%s"},"badge":"%s","verify":{"type":"hosted","url":"%s"},"issuedOn":"%d","evidence":"%s"}';
134 $this->assertion->class = '{"name":"%s","description":"%s","image":"%s","criteria":"%s","issuer":"%s"}';
135 $this->assertion->issuer = '{"name":"%s","url":"%s","email":"%s"}';
d363a5c2
TT
136 // Format JSON-LD for Openbadge specification version 2.0.
137 $this->assertion2 = new stdClass();
138 $this->assertion2->badge = '{"recipient":{"identity":"%s","type":"email","hashed":true,"salt":"%s"},' .
139 '"badge":{"name":"%s","description":"%s","image":{"id":"%s","author":"%s","caption":"%s"},' .
140 '"criteria":{"id":"%s","narrative":"%s"},"issuer":{"name":"%s","url":"%s","email":"%s",' .
141 '"@context":"https:\/\/w3id.org\/openbadges\/v2","id":"%s","type":"Issuer"},' .
142 '"@context":"https:\/\/w3id.org\/openbadges\/v2","id":"%s","type":"BadgeClass","version":"%s",' .
143 '"@language":"%s","related":[{"id":"%s","version":"%s","@language":"%s"}],"endorsement":"%s",' .
144 '"alignment":[{"targetName":"%s","targetUrl":"%s","targetDescription":"%s","targetFramework":"%s",' .
145 '"targetCode":"%s"}]},"verify":{"type":"hosted","url":"%s"},"issuedOn":"%s","evidence":"%s",' .
146 '"@context":"https:\/\/w3id.org\/openbadges\/v2","type":"Assertion","id":"%s"}';
147 $this->assertion2->class = '{"name":"%s","description":"%s","image":{"id":"%s","author":"%s","caption":"%s"},' .
148 '"criteria":{"id":"%s","narrative":"%s"},"issuer":{"name":"%s","url":"%s","email":"%s",' .
149 '"@context":"https:\/\/w3id.org\/openbadges\/v2","id":"%s","type":"Issuer"},' .
150 '"@context":"https:\/\/w3id.org\/openbadges\/v2","id":"%s","type":"BadgeClass","version":"%s",' .
151 '"@language":"%s","related":[{"id":"%s","version":"%s","@language":"%s"}],"endorsement":"%s",' .
152 '"alignment":[{"targetName":"%s","targetUrl":"%s","targetDescription":"%s","targetFramework":"%s",' .
153 '"targetCode":"%s"}]}';
154 $this->assertion2->issuer = '{"name":"%s","url":"%s","email":"%s",' .
155 '"@context":"https:\/\/w3id.org\/openbadges\/v2","id":"%s","type":"Issuer"}';
27806552
YB
156 }
157
158 public function test_create_badge() {
159 $badge = new badge($this->badgeid);
160
161 $this->assertInstanceOf('badge', $badge);
162 $this->assertEquals($this->badgeid, $badge->id);
163 }
164
165 public function test_clone_badge() {
166 $badge = new badge($this->badgeid);
167 $newid = $badge->make_clone();
168 $cloned_badge = new badge($newid);
169
27806552
YB
170 $this->assertEquals($badge->description, $cloned_badge->description);
171 $this->assertEquals($badge->issuercontact, $cloned_badge->issuercontact);
172 $this->assertEquals($badge->issuername, $cloned_badge->issuername);
853e506a 173 $this->assertEquals($badge->issuercontact, $cloned_badge->issuercontact);
27806552
YB
174 $this->assertEquals($badge->issuerurl, $cloned_badge->issuerurl);
175 $this->assertEquals($badge->expiredate, $cloned_badge->expiredate);
176 $this->assertEquals($badge->expireperiod, $cloned_badge->expireperiod);
177 $this->assertEquals($badge->type, $cloned_badge->type);
178 $this->assertEquals($badge->courseid, $cloned_badge->courseid);
179 $this->assertEquals($badge->message, $cloned_badge->message);
180 $this->assertEquals($badge->messagesubject, $cloned_badge->messagesubject);
181 $this->assertEquals($badge->attachment, $cloned_badge->attachment);
182 $this->assertEquals($badge->notification, $cloned_badge->notification);
d363a5c2
TT
183 $this->assertEquals($badge->version, $cloned_badge->version);
184 $this->assertEquals($badge->language, $cloned_badge->language);
185 $this->assertEquals($badge->imagecaption, $cloned_badge->imagecaption);
186 $this->assertEquals($badge->imageauthorname, $cloned_badge->imageauthorname);
187 $this->assertEquals($badge->imageauthoremail, $cloned_badge->imageauthoremail);
188 $this->assertEquals($badge->imageauthorurl, $cloned_badge->imageauthorurl);
189
27806552
YB
190 }
191
192 public function test_badge_status() {
193 $badge = new badge($this->badgeid);
194 $old_status = $badge->status;
195 $badge->set_status(BADGE_STATUS_ACTIVE);
196 $this->assertAttributeNotEquals($old_status, 'status', $badge);
197 $this->assertAttributeEquals(BADGE_STATUS_ACTIVE, 'status', $badge);
198 }
199
200 public function test_delete_badge() {
201 $badge = new badge($this->badgeid);
202 $badge->delete();
203 // We don't actually delete badges. We archive them.
204 $this->assertAttributeEquals(BADGE_STATUS_ARCHIVED, 'status', $badge);
205 }
206
207 public function test_create_badge_criteria() {
208 $badge = new badge($this->badgeid);
209 $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
210 $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL));
211
212 $this->assertCount(1, $badge->get_criteria());
213
214 $criteria_profile = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $badge->id));
215 $params = array('agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address');
216 $criteria_profile->save($params);
217
218 $this->assertCount(2, $badge->get_criteria());
219 }
220
3784d3be
YB
221 public function test_add_badge_criteria_description() {
222 $criteriaoverall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $this->badgeid));
fffeb03f
YB
223 $criteriaoverall->save(array(
224 'agg' => BADGE_CRITERIA_AGGREGATION_ALL,
225 'description' => 'Overall description',
226 'descriptionformat' => FORMAT_HTML
227 ));
3784d3be
YB
228
229 $criteriaprofile = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $this->badgeid));
fffeb03f
YB
230 $params = array(
231 'agg' => BADGE_CRITERIA_AGGREGATION_ALL,
232 'field_address' => 'address',
233 'description' => 'Description',
234 'descriptionformat' => FORMAT_HTML
235 );
3784d3be
YB
236 $criteriaprofile->save($params);
237
238 $badge = new badge($this->badgeid);
239 $this->assertEquals('Overall description', $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->description);
240 $this->assertEquals('Description', $badge->criteria[BADGE_CRITERIA_TYPE_PROFILE]->description);
241 }
242
27806552
YB
243 public function test_delete_badge_criteria() {
244 $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $this->badgeid));
245 $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL));
246 $badge = new badge($this->badgeid);
247
248 $this->assertInstanceOf('award_criteria_overall', $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
249
250 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->delete();
251 $this->assertEmpty($badge->get_criteria());
252 }
253
254 public function test_badge_awards() {
be2b37cf 255 $this->preventResetByRollback(); // Messaging is not compatible with transactions.
27806552
YB
256 $badge = new badge($this->badgeid);
257 $user1 = $this->getDataGenerator()->create_user();
258
259 $badge->issue($user1->id, true);
260 $this->assertTrue($badge->is_issued($user1->id));
261
262 $user2 = $this->getDataGenerator()->create_user();
263 $badge->issue($user2->id, true);
264 $this->assertTrue($badge->is_issued($user2->id));
265
266 $this->assertCount(2, $badge->get_awards());
267 }
268
d237385e
SH
269 /**
270 * Test the {@link badges_get_user_badges()} function in lib/badgeslib.php
271 */
272 public function test_badges_get_user_badges() {
273 global $DB;
274
275 // Messaging is not compatible with transactions.
276 $this->preventResetByRollback();
277
278 $badges = array();
279 $user1 = $this->getDataGenerator()->create_user();
280 $user2 = $this->getDataGenerator()->create_user();
281
282 // Record the current time, we need to be precise about a couple of things.
283 $now = time();
284 // Create 11 badges with which to test.
285 for ($i = 1; $i <= 11; $i++) {
286 // Mock up a badge.
287 $badge = new stdClass();
288 $badge->id = null;
289 $badge->name = "Test badge $i";
290 $badge->description = "Testing badges $i";
291 $badge->timecreated = $now - 12;
292 $badge->timemodified = $now - 12;
293 $badge->usercreated = $user1->id;
294 $badge->usermodified = $user1->id;
295 $badge->issuername = "Test issuer";
296 $badge->issuerurl = "http://issuer-url.domain.co.nz";
297 $badge->issuercontact = "issuer@example.com";
298 $badge->expiredate = null;
299 $badge->expireperiod = null;
300 $badge->type = BADGE_TYPE_SITE;
301 $badge->courseid = null;
302 $badge->messagesubject = "Test message subject for badge $i";
303 $badge->message = "Test message body for badge $i";
304 $badge->attachment = 1;
305 $badge->notification = 0;
306 $badge->status = BADGE_STATUS_INACTIVE;
d363a5c2
TT
307 $badge->version = "Version $i";
308 $badge->language = "en";
309 $badge->imagecaption = "Image caption $i";
310 $badge->imageauthorname = "Image author's name $i";
311 $badge->imageauthoremail = "author$i@example.com";
312 $badge->imageauthorname = "Image author's name $i";
d237385e
SH
313
314 $badgeid = $DB->insert_record('badge', $badge, true);
315 $badges[$badgeid] = new badge($badgeid);
316 $badges[$badgeid]->issue($user2->id, true);
317 // Check it all actually worked.
318 $this->assertCount(1, $badges[$badgeid]->get_awards());
319
320 // Hack the database to adjust the time each badge was issued.
321 // The alternative to this is sleep which is a no-no in unit tests.
322 $DB->set_field('badge_issued', 'dateissued', $now - 11 + $i, array('userid' => $user2->id, 'badgeid' => $badgeid));
323 }
324
325 // Make sure the first user has no badges.
326 $result = badges_get_user_badges($user1->id);
327 $this->assertInternalType('array', $result);
328 $this->assertCount(0, $result);
329
330 // Check that the second user has the expected 11 badges.
331 $result = badges_get_user_badges($user2->id);
332 $this->assertCount(11, $result);
333
334 // Test pagination.
335 // Ordering is by time issued desc, so things will come out with the last awarded badge first.
336 $result = badges_get_user_badges($user2->id, 0, 0, 4);
337 $this->assertCount(4, $result);
338 $lastbadgeissued = reset($result);
339 $this->assertSame('Test badge 11', $lastbadgeissued->name);
340 // Page 2. Expecting 4 results again.
341 $result = badges_get_user_badges($user2->id, 0, 1, 4);
342 $this->assertCount(4, $result);
343 $lastbadgeissued = reset($result);
344 $this->assertSame('Test badge 7', $lastbadgeissued->name);
345 // Page 3. Expecting just three results here.
346 $result = badges_get_user_badges($user2->id, 0, 2, 4);
347 $this->assertCount(3, $result);
348 $lastbadgeissued = reset($result);
349 $this->assertSame('Test badge 3', $lastbadgeissued->name);
350 // Page 4.... there is no page 4.
351 $result = badges_get_user_badges($user2->id, 0, 3, 4);
352 $this->assertCount(0, $result);
353
354 // Test search.
355 $result = badges_get_user_badges($user2->id, 0, 0, 0, 'badge 1');
356 $this->assertCount(3, $result);
357 $lastbadgeissued = reset($result);
358 $this->assertSame('Test badge 11', $lastbadgeissued->name);
359 // The term Totara doesn't appear anywhere in the badges.
360 $result = badges_get_user_badges($user2->id, 0, 0, 0, 'Totara');
361 $this->assertCount(0, $result);
b4846b88
AO
362
363 // Issue a user with a course badge and verify its returned based on if
364 // coursebadges are enabled or disabled.
365 $sitebadgeid = key($badges);
366 $badges[$sitebadgeid]->issue($this->user->id, true);
367
368 $badge = new stdClass();
369 $badge->id = null;
370 $badge->name = "Test course badge";
371 $badge->description = "Testing course badge";
372 $badge->timecreated = $now;
373 $badge->timemodified = $now;
374 $badge->usercreated = $user1->id;
375 $badge->usermodified = $user1->id;
376 $badge->issuername = "Test issuer";
377 $badge->issuerurl = "http://issuer-url.domain.co.nz";
378 $badge->issuercontact = "issuer@example.com";
379 $badge->expiredate = null;
380 $badge->expireperiod = null;
381 $badge->type = BADGE_TYPE_COURSE;
382 $badge->courseid = $this->course->id;
383 $badge->messagesubject = "Test message subject for course badge";
384 $badge->message = "Test message body for course badge";
385 $badge->attachment = 1;
386 $badge->notification = 0;
387 $badge->status = BADGE_STATUS_ACTIVE;
d363a5c2
TT
388 $badge->version = "Version $i";
389 $badge->language = "en";
390 $badge->imagecaption = "Image caption";
391 $badge->imageauthorname = "Image author's name";
392 $badge->imageauthoremail = "author@example.com";
393 $badge->imageauthorname = "Image author's name";
b4846b88
AO
394
395 $badgeid = $DB->insert_record('badge', $badge, true);
396 $badges[$badgeid] = new badge($badgeid);
397 $badges[$badgeid]->issue($this->user->id, true);
398
399 // With coursebadges off, we should only get the site badge.
400 set_config('badges_allowcoursebadges', false);
401 $result = badges_get_user_badges($this->user->id);
402 $this->assertCount(1, $result);
403
404 // With it on, we should get both.
405 set_config('badges_allowcoursebadges', true);
406 $result = badges_get_user_badges($this->user->id);
407 $this->assertCount(2, $result);
408
d237385e
SH
409 }
410
27806552
YB
411 public function data_for_message_from_template() {
412 return array(
413 array(
414 'This is a message with no variables',
415 array(), // no params
416 'This is a message with no variables'
417 ),
418 array(
419 'This is a message with %amissing% variables',
420 array(), // no params
421 'This is a message with %amissing% variables'
422 ),
423 array(
424 'This is a message with %one% variable',
425 array('one' => 'a single'),
426 'This is a message with a single variable'
427 ),
428 array(
429 'This is a message with %one% %two% %three% variables',
430 array('one' => 'more', 'two' => 'than', 'three' => 'one'),
431 'This is a message with more than one variables'
432 ),
433 array(
434 'This is a message with %three% %two% %one%',
435 array('one' => 'variables', 'two' => 'ordered', 'three' => 'randomly'),
436 'This is a message with randomly ordered variables'
437 ),
438 array(
439 'This is a message with %repeated% %one% %repeated% of variables',
440 array('one' => 'and', 'repeated' => 'lots'),
441 'This is a message with lots and lots of variables'
442 ),
443 );
444 }
445
446 /**
447 * @dataProvider data_for_message_from_template
448 */
449 public function test_badge_message_from_template($message, $params, $result) {
450 $this->assertEquals(badge_message_from_template($message, $params), $result);
451 }
452
137d94f3
RT
453 /**
454 * Test badges observer when course module completion event id fired.
137d94f3 455 */
cdc54199 456 public function test_badges_observer_course_module_criteria_review() {
be2b37cf 457 $this->preventResetByRollback(); // Messaging is not compatible with transactions.
cdc54199
RT
458 $badge = new badge($this->coursebadge);
459 $this->assertFalse($badge->is_issued($this->user->id));
137d94f3
RT
460
461 $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
462 $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
463 $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_ACTIVITY, 'badgeid' => $badge->id));
74b63eae 464 $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'module_'.$this->module->cmid => $this->module->cmid));
137d94f3 465
4f2424ca
MG
466 // Assert the badge will not be issued to the user as is.
467 $badge = new badge($this->coursebadge);
468 $badge->review_all_criteria();
469 $this->assertFalse($badge->is_issued($this->user->id));
470
137d94f3 471 // Set completion for forum activity.
cdc54199 472 $c = new completion_info($this->course);
137d94f3
RT
473 $activities = $c->get_activities();
474 $this->assertEquals(1, count($activities));
cdc54199
RT
475 $this->assertTrue(isset($activities[$this->module->cmid]));
476 $this->assertEquals($activities[$this->module->cmid]->name, $this->module->name);
137d94f3 477
cdc54199 478 $current = $c->get_data($activities[$this->module->cmid], false, $this->user->id);
137d94f3
RT
479 $current->completionstate = COMPLETION_COMPLETE;
480 $current->timemodified = time();
f007e899 481 $sink = $this->redirectEmails();
cdc54199 482 $c->internal_set_data($activities[$this->module->cmid], $current);
f007e899
PS
483 $this->assertCount(1, $sink->get_messages());
484 $sink->close();
137d94f3
RT
485
486 // Check if badge is awarded.
487 $this->assertDebuggingCalled('Error baking badge image!');
cdc54199 488 $this->assertTrue($badge->is_issued($this->user->id));
137d94f3 489 }
1cb1e5fe
RT
490
491 /**
492 * Test badges observer when course_completed event is fired.
493 */
494 public function test_badges_observer_course_criteria_review() {
be2b37cf 495 $this->preventResetByRollback(); // Messaging is not compatible with transactions.
1cb1e5fe
RT
496 $badge = new badge($this->coursebadge);
497 $this->assertFalse($badge->is_issued($this->user->id));
498
499 $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
500 $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
501 $criteria_overall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_COURSE, 'badgeid' => $badge->id));
502 $criteria_overall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'course_'.$this->course->id => $this->course->id));
503
504 $ccompletion = new completion_completion(array('course' => $this->course->id, 'userid' => $this->user->id));
505
4f2424ca
MG
506 // Assert the badge will not be issued to the user as is.
507 $badge = new badge($this->coursebadge);
508 $badge->review_all_criteria();
509 $this->assertFalse($badge->is_issued($this->user->id));
510
1cb1e5fe 511 // Mark course as complete.
f007e899 512 $sink = $this->redirectEmails();
1cb1e5fe 513 $ccompletion->mark_complete();
f007e899
PS
514 $this->assertCount(1, $sink->get_messages());
515 $sink->close();
1cb1e5fe
RT
516
517 // Check if badge is awarded.
518 $this->assertDebuggingCalled('Error baking badge image!');
519 $this->assertTrue($badge->is_issued($this->user->id));
520 }
bb78e249
RT
521
522 /**
523 * Test badges observer when user_updated event is fired.
524 */
525 public function test_badges_observer_profile_criteria_review() {
4f2424ca
MG
526 global $CFG, $DB;
527 require_once($CFG->dirroot.'/user/profile/lib.php');
528
529 // Add a custom field of textarea type.
530 $customprofileid = $DB->insert_record('user_info_field', array(
531 'shortname' => 'newfield', 'name' => 'Description of new field', 'categoryid' => 1,
532 'datatype' => 'textarea'));
533
be2b37cf 534 $this->preventResetByRollback(); // Messaging is not compatible with transactions.
bb78e249 535 $badge = new badge($this->coursebadge);
bb78e249
RT
536
537 $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
538 $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
539 $criteria_overall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $badge->id));
4f2424ca
MG
540 $criteria_overall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address', 'field_aim' => 'aim',
541 'field_' . $customprofileid => $customprofileid));
542
543 // Assert the badge will not be issued to the user as is.
544 $badge = new badge($this->coursebadge);
545 $badge->review_all_criteria();
546 $this->assertFalse($badge->is_issued($this->user->id));
bb78e249 547
4f2424ca 548 // Set the required fields and make sure the badge got issued.
bb78e249 549 $this->user->address = 'Test address';
c8d2f392 550 $this->user->aim = '999999999';
f007e899 551 $sink = $this->redirectEmails();
4f2424ca 552 profile_save_data((object)array('id' => $this->user->id, 'profile_field_newfield' => 'X'));
bb78e249 553 user_update_user($this->user, false);
f007e899
PS
554 $this->assertCount(1, $sink->get_messages());
555 $sink->close();
bb78e249
RT
556 // Check if badge is awarded.
557 $this->assertDebuggingCalled('Error baking badge image!');
558 $this->assertTrue($badge->is_issued($this->user->id));
559 }
853e506a 560
75653a30
SB
561 /**
562 * Test badges observer when cohort_member_added event is fired.
563 */
564 public function test_badges_observer_cohort_criteria_review() {
565 global $CFG;
566
567 require_once("$CFG->dirroot/cohort/lib.php");
568
569 $cohort = $this->getDataGenerator()->create_cohort();
570
571 $this->preventResetByRollback(); // Messaging is not compatible with transactions.
572 $badge = new badge($this->badgeid);
573 $this->assertFalse($badge->is_issued($this->user->id));
574
575 // Set up the badge criteria.
576 $criteriaoverall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
577 $criteriaoverall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
578 $criteriaoverall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_COHORT, 'badgeid' => $badge->id));
579 $criteriaoverall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'cohort_cohorts' => array('0' => $cohort->id)));
580
581 // Make the badge active.
582 $badge->set_status(BADGE_STATUS_ACTIVE);
583
584 // Add the user to the cohort.
585 cohort_add_member($cohort->id, $this->user->id);
586
587 // Verify that the badge was awarded.
588 $this->assertDebuggingCalled();
589 $this->assertTrue($badge->is_issued($this->user->id));
590
591 }
592
853e506a
Y
593 /**
594 * Test badges assertion generated when a badge is issued.
595 */
596 public function test_badges_assertion() {
be2b37cf 597 $this->preventResetByRollback(); // Messaging is not compatible with transactions.
853e506a
Y
598 $badge = new badge($this->coursebadge);
599 $this->assertFalse($badge->is_issued($this->user->id));
600
601 $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
602 $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
603 $criteria_overall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $badge->id));
604 $criteria_overall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address'));
605
606 $this->user->address = 'Test address';
f007e899 607 $sink = $this->redirectEmails();
853e506a 608 user_update_user($this->user, false);
f007e899
PS
609 $this->assertCount(1, $sink->get_messages());
610 $sink->close();
853e506a
Y
611 // Check if badge is awarded.
612 $this->assertDebuggingCalled('Error baking badge image!');
613 $awards = $badge->get_awards();
614 $this->assertCount(1, $awards);
615
616 // Get assertion.
617 $award = reset($awards);
618 $assertion = new core_badges_assertion($award->uniquehash);
619 $testassertion = $this->assertion;
620
621 // Make sure JSON strings have the same structure.
622 $this->assertStringMatchesFormat($testassertion->badge, json_encode($assertion->get_badge_assertion()));
623 $this->assertStringMatchesFormat($testassertion->class, json_encode($assertion->get_badge_class()));
624 $this->assertStringMatchesFormat($testassertion->issuer, json_encode($assertion->get_issuer()));
d363a5c2
TT
625
626 // Test Openbadge specification version 2.
627 // Get assertion version 2.
628 $award = reset($awards);
629 $assertion2 = new core_badges_assertion($award->uniquehash, 2);
630 $testassertion2 = $this->assertion2;
631
632 // Make sure JSON strings have the same structure.
633 $this->assertStringMatchesFormat($testassertion2->badge, json_encode($assertion2->get_badge_assertion()));
634 $this->assertStringMatchesFormat($testassertion2->class, json_encode($assertion2->get_badge_class()));
635 $this->assertStringMatchesFormat($testassertion2->issuer, json_encode($assertion2->get_issuer()));
853e506a 636 }
bef0d6b0
AA
637
638 /**
be5e0110 639 * Tests the core_badges_myprofile_navigation() function.
bef0d6b0
AA
640 */
641 public function test_core_badges_myprofile_navigation() {
be5e0110
MN
642 // Set up the test.
643 $tree = new \core_user\output\myprofile\tree();
bef0d6b0 644 $this->setAdminUser();
bef0d6b0 645 $badge = new badge($this->badgeid);
be5e0110
MN
646 $badge->issue($this->user->id, true);
647 $iscurrentuser = true;
bef0d6b0 648 $course = null;
bef0d6b0
AA
649
650 // Enable badges.
651 set_config('enablebadges', true);
bef0d6b0 652
be5e0110
MN
653 // Check the node tree is correct.
654 core_badges_myprofile_navigation($tree, $this->user, $iscurrentuser, $course);
655 $reflector = new ReflectionObject($tree);
656 $nodes = $reflector->getProperty('nodes');
657 $nodes->setAccessible(true);
658 $this->assertArrayHasKey('localbadges', $nodes->getValue($tree));
659 }
660
661 /**
662 * Tests the core_badges_myprofile_navigation() function with badges disabled..
663 */
664 public function test_core_badges_myprofile_navigation_badges_disabled() {
665 // Set up the test.
666 $tree = new \core_user\output\myprofile\tree();
667 $this->setAdminUser();
668 $badge = new badge($this->badgeid);
669 $badge->issue($this->user->id, true);
670 $iscurrentuser = false;
671 $course = null;
672
673 // Disable badges.
674 set_config('enablebadges', false);
bef0d6b0 675
be5e0110
MN
676 // Check the node tree is correct.
677 core_badges_myprofile_navigation($tree, $this->user, $iscurrentuser, $course);
678 $reflector = new ReflectionObject($tree);
679 $nodes = $reflector->getProperty('nodes');
680 $nodes->setAccessible(true);
681 $this->assertArrayNotHasKey('localbadges', $nodes->getValue($tree));
682 }
683
684 /**
685 * Tests the core_badges_myprofile_navigation() function with a course badge.
686 */
687 public function test_core_badges_myprofile_navigation_with_course_badge() {
688 // Set up the test.
689 $tree = new \core_user\output\myprofile\tree();
690 $this->setAdminUser();
bef0d6b0 691 $badge = new badge($this->coursebadge);
be5e0110 692 $badge->issue($this->user->id, true);
bef0d6b0 693 $iscurrentuser = false;
be5e0110
MN
694
695 // Check the node tree is correct.
696 core_badges_myprofile_navigation($tree, $this->user, $iscurrentuser, $this->course);
697 $reflector = new ReflectionObject($tree);
698 $nodes = $reflector->getProperty('nodes');
699 $nodes->setAccessible(true);
700 $this->assertArrayHasKey('localbadges', $nodes->getValue($tree));
bef0d6b0 701 }
d363a5c2
TT
702
703 /**
704 * Test insert and update endorsement with a site badge.
705 */
706 public function test_badge_endorsement() {
707 $badge = new badge($this->badgeid);
708
709 // Insert Endorsement.
710 $endorsement = new stdClass();
711 $endorsement->badgeid = $this->badgeid;
712 $endorsement->issuername = "Issuer 123";
713 $endorsement->issueremail = "issuer123@email.com";
714 $endorsement->issuerurl = "https://example.org/issuer-123";
715 $endorsement->dateissued = 1524567747;
716 $endorsement->claimid = "https://example.org/robotics-badge.json";
717 $endorsement->claimcomment = "Test endorser comment";
718
719 $badge->save_endorsement($endorsement);
720 $endorsement1 = $badge->get_endorsement();
721 $this->assertEquals($endorsement->badgeid, $endorsement1->badgeid);
722 $this->assertEquals($endorsement->issuername, $endorsement1->issuername);
723 $this->assertEquals($endorsement->issueremail, $endorsement1->issueremail);
724 $this->assertEquals($endorsement->issuerurl, $endorsement1->issuerurl);
725 $this->assertEquals($endorsement->dateissued, $endorsement1->dateissued);
726 $this->assertEquals($endorsement->claimid, $endorsement1->claimid);
727 $this->assertEquals($endorsement->claimcomment, $endorsement1->claimcomment);
728
729 // Update Endorsement.
730 $endorsement1->issuername = "Issuer update";
731 $badge->save_endorsement($endorsement1);
732 $endorsement2 = $badge->get_endorsement();
733 $this->assertEquals($endorsement1->id, $endorsement2->id);
734 $this->assertEquals($endorsement1->issuername, $endorsement2->issuername);
735 }
736
737 /**
738 * Test insert and delete related badge with a site badge.
739 */
740 public function test_badge_related() {
741 $badge = new badge($this->badgeid);
742 $newid1 = $badge->make_clone();
743 $newid2 = $badge->make_clone();
744 $newid3 = $badge->make_clone();
745
746 // Insert an related badge.
747 $badge->add_related_badges([$newid1, $newid2, $newid3]);
748 $this->assertCount(3, $badge->get_related_badges());
749
750 // Only get related is active.
751 $clonedbage1 = new badge($newid1);
752 $clonedbage1->status = BADGE_STATUS_ACTIVE;
753 $clonedbage1->save();
754 $this->assertCount(1, $badge->get_related_badges(true));
755
756 // Delete an related badge.
757 $badge->delete_related_badge($newid2);
758 $this->assertCount(2, $badge->get_related_badges());
759 }
760
761 /**
762 * Test insert, update, delete competencies alignment with a site badge.
763 */
764 public function test_competencies_alignment() {
765 $badge = new badge($this->badgeid);
766
767 // Insert a competency alignment.
768 $competency1 = new stdClass();
769 $competency1->badgeid = $this->badgeid;
770 $competency1->targetname = 'CCSS.ELA-Literacy.RST.11-12.3';
771 $competency1->targeturl = 'http://www.corestandards.org/ELA-Literacy/RST/11-12/3';
772 $competency1->targetdescription = 'Test target description';
773 $competency1->targetframework = 'CCSS.RST.11-12.3';
774 $competency1->targetcode = 'CCSS.RST.11-12.3';
775 $competency2 = clone $competency1;
776 $newid1 = $badge->save_alignment($competency1);
777 $newid2 = $badge->save_alignment($competency2);
778 $competencies1 = $badge->get_alignment();
779 $this->assertCount(2, $competencies1);
780
781 $this->assertEquals($competency1->badgeid, $competencies1[$newid1]->badgeid);
782 $this->assertEquals($competency1->targetname, $competencies1[$newid1]->targetname);
783 $this->assertEquals($competency1->targeturl, $competencies1[$newid1]->targeturl);
784 $this->assertEquals($competency1->targetdescription, $competencies1[$newid1]->targetdescription);
785 $this->assertEquals($competency1->targetframework, $competencies1[$newid1]->targetframework);
786 $this->assertEquals($competency1->targetcode, $competencies1[$newid1]->targetcode);
787
788 // Update competency aligment.
789 $competencies1[$newid1]->targetname = 'CCSS.ELA-Literacy.RST.11-12.3 update';
790 $badge->save_alignment($competencies1[$newid1], $competencies1[$newid1]->id);
791 $competencies2 = $badge->get_alignment();
792 $this->assertEquals($competencies1[$newid1]->id, $competencies2[$newid1]->id);
793 $this->assertEquals($competencies1[$newid1]->targetname, $competencies2[$newid1]->targetname);
794
795 // Delete competency alignment.
796 $badge->delete_alignment($competencies1[$newid2]->id);
797 $this->assertCount(1, $badge->get_alignment());
798 }
27806552 799}