diff --git a/docs/API_v3.md b/docs/API_v3.md index 291af4df9d..206e749b58 100644 --- a/docs/API_v3.md +++ b/docs/API_v3.md @@ -459,6 +459,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": { @@ -568,6 +569,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 @@ -672,6 +674,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": { @@ -775,7 +778,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" @@ -836,6 +839,7 @@ Upload a file to an answer before form submission |--------------|----------------|-------------| | _files_ | Array of files | Files to upload | - Response: **Status-Code OK**, as well as the id of the uploaded file and it's name. + 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": {"uploadedFileId": integer, "fileName": "string"} diff --git a/lib/Controller/ApiController.php b/lib/Controller/ApiController.php index 58dc36ba4c..48e7062063 100644 --- a/lib/Controller/ApiController.php +++ b/lib/Controller/ApiController.php @@ -733,7 +733,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 @@ -794,16 +793,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); @@ -1018,7 +1009,7 @@ public function deleteOption(int $formId, int $questionId, int $optionId): DataR $question = $this->questionMapper->findById($questionId); } catch (IMapperException $e) { $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) { @@ -1587,6 +1578,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 @@ -1638,6 +1630,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 fefd9fd259..7f31d8df82 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 367d945041..a3bbf63dba 100644 --- a/lib/Db/SubmissionMapper.php +++ b/lib/Db/SubmissionMapper.php @@ -20,10 +20,12 @@ class SubmissionMapper extends QBMapper { * SubmissionMapper constructor. * @param IDBConnection $db * @param AnswerMapper $answerMapper + * @param QuestionMapper $questionMapper */ public function __construct( IDBConnection $db, private AnswerMapper $answerMapper, + private QuestionMapper $questionMapper, ) { parent::__construct($db, 'forms_v2_submissions', Submission::class); } @@ -60,25 +62,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 @@ -152,18 +173,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/SubmissionService.php b/lib/Service/SubmissionService.php index 3c93eff5a6..744c888ad2 100644 --- a/lib/Service/SubmissionService.php +++ b/lib/Service/SubmissionService.php @@ -67,13 +67,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 $e) { @@ -83,6 +87,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 * @@ -104,9 +118,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 $e) { @@ -132,7 +148,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 $e) { return null; @@ -225,6 +242,7 @@ public function getSubmissionsData(Form $form, string $fileFormat, ?File $file = $submissionEntities = array_reverse($submissionEntities); $questions = $this->questionMapper->findByForm($form->getId()); + $defaultTimeZone = $this->config->getSystemValueString('default_timezone', 'UTC'); if (!$this->currentUser) { diff --git a/openapi.json b/openapi.json index 1e8e8bc83f..8863b453c5 100644 --- a/openapi.json +++ b/openapi.json @@ -1886,7 +1886,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 595b1e8536..9fb801bf80 100644 --- a/tests/Integration/Api/ApiV3Test.php +++ b/tests/Integration/Api/ApiV3Test.php @@ -874,6 +874,54 @@ public function testDeleteQuestion(array $fullFormExpected) { $this->testGetFullForm($fullFormExpected); } + 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 c763251bb1..bd313f8be1 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' ] ] ], @@ -120,7 +135,8 @@ public function setUp(): void { $db = \OCP\Server::get(IDBConnection::class); $answerMapper = \OCP\Server::get(\OCA\Forms\Db\AnswerMapper::class); - $this->submissionMapper = new SubmissionMapper($db, $answerMapper); + $questionMapper = \OCP\Server::get(\OCA\Forms\Db\QuestionMapper::class); + $this->submissionMapper = new SubmissionMapper($db, $answerMapper, $questionMapper); } public function testFindByFormBasic(): void { @@ -147,6 +163,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); @@ -177,6 +197,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 2d0ac7b3c4..4d89b85916 100644 --- a/tests/Unit/Controller/ApiControllerTest.php +++ b/tests/Unit/Controller/ApiControllerTest.php @@ -692,7 +692,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') @@ -753,6 +753,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); @@ -1165,6 +1207,96 @@ public function testDeleteAllSubmissionsWithResultsDeletePermission(): void { $this->assertEquals(new DataResponse(1), $this->apiController->deleteAllSubmissions(1)); } + 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 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, '', 7); + } + public function testTransferOwnerNotOwner() { $form = new Form(); $form->setId(1); diff --git a/tests/Unit/Service/SubmissionServiceTest.php b/tests/Unit/Service/SubmissionServiceTest.php index 283ac546ae..34d7bdb0d0 100644 --- a/tests/Unit/Service/SubmissionServiceTest.php +++ b/tests/Unit/Service/SubmissionServiceTest.php @@ -160,6 +160,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) { @@ -177,6 +187,11 @@ public function testGetSubmissions() { [43, []] ]); + $this->questionMapper->expects($this->any()) + ->method('findByForm') + ->with(5) + ->willReturn([$question_1, $question_2]); + $expected = [ [ 'id' => 42, @@ -232,6 +247,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) @@ -243,6 +268,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,