From 7e099a70b48313e92178522c8299f63b0224117a Mon Sep 17 00:00:00 2001 From: Christian Hartmann Date: Tue, 24 Nov 2026 19:53:41 +0100 Subject: [PATCH] fix: unify checks for deleted questions and don't load submissions to deleted questions Signed-off-by: Christian Hartmann only file questions take uploads Signed-off-by: Christian Hartmann test(question): expect the status of each endpoint for deleted questions With deleted questions filtered in QuestionMapper::findById(), each endpoint answers a deleted question like an unknown one: deleteOption with 400, as it always did for an unknown question, and the others with 404, so the expected exception is set per data set. testUploadFiles now uploads for a file question, as uploads for other question types are rejected, and a new test covers both rejections: a short question (400) and a deleted file question (404). Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger fix(api): document the rejected question type of an upload as @throws The tag was spelled @htrows, so the OpenAPI extractor took the line for part of the endpoint description instead of a documented response. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger fix(submission): leave answers to deleted questions out of the search The results list and the export no longer show answers to deleted questions, but the search still matched them, so a search for a word that only appears in such an answer returned the submission without any visible match. The search now joins the questions and only matches answers to questions that are not deleted, for the list and the count alike. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger perf(submission): look up the active questions of answers by key Each answer was checked with in_array against all question ids of the form, which grows with answers times questions on every results load and export. The ids are now keys of an array, and the export reuses the id list it builds for the options anyway. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger fix(api): answer a missing option or question of deleteOption with 404 deleteOption documents "Could not find question or option" as a 404, like updateOption, but threw a 400. With deleted questions filtered in QuestionMapper::findById(), a deleted question would also have changed from 404 to 400 there; now all option and question endpoints answer a deleted or unknown question with 404. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger refactor(question): always skip deleted questions in findById No caller loads a deleted question by id, so the loadDeleted option goes, and an integration test checks against the database that findById finds an active question and skips a deleted one, which every endpoint now relies on. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger refactor(submission): build the lookup of active questions in one place getSubmissionsData built the same id lookup as the helper next to it. The helper now takes the questions, so all three callers share it, and the comments that repeated the code are gone. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger refactor(submission): take the questions table of the search from its mapper The search joined the answers table through its mapper but the questions table by a literal name. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger test(question): drop the unused deleted questions of the rejection tests findById() is mocked to throw in these tests, so the question objects with order 0 they built were never read. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger docs(api): describe the responses for deleted questions and non-file uploads Reordering with a deleted question and deleting an option of a deleted question now answer with Not Found, an upload for a question that is not a file question with Bad Request, and submissions, search and exports leave out answers to deleted questions. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger docs(question): state that findById does not find deleted questions Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger refactor(submission): require the active questions when reading answers The only caller of getAnswers always passes them, so the optional null case never ran. The confirmation email test uses the imported DoesNotExistException like the rest of the file. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger test(question): reject deleted and unknown questions on every endpoint The controller unit tests mock findById(), where a deleted and an unknown question look the same. Against the database, the API now gets a deleted question (deleted through the API first) and an id that does not exist on every question and option endpoint and on the upload, and expects 404 for both; an upload for a short question gets 400. The mapper test covers an unknown id next to an active and a deleted question. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger Signed-off-by: Christian Hartmann Signed-off-by: Andy Scherzinger --- docs/API_v3.md | 6 +- lib/Controller/ApiController.php | 19 ++- lib/Db/QuestionMapper.php | 6 +- lib/Db/SubmissionMapper.php | 60 ++++---- lib/Service/ConfirmationEmailService.php | 1 - lib/Service/SubmissionService.php | 23 ++- openapi.json | 2 +- tests/Integration/Api/ApiV3Test.php | 48 +++++++ tests/Integration/DB/QuestionMapperTest.php | 93 ++++++++++++ tests/Integration/DB/SubmissionMapperTest.php | 26 +++- tests/Unit/Controller/ApiControllerTest.php | 134 +++++++++++++++++- .../Service/ConfirmationEmailServiceTest.php | 8 +- tests/Unit/Service/SubmissionServiceTest.php | 30 ++++ 13 files changed, 404 insertions(+), 52 deletions(-) create mode 100644 tests/Integration/DB/QuestionMapperTest.php diff --git a/docs/API_v3.md b/docs/API_v3.md index 356bfef22c..d77fe7ff73 100644 --- a/docs/API_v3.md +++ b/docs/API_v3.md @@ -466,6 +466,7 @@ Reorders all Questions of a single form | _newOrder_ | Array | Array of **all** Question-IDs, ordered in the desired order | - Restrictions: The Array **must** contain all Question-IDs corresponding to the specified form and **must not** contain any duplicates. - Response: Array of questionIDs and their corresponding order. + An id of a deleted question gets a **Not Found** response. ``` "data": { @@ -583,6 +584,7 @@ Update a single or all properties of an option-object | _questionId_ | Integer | ID of the question, the new option will belong to | | _optionId_ | Integer | ID of the option to delete | - Response: **Status-Code OK**, as well as the id of the deleted option. + An option or question that does not exist, and a deleted question, get a **Not Found** response. ``` "data": 7 @@ -688,6 +690,7 @@ Get all Submissions to a Form | _limit_ | Integer | How many items to get | | _offset_ | Integer | How many items to skip for a pagination | - Response: An Array of all submissions, sorted as newest first, as well as an array of the corresponding questions. + Answers to deleted questions are left out, and the search does not match them. ``` "data": { @@ -791,7 +794,7 @@ Returns all submissions to the form in form of a csv-file. |--------------|---------|-------------| | _formId_ | Integer | Id of the form to get the submissions for | | _fileFormat_ | String | `csv|ods|xlsx` | -- Response: A Data Download Response containing the headers `Content-Disposition: attachment; filename="Form 1 (responses).csv"` and `Content-Type: text/csv;charset=UTF-8`. The actual data contains all submissions to the referred form, formatted as comma separated and escaped csv. For file format `ods` or `xlsx` the Download Response contains an Open Document Spreadsheet or an Office Open XML Spreadsheet file. +- Response: A Data Download Response containing the headers `Content-Disposition: attachment; filename="Form 1 (responses).csv"` and `Content-Type: text/csv;charset=UTF-8`. The actual data contains all submissions to the referred form, without answers to deleted questions, formatted as comma separated and escaped csv. For file format `ods` or `xlsx` the Download Response contains an Open Document Spreadsheet or an Office Open XML Spreadsheet file. ``` "User display name","Timestamp","Question 1","Question 2" @@ -853,6 +856,7 @@ Upload a file to a file question before form submission. Each uploaded file is s | _files_ | Array of files | Files to upload | | _shareHash_ | String | optional, only necessary for uploads on a public share link | - Response: **Status-Code OK**, as well as a list of uploaded files. + An upload for a question that is not a file question gets a **Bad Request** response, and a deleted question gets a **Not Found** response. ``` "data": [ diff --git a/lib/Controller/ApiController.php b/lib/Controller/ApiController.php index e6d9176669..fdbdcb8974 100644 --- a/lib/Controller/ApiController.php +++ b/lib/Controller/ApiController.php @@ -795,7 +795,6 @@ public function deleteQuestion(int $formId, int $questionId): DataResponse { * @throws OCSBadRequestException The given array contains duplicates * @throws OCSBadRequestException The length of the given array does not match the number of stored questions * @throws OCSBadRequestException Question doesn't belong to given Form - * @throws OCSBadRequestException One question has already been marked as deleted * @throws OCSForbiddenException This form is archived and can not be modified * @throws OCSForbiddenException User has no permissions to get this form * @throws OCSNotFoundException Could not find form @@ -856,16 +855,8 @@ public function reorderQuestions(int $formId, array $newOrder): DataResponse { throw new OCSBadRequestException('Question doesn\'t belong to given Form'); } - // Abort if a question is already marked as deleted (order==0) - $oldOrder = $questions[$arrayKey]->getOrder(); - if ($oldOrder === 0) { - $this->logger->debug('This question has already been marked as deleted: Id: {questionId}', [ - 'questionId' => $questions[$arrayKey]->getId() - ]); - throw new OCSBadRequestException('One question has already been marked as deleted'); - } - // Only set order, if it changed. + $oldOrder = $questions[$arrayKey]->getOrder(); if ($oldOrder !== $arrayKey + 1) { // Set Order. ArrayKey counts from zero, order counts from 1. $questions[$arrayKey]->setOrder($arrayKey + 1); @@ -1083,7 +1074,7 @@ public function deleteOption(int $formId, int $questionId, int $optionId): DataR $question = $this->questionMapper->findById($questionId); } catch (IMapperException) { $this->logger->debug('Could not find option or question'); - throw new OCSBadRequestException('Could not find option or question'); + throw new OCSNotFoundException('Could not find option or question'); } if ($option->getQuestionId() !== $questionId || $question->getFormId() !== $formId) { @@ -1659,6 +1650,7 @@ public function exportSubmissionsToCloud(int $formId, string $path, string $file * @return DataResponse, array{}> * @throws OCSBadRequestException No files provided * @throws OCSBadRequestException Question doesn't belong to the given form + * @throws OCSBadRequestException Wrong question type * @throws OCSBadRequestException Invalid file provided * @throws OCSBadRequestException Failed to upload the file * @throws OCSBadRequestException File size exceeds the maximum allowed size @@ -1710,6 +1702,11 @@ public function uploadFiles(int $formId, int $questionId, string $shareHash = '' throw new OCSBadRequestException('Question doesn\'t belong to the given form'); } + if ($question->getType() !== Constants::ANSWER_TYPE_FILE) { + $this->logger->debug('Question {questionId} is no file question', ['questionId' => $questionId]); + throw new OCSBadRequestException('Wrong question type'); + } + $path = $this->formsService->getTemporaryUploadedFilePath($form, $question); $response = []; diff --git a/lib/Db/QuestionMapper.php b/lib/Db/QuestionMapper.php index c705ac3c1e..d1db60cadc 100644 --- a/lib/Db/QuestionMapper.php +++ b/lib/Db/QuestionMapper.php @@ -72,8 +72,9 @@ public function deleteByForm(int $formId): void { } /** - * Find Question by its ID + * Find Question by its ID, unless it is deleted * @param int|float $questionId The question ID (int but for 32bit systems PHP uses float) + * @throws DoesNotExistException if the question does not exist or is deleted */ public function findById(int|float $questionId): Question { $qb = $this->db->getQueryBuilder(); @@ -82,6 +83,9 @@ public function findById(int|float $questionId): Question { ->from($this->getTableName()) ->where( $qb->expr()->eq('id', $qb->createNamedParameter($questionId, IQueryBuilder::PARAM_INT)) + ) + ->andWhere( + $qb->expr()->neq('order', $qb->createNamedParameter(0, IQueryBuilder::PARAM_INT)) ); return $this->findEntity($qb); diff --git a/lib/Db/SubmissionMapper.php b/lib/Db/SubmissionMapper.php index ab6273e441..35d816d797 100644 --- a/lib/Db/SubmissionMapper.php +++ b/lib/Db/SubmissionMapper.php @@ -23,12 +23,14 @@ class SubmissionMapper extends QBMapper { * SubmissionMapper constructor. * @param IDBConnection $db * @param AnswerMapper $answerMapper + * @param QuestionMapper $questionMapper * @param FilePathHelper $filePathHelper * @param LoggerInterface $logger */ public function __construct( IDBConnection $db, private readonly AnswerMapper $answerMapper, + private readonly QuestionMapper $questionMapper, private readonly FilePathHelper $filePathHelper, private readonly LoggerInterface $logger, ) { @@ -67,25 +69,44 @@ public function findByForm(int $formId, ?string $userId = null, ?string $searchS ->setFirstResult($offset) ->setMaxResults($limit); - // If a query is provided, join the answers table and filter by the query text if (!is_null($searchString) && $searchString !== '') { - $qb->join( - 'submissions', - $this->answerMapper->getTableName(), - 'answers', - $qb->expr()->eq('submissions.id', 'answers.submission_id') - ) - ->andWhere( - $qb->expr()->orX( - $qb->expr()->iLike('submissions.user_id', $qb->createNamedParameter('%' . $searchString . '%')), - $qb->expr()->iLike('answers.text', $qb->createNamedParameter('%' . $searchString . '%')), - ), - ); + $this->filterBySearch($qb, $searchString); } return $this->findEntities($qb); } + /** + * Restricts the submissions to those whose user id or an answer to a question that is not deleted contains the search string + * + * @param IQueryBuilder $qb query on the submissions table with the alias `submissions` + * @param string $searchString the search string + */ + private function filterBySearch(IQueryBuilder $qb, string $searchString): void { + $pattern = $qb->createNamedParameter('%' . $searchString . '%'); + $qb->join( + 'submissions', + $this->answerMapper->getTableName(), + 'answers', + $qb->expr()->eq('submissions.id', 'answers.submission_id') + ) + ->join( + 'answers', + $this->questionMapper->getTableName(), + 'questions', + $qb->expr()->eq('answers.question_id', 'questions.id') + ) + ->andWhere( + $qb->expr()->orX( + $qb->expr()->iLike('submissions.user_id', $pattern), + $qb->expr()->andX( + $qb->expr()->iLike('answers.text', $pattern), + $qb->expr()->neq('questions.order', $qb->createNamedParameter(0, IQueryBuilder::PARAM_INT)), + ), + ), + ); + } + /** * @param int $id * @return Submission @@ -159,18 +180,7 @@ protected function countSubmissionsWithFilters(int $formId, ?string $userId = nu } if (!is_null($searchString) && $searchString !== '') { - $query->join( - 'submissions', - $this->answerMapper->getTableName(), - 'answers', - $qb->expr()->eq('submissions.id', 'answers.submission_id') - ) - ->andWhere( - $qb->expr()->orX( - $qb->expr()->iLike('submissions.user_id', $qb->createNamedParameter('%' . $searchString . '%')), - $qb->expr()->iLike('answers.text', $qb->createNamedParameter('%' . $searchString . '%')), - ), - ); + $this->filterBySearch($query, $searchString); } if ($limit !== -1) { diff --git a/lib/Service/ConfirmationEmailService.php b/lib/Service/ConfirmationEmailService.php index dcdb85b3c0..bd2276ef0b 100644 --- a/lib/Service/ConfirmationEmailService.php +++ b/lib/Service/ConfirmationEmailService.php @@ -115,7 +115,6 @@ public function validateRecipientQuestionId(Form $form, mixed $recipientId): voi } if ($question->getFormId() !== $form->getId() - || $question->getOrder() === 0 || !$question->isEmailType()) { throw new \InvalidArgumentException('Invalid confirmationEmailQuestionId'); } diff --git a/lib/Service/SubmissionService.php b/lib/Service/SubmissionService.php index d11dc7ca20..1a8733ad20 100644 --- a/lib/Service/SubmissionService.php +++ b/lib/Service/SubmissionService.php @@ -71,13 +71,17 @@ public function __construct( * Get all the answers of a given submission * * @param int $submissionId the submission id + * @param array $activeQuestionIds ids of the active questions as keys, to filter answers * @return list */ - private function getAnswers(int $submissionId): array { + private function getAnswers(int $submissionId, array $activeQuestionIds): array { $answerList = []; try { $answerEntities = $this->answerMapper->findBySubmission($submissionId); foreach ($answerEntities as $answerEntity) { + if (!isset($activeQuestionIds[$answerEntity->getQuestionId()])) { + continue; + } $answerList[] = $answerEntity->read(); } } catch (DoesNotExistException) { @@ -87,6 +91,16 @@ private function getAnswers(int $submissionId): array { } } + /** + * Get the ids of the given questions as keys + * + * @param list $questions questions that are not deleted + * @return array the question ids as keys + */ + private function getActiveQuestionIds(array $questions): array { + return array_fill_keys(array_map(static fn (Question $question) => $question->getId(), $questions), true); + } + /** * Get all submissions of a form * @@ -108,9 +122,11 @@ public function getSubmissions(int $formId, ?string $userId = null, ?string $que try { $submissionEntities = $this->submissionMapper->findByForm($formId, $userId, $query, $limit, $offset); + $activeQuestionIds = $this->getActiveQuestionIds($this->questionMapper->findByForm($formId)); + foreach ($submissionEntities as $submissionEntity) { $submission = $submissionEntity->read(); - $submission['answers'] = $this->getAnswers($submission['id']); + $submission['answers'] = $this->getAnswers($submission['id'], $activeQuestionIds); $submissionList[] = $submission; } } catch (DoesNotExistException) { @@ -136,7 +152,8 @@ public function getSubmission(int $submissionId): ?array { try { $submissionEntity = $this->submissionMapper->findById($submissionId); $submission = $submissionEntity->read(); - $submission['answers'] = $this->getAnswers($submission['id']); + $activeQuestionIds = $this->getActiveQuestionIds($this->questionMapper->findByForm($submission['formId'])); + $submission['answers'] = $this->getAnswers($submission['id'], $activeQuestionIds); return $submission; } catch (DoesNotExistException) { return null; diff --git a/openapi.json b/openapi.json index 32c6b43568..825134dd14 100644 --- a/openapi.json +++ b/openapi.json @@ -1974,7 +1974,7 @@ } }, "400": { - "description": "One question has already been marked as deleted", + "description": "Question doesn't belong to given Form", "content": { "application/json": { "schema": { diff --git a/tests/Integration/Api/ApiV3Test.php b/tests/Integration/Api/ApiV3Test.php index a8fbfc595c..ce657f64a7 100644 --- a/tests/Integration/Api/ApiV3Test.php +++ b/tests/Integration/Api/ApiV3Test.php @@ -990,6 +990,54 @@ public function testDeleteFileQuestion() { $this->assertNotContains($fileQuestionId, $questionIds); } + public static function dataMissingQuestion(): array { + return [ + 'deleted question' => [true], + 'unknown question' => [false], + ]; + } + + /** + * @dataProvider dataMissingQuestion + */ + public function testQuestionEndpointsRejectMissingQuestion(bool $deleted): void { + $formId = $this->testForms[0]['id']; + $questions = $this->testForms[0]['questions']; + $questionId = $deleted ? $questions[1]['id'] : 2147483647; + $optionId = $questions[1]['options'][0]['id']; + if ($deleted) { + $resp = $this->http->request('DELETE', "api/v3/forms/{$formId}/questions/{$questionId}"); + $this->assertEquals(200, $resp->getStatusCode()); + } + $newOrder = $deleted ? [$questions[0]['id'], $questionId] : [$questions[0]['id'], $questionId, $questions[2]['id']]; + + $requests = [ + 'get question' => ['GET', "api/v3/forms/{$formId}/questions/{$questionId}", []], + 'update question' => ['PATCH', "api/v3/forms/{$formId}/questions/{$questionId}", ['json' => ['keyValuePairs' => ['text' => 'New text']]]], + 'delete question' => ['DELETE', "api/v3/forms/{$formId}/questions/{$questionId}", []], + 'clone question' => ['POST', "api/v3/forms/{$formId}/questions", ['json' => ['fromId' => $questionId]]], + 'reorder questions' => ['PATCH', "api/v3/forms/{$formId}/questions", ['json' => ['newOrder' => $newOrder]]], + 'new option' => ['POST', "api/v3/forms/{$formId}/questions/{$questionId}/options", ['json' => ['optionTexts' => ['New option']]]], + 'update option' => ['PATCH', "api/v3/forms/{$formId}/questions/{$questionId}/options/{$optionId}", ['json' => ['keyValuePairs' => ['text' => 'New text']]]], + 'delete option' => ['DELETE', "api/v3/forms/{$formId}/questions/{$questionId}/options/{$optionId}", []], + 'reorder options' => ['PATCH', "api/v3/forms/{$formId}/questions/{$questionId}/options", ['json' => ['newOrder' => [$optionId]]]], + 'upload file' => ['POST', "api/v3/forms/{$formId}/submissions/files/{$questionId}", ['multipart' => [['name' => 'files[]', 'contents' => 'test file content', 'filename' => 'test.txt']]]], + ]; + foreach ($requests as $name => [$method, $url, $options]) { + $resp = $this->http->request($method, $url, $options + ['http_errors' => false]); + $this->assertEquals(404, $resp->getStatusCode(), $name); + } + } + + public function testUploadFileRejectsNonFileQuestion(): void { + $resp = $this->http->request('POST', "api/v3/forms/{$this->testForms[0]['id']}/submissions/files/{$this->testForms[0]['questions'][0]['id']}", [ + 'multipart' => [['name' => 'files[]', 'contents' => 'test file content', 'filename' => 'test.txt']], + 'http_errors' => false, + ]); + + $this->assertEquals(400, $resp->getStatusCode()); + } + public function testCloneQuestion() { $resp = $this->http->request('POST', "api/v3/forms/{$this->testForms[0]['id']}/questions?fromId=" . $this->testForms[0]['questions'][0]['id']); $data = $this->OcsResponse2Data($resp); diff --git a/tests/Integration/DB/QuestionMapperTest.php b/tests/Integration/DB/QuestionMapperTest.php new file mode 100644 index 0000000000..1eb1d93e70 --- /dev/null +++ b/tests/Integration/DB/QuestionMapperTest.php @@ -0,0 +1,93 @@ + 'Test user', + ]; + + public function setUp(): void { + $this->testForms = [ + [ + 'hash' => 'question_mapper_form', + 'title' => 'Question mapper form', + 'description' => '', + 'owner_id' => 'test', + 'access_enum' => 0, + 'created' => 12345, + 'expires' => 0, + 'state' => 0, + 'is_anonymous' => false, + 'submit_multiple' => false, + 'show_expiration' => false, + 'last_updated' => 123456789, + 'submission_message' => '', + 'file_id' => null, + 'file_format' => null, + 'allow_comments' => false, + 'questions' => [ + [ + 'type' => 'short', + 'text' => 'Active question', + 'isRequired' => false, + 'name' => '', + 'order' => 1, + 'options' => [], + 'accept' => [], + 'description' => '', + 'extraSettings' => [], + ], + [ + 'type' => 'short', + 'text' => 'Deleted question', + 'isRequired' => false, + 'name' => '', + 'order' => 0, + 'options' => [], + 'accept' => [], + 'description' => '', + 'extraSettings' => [], + ], + ], + 'shares' => [], + 'submissions' => [], + ], + ]; + parent::setUp(); + + $this->questionMapper = \OCP\Server::get(QuestionMapper::class); + } + + public function testFindByIdFindsActiveQuestion(): void { + $question = $this->questionMapper->findById($this->testForms[0]['questions'][0]['id']); + + $this->assertSame('Active question', $question->getText()); + } + + public function testFindByIdSkipsDeletedQuestion(): void { + $this->expectException(DoesNotExistException::class); + $this->questionMapper->findById($this->testForms[0]['questions'][1]['id']); + } + + public function testFindByIdThrowsForUnknownQuestion(): void { + $this->expectException(DoesNotExistException::class); + $this->questionMapper->findById(2147483647); + } +} diff --git a/tests/Integration/DB/SubmissionMapperTest.php b/tests/Integration/DB/SubmissionMapperTest.php index 876b88a002..9b2409ac3f 100644 --- a/tests/Integration/DB/SubmissionMapperTest.php +++ b/tests/Integration/DB/SubmissionMapperTest.php @@ -55,6 +55,17 @@ private function setTestForms() { 'accept' => [], 'description' => 'Please answer this.', 'extraSettings' => [] + ], + [ + 'type' => 'short', + 'text' => 'Deleted Question?', + 'isRequired' => false, + 'name' => '', + 'order' => 0, + 'options' => [], + 'accept' => [], + 'description' => '', + 'extraSettings' => [] ] ], 'shares' => [], @@ -76,6 +87,10 @@ private function setTestForms() { [ 'questionIndex' => 0, 'text' => 'Answer 2' + ], + [ + 'questionIndex' => 1, + 'text' => 'Deleted term' ] ] ], @@ -121,9 +136,10 @@ public function setUp(): void { $db = \OCP\Server::get(IDBConnection::class); $answerMapper = \OCP\Server::get(\OCA\Forms\Db\AnswerMapper::class); + $questionMapper = \OCP\Server::get(\OCA\Forms\Db\QuestionMapper::class); $filePathHelper = \OCP\Server::get(\OCA\Forms\Helper\FilePathHelper::class); $logger = \OCP\Server::get(\Psr\Log\LoggerInterface::class); - $this->submissionMapper = new SubmissionMapper($db, $answerMapper, $filePathHelper, $logger); + $this->submissionMapper = new SubmissionMapper($db, $answerMapper, $questionMapper, $filePathHelper, $logger); } public function testFindByFormBasic(): void { @@ -150,6 +166,10 @@ public function testFindByFormWithSearchQuery(): void { $this->assertEquals('user2', $submissions[0]->getUserId()); } + public function testFindByFormSearchSkipsAnswersToDeletedQuestions(): void { + $this->assertCount(0, $this->submissionMapper->findByForm($this->testForms[0]['id'], null, 'Deleted term')); + } + public function testFindByFormWithLimit(): void { $submissions = $this->submissionMapper->findByForm($this->testForms[0]['id'], null, null, 2); @@ -180,6 +200,10 @@ public function testCountSubmissionsWithSearch(): void { $this->assertEquals(1, $count); } + public function testCountSubmissionsSearchSkipsAnswersToDeletedQuestions(): void { + $this->assertEquals(0, $this->submissionMapper->countSubmissions($this->testForms[0]['id'], null, 'Deleted term')); + } + public function testCountSubmissionsEmptyForm(): void { $count = $this->submissionMapper->countSubmissions($this->testForms[1]['id']); diff --git a/tests/Unit/Controller/ApiControllerTest.php b/tests/Unit/Controller/ApiControllerTest.php index 4ef57fba90..0bbec3df32 100644 --- a/tests/Unit/Controller/ApiControllerTest.php +++ b/tests/Unit/Controller/ApiControllerTest.php @@ -685,7 +685,7 @@ public function testUploadFiles() { $form->setId(1); $form->setHash('hash'); $form->setOwnerId('currentUser'); - $question = Question::fromParams(['formId' => 1]); + $question = Question::fromParams(['formId' => 1, 'type' => Constants::ANSWER_TYPE_FILE]); $this->formsService->expects($this->once()) ->method('loadFormForSubmission') @@ -746,6 +746,48 @@ public function testUploadFiles() { $this->apiController->uploadFiles(1, 10, ''); } + public static function dataUploadFilesNoFileQuestion(): array { + return [ + 'short question' => [Constants::ANSWER_TYPE_SHORT, false, OCSBadRequestException::class], + 'deleted file question' => [Constants::ANSWER_TYPE_FILE, true, OCSNotFoundException::class], + ]; + } + + /** + * @dataProvider dataUploadFilesNoFileQuestion + */ + public function testUploadFilesNoFileQuestion(string $type, bool $deleted, string $exception): void { + $form = new Form(); + $form->setId(1); + $form->setHash('hash'); + $form->setOwnerId('currentUser'); + + $this->formsService->method('loadFormForSubmission') + ->with(1) + ->willReturn($form); + $this->formsService->method('canSubmit') + ->willReturn(true); + $lookup = $this->questionMapper->method('findById')->with(10); + if ($deleted) { + $lookup->willThrowException(new DoesNotExistException('Question is deleted')); + } else { + $lookup->willReturn(Question::fromParams(['formId' => 1, 'type' => $type])); + } + $this->request->method('getUploadedFile') + ->with('files') + ->willReturn([ + 'size' => [100], + 'tmp_name' => [tempnam('/tmp', 'test')], + 'name' => ['file.txt'], + 'error' => [0], + ]); + $this->storage->expects($this->never()) + ->method('getUserFolder'); + + $this->expectException($exception); + $this->apiController->uploadFiles(1, 10, ''); + } + public function testNewSubmission_answers() { $form = new Form(); $form->setId(1); @@ -1251,6 +1293,67 @@ public function testUpdateFormRejectsInvalidConfirmationEmailQuestionId(string $ $this->apiController->updateForm(1, ['confirmationEmailQuestionId' => 7]); } + public function testGetDeletedQuestion(): void { + $form = new Form(); + $form->setId(1); + $this->formMapper->method('findById') + ->with(1) + ->willReturn($form); + $this->formsService->method('hasUserAccess') + ->with($form) + ->willReturn(true); + $this->formsService->method('getQuestion') + ->with(2) + ->willReturn(null); + + $this->expectException(OCSNotFoundException::class); + $this->apiController->getQuestion(1, 2); + } + + public static function dataChangeDeletedQuestion(): array { + return [ + 'update question' => ['updateQuestion', [1, 7, ['text' => 'New text']], OCSNotFoundException::class], + 'new option' => ['newOption', [1, 7, ['New option']], OCSNotFoundException::class], + 'update option' => ['updateOption', [1, 7, 3, ['text' => 'New text']], OCSNotFoundException::class], + 'delete option' => ['deleteOption', [1, 7, 3], OCSNotFoundException::class], + 'reorder options' => ['reorderOptions', [1, 7, [3]], OCSNotFoundException::class], + ]; + } + + /** + * @dataProvider dataChangeDeletedQuestion + */ + public function testChangeDeletedQuestion(string $method, array $arguments, string $exception): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $this->formsService + ->method('getFormIfAllowed') + ->with(1, Constants::PERMISSION_EDIT) + ->willReturn($form); + $this->formsService + ->method('isFormArchived') + ->with($form) + ->willReturn(false); + $this->questionMapper + ->method('findById') + ->with(7) + ->willThrowException(new DoesNotExistException('Question not found')); + $this->optionMapper + ->method('findById') + ->with(3) + ->willReturn(\OCA\Forms\Db\Option::fromParams(['id' => 3, 'questionId' => 7])); + $this->questionMapper->expects($this->never())->method('update'); + $this->optionMapper->expects($this->never())->method('insert'); + $this->optionMapper->expects($this->never())->method('update'); + $this->optionMapper->expects($this->never())->method('delete'); + $this->formMapper->expects($this->never())->method('update'); + + $this->expectException($exception); + $this->apiController->$method(...$arguments); + } + public function testUpdateQuestionClearsConfirmationEmailQuestionIdWhenQuestionStopsBeingEmail(): void { $form = new Form(); $form->setId(1); @@ -1334,6 +1437,35 @@ public function testDeleteQuestionClearsConfirmationEmailQuestionIdWhenDeletingS $this->assertNull($form->getConfirmationEmailQuestionId()); } + public function testDeleteQuestionRejectsDeletedQuestion(): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); + $this->formsService->method('isFormArchived')->with($form)->willReturn(false); + $this->questionMapper->method('findById')->with(7)->willThrowException(new DoesNotExistException('Question not found')); + $this->questionMapper->expects($this->never())->method('update'); + $this->formMapper->expects($this->never())->method('update'); + + $this->expectException(OCSNotFoundException::class); + $this->apiController->deleteQuestion(1, 7); + } + + public function testCloneQuestionRejectsDeletedQuestion(): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); + $this->formsService->method('isFormArchived')->with($form)->willReturn(false); + $this->questionMapper->method('findById')->with(7)->willThrowException(new DoesNotExistException('Question not found')); + $this->questionMapper->expects($this->never())->method('insert'); + + $this->expectException(OCSNotFoundException::class); + $this->apiController->newQuestion(1, null, null, '', 7); + } + public function testCloneFormWithConfirmationEmailQuestionId(): void { $this->configService->method('canCreateForms')->willReturn(true); diff --git a/tests/Unit/Service/ConfirmationEmailServiceTest.php b/tests/Unit/Service/ConfirmationEmailServiceTest.php index afc8198724..df0ee7aad9 100644 --- a/tests/Unit/Service/ConfirmationEmailServiceTest.php +++ b/tests/Unit/Service/ConfirmationEmailServiceTest.php @@ -423,13 +423,7 @@ public function testValidateRecipientQuestionIdRejectsDeletedQuestion(): void { $form = new Form(); $form->setId(1); - $question = new Question(); - $question->setFormId(1); - $question->setOrder(0); - $question->setType(Constants::ANSWER_TYPE_SHORT); - $question->setExtraSettings(['validationType' => 'email']); - - $this->questionMapper->method('findById')->willReturn($question); + $this->questionMapper->method('findById')->willThrowException(new DoesNotExistException('Question not found')); $this->expectException(\InvalidArgumentException::class); $this->service->validateRecipientQuestionId($form, 7); } diff --git a/tests/Unit/Service/SubmissionServiceTest.php b/tests/Unit/Service/SubmissionServiceTest.php index 4f8198cb26..149cd9f60b 100644 --- a/tests/Unit/Service/SubmissionServiceTest.php +++ b/tests/Unit/Service/SubmissionServiceTest.php @@ -135,6 +135,16 @@ public function testGetSubmissions() { $submission_2->setUserId('someOtherUser'); $submission_2->setTimestamp(1234); + $question_1 = new Question(); + $question_1->setId(422); + $question_1->setFormId(5); + $question_1->setOrder(1); + + $question_2 = new Question(); + $question_2->setId(423); + $question_2->setFormId(5); + $question_2->setOrder(2); + $this->submissionMapper->expects($this->any()) ->method('findByForm') ->willReturnCallback(function ($formId, $userId = null) use ($submission_1, $submission_2) { @@ -152,6 +162,11 @@ public function testGetSubmissions() { [43, []] ]); + $this->questionMapper->expects($this->any()) + ->method('findByForm') + ->with(5) + ->willReturn([$question_1, $question_2]); + $expected = [ [ 'id' => 42, @@ -207,6 +222,16 @@ public function testGetSubmission() { $answer_2->setQuestionId(423); $answer_2->setText('Just some more Text'); + $question_1 = new Question(); + $question_1->setId(422); + $question_1->setFormId(5); + $question_1->setOrder(1); + + $question_2 = new Question(); + $question_2->setId(423); + $question_2->setFormId(5); + $question_2->setOrder(2); + $this->submissionMapper->expects($this->once()) ->method('findById') ->with(42) @@ -218,6 +243,11 @@ public function testGetSubmission() { [42, [$answer_1, $answer_2]] ]); + $this->questionMapper->expects($this->any()) + ->method('findByForm') + ->with(5) + ->willReturn([$question_1, $question_2]); + $expected = [ 'id' => 42, 'formId' => 5,