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