MDL-66815 behat: question category generator must find right parent id

This is implemented in a bit of a hacky way, because the only other
alternative would be a large rewrite of the whole class, which is
not feasible for me right now. Note that many other types of thing
that can be generated suffer from the same issue. (E.g. if you ever
wanted to generate two groups with the same name in two different
courses and then add group memebers.)

It is worth doing a special-case fix for question categories, because
way Moodle works, it is inevitable that we end up with many categories
called 'top' in the database.
This commit is contained in:
Tim Hunt
2019-10-01 16:43:25 +01:00
parent 9528b1ff5b
commit 6e73157a3c
+24
View File
@@ -667,7 +667,31 @@ class behat_data_generators extends behat_base {
* @param array $data the row of data from the behat script.
*/
protected function process_question_category($data) {
global $DB;
$context = $this->get_context($data['contextlevel'], $data['reference']);
// The way this class works, we have already looked up the given parent category
// name and found a matching category. However, it is possible, particularly
// for the 'top' category, for there to be several categories with the
// same name. So far one will have been picked at random, but we need
// the one from the right context. So, if we have the wrong category, try again.
// (Just fixing it here, rather than getting it right first time, is a bit
// of a bodge, but in general this class assumes that names are unique,
// and normally they are, so this was the easiest fix.)
if (!empty($data['parent'])) {
$foundparent = $DB->get_record('question_categories', ['id' => $data['parent']], '*', MUST_EXIST);
if ($foundparent->contextid != $context->id) {
$rightparentid = $DB->get_field('question_categories', 'id',
['contextid' => $context->id, 'name' => $foundparent->name]);
if (!$rightparentid) {
throw new Exception('The specified question category with name "' . $foundparent->name .
'" does not exist in context "' . $context->get_context_name() . '"."');
}
$data['parent'] = $rightparentid;
}
}
$data['contextid'] = $context->id;
$this->datagenerator->get_plugin_generator('core_question')->create_question_category($data);
}