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