MDL-62660 tool_dataprivacy: Add method for unit tests to run adhoc tasks

This commit is contained in:
Andrew Nicols
2018-08-21 09:52:59 +08:00
committed by Jun Pataleta
parent 8987e225da
commit e29b668d7b
+58
View File
@@ -663,4 +663,62 @@ abstract class advanced_testcase extends base_testcase {
usleep(50000);
}
}
/**
* Run adhoc tasks, optionally matching the specified classname.
*
* @param string $matchclass The name of the class to match on.
* @param int $matchuserid The userid to match.
*/
protected function runAdhocTasks($matchclass = '', $matchuserid = null) {
global $CFG, $DB;
require_once($CFG->libdir.'/cronlib.php');
$params = [];
if (!empty($matchclass)) {
if (strpos($matchclass, '\\') !== 0) {
$matchclass = '\\' . $matchclass;
}
$params['classname'] = $matchclass;
}
if (!empty($matchuserid)) {
$params['userid'] = $matchuserid;
}
$lock = $this->createMock(\core\lock\lock::class);
$cronlock = $this->createMock(\core\lock\lock::class);
$tasks = $DB->get_recordset('task_adhoc', $params);
foreach ($tasks as $record) {
// Note: This is for cron only.
// We do not lock the tasks.
$task = \core\task\manager::adhoc_task_from_record($record);
$user = null;
if ($userid = $task->get_userid()) {
// This task has a userid specified.
$user = \core_user::get_user($userid);
// User found. Check that they are suitable.
\core_user::require_active_user($user, true, true);
}
$task->set_lock($lock);
if (!$task->is_blocking()) {
$cronlock->release();
} else {
$task->set_cron_lock($cronlock);
}
cron_prepare_core_renderer();
$this->setUser($user);
$task->execute();
\core\task\manager::adhoc_task_complete($task);
unset($task);
}
$tasks->close();
}
}