From c38eb4e6e61987fd7bc7f09419fd51fcdad20bea Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 8 Jan 2015 17:41:51 +0000 Subject: [PATCH] MDL-48474 qtype_shortanswer: answers were not being trimmed. This fix is based on Oleg Sychev's suggestion. Thanks. --- question/type/shortanswer/questiontype.php | 6 ++++ .../shortanswer/tests/questiontype_test.php | 28 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/question/type/shortanswer/questiontype.php b/question/type/shortanswer/questiontype.php index fab260a97cb..c98ec743e95 100644 --- a/question/type/shortanswer/questiontype.php +++ b/question/type/shortanswer/questiontype.php @@ -78,6 +78,12 @@ class qtype_shortanswer extends question_type { $this->save_hints($question); } + protected function fill_answer_fields($answer, $questiondata, $key, $context) { + $answer = parent::fill_answer_fields($answer, $questiondata, $key, $context); + $answer->answer = trim($answer->answer); + return $answer; + } + protected function initialise_question_instance(question_definition $question, $questiondata) { parent::initialise_question_instance($question, $questiondata); $this->initialise_question_answers($question, $questiondata); diff --git a/question/type/shortanswer/tests/questiontype_test.php b/question/type/shortanswer/tests/questiontype_test.php index 91d2bcd420c..2bfa9a90a82 100644 --- a/question/type/shortanswer/tests/questiontype_test.php +++ b/question/type/shortanswer/tests/questiontype_test.php @@ -141,4 +141,32 @@ class qtype_shortanswer_test extends advanced_testcase { } } } + + public function test_question_saving_trims_answers() { + $this->resetAfterTest(true); + $this->setAdminUser(); + + $questiondata = test_question_maker::get_question_data('shortanswer'); + $formdata = test_question_maker::get_question_form_data('shortanswer'); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_question'); + $cat = $generator->create_question_category(array()); + + $formdata->category = "{$cat->id},{$cat->contextid}"; + $formdata->answer[0] = ' frog '; + qtype_shortanswer_edit_form::mock_submit((array)$formdata); + + $form = qtype_shortanswer_test_helper::get_question_editing_form($cat, $questiondata); + + $this->assertTrue($form->is_validated()); + + $fromform = $form->get_data(); + + $returnedfromsave = $this->qtype->save_question($questiondata, $fromform); + $actualquestionsdata = question_load_questions(array($returnedfromsave->id)); + $actualquestiondata = end($actualquestionsdata); + + $firstsavedanswer = reset($questiondata->options->answers); + $this->assertEquals('frog', $firstsavedanswer->answer); + } }