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