How to use prophesize method of Prophet class

Best Prophecy code snippet using Prophet.prophesize

Typo3DbQueryParserTest.php

Source:Typo3DbQueryParserTest.php Github

copy

Full Screen

...62 [],63 '',64 false65 );66 $queryBuilderProphecy = $this->prophesize(QueryBuilder::class);67 $subject->_set('queryBuilder', $queryBuilderProphecy->reveal());68 $queryProphecy = $this->prophesize(QueryInterface::class);69 $sourceProphecy = $this->prophesize(SourceInterface::class);70 $queryProphecy->getSource()->willReturn($sourceProphecy->reveal());71 $queryProphecy->getOrderings()->willReturn([]);72 $queryProphecy->getStatement()->willReturn(null);73 // Test part: getConstraint returns no constraint object, andWhere() should not be called74 $queryProphecy->getConstraint()->willReturn(null);75 $queryBuilderProphecy->andWhere()->shouldNotBeCalled();76 $subject->convertQueryToDoctrineQueryBuilder($queryProphecy->reveal());77 }78 /**79 * @test80 */81 public function convertQueryToDoctrineQueryBuilderThrowsExceptionOnNotImplementedConstraint()82 {83 // Prepare subject, turn off initialize qb method and inject qb prophecy revelation84 $subject = $this->getAccessibleMock(85 Typo3DbQueryParser::class,86 // Shut down some methods not important for this test87 ['initializeQueryBuilder', 'parseOrderings', 'addTypo3Constraints', 'parseComparison'],88 [],89 '',90 false91 );92 $queryBuilderProphecy = $this->prophesize(QueryBuilder::class);93 $subject->_set('queryBuilder', $queryBuilderProphecy->reveal());94 $queryProphecy = $this->prophesize(QueryInterface::class);95 $sourceProphecy = $this->prophesize(SourceInterface::class);96 $queryProphecy->getSource()->willReturn($sourceProphecy->reveal());97 $queryProphecy->getOrderings()->willReturn([]);98 $queryProphecy->getStatement()->willReturn(null);99 // Test part: getConstraint returns not implemented object100 $constraintProphecy = $this->prophesize(ConstraintInterface::class);101 $queryProphecy->getConstraint()->willReturn($constraintProphecy->reveal());102 $this->expectException(\RuntimeException::class);103 $this->expectExceptionCode(1476199898);104 $subject->convertQueryToDoctrineQueryBuilder($queryProphecy->reveal());105 }106 /**107 * @test108 */109 public function convertQueryToDoctrineQueryBuilderAddsSimpleAndWhere()110 {111 // Prepare subject, turn off initialize qb method and inject qb prophecy revelation112 $subject = $this->getAccessibleMock(113 Typo3DbQueryParser::class,114 // Shut down some methods not important for this test115 ['initializeQueryBuilder', 'parseOrderings', 'addTypo3Constraints', 'parseComparison'],116 [],117 '',118 false119 );120 $queryBuilderProphecy = $this->prophesize(QueryBuilder::class);121 $subject->_set('queryBuilder', $queryBuilderProphecy->reveal());122 $queryProphecy = $this->prophesize(QueryInterface::class);123 $sourceProphecy = $this->prophesize(SourceInterface::class);124 $queryProphecy->getSource()->willReturn($sourceProphecy->reveal());125 $queryProphecy->getOrderings()->willReturn([]);126 $queryProphecy->getStatement()->willReturn(null);127 // Test part: getConstraint returns simple constraint, and should push to andWhere()128 $constraintProphecy = $this->prophesize(ComparisonInterface::class);129 $queryProphecy->getConstraint()->willReturn($constraintProphecy->reveal());130 $subject->expects(self::once())->method('parseComparison')->willReturn('heinz');131 $queryBuilderProphecy->andWhere('heinz')->shouldBeCalled();132 $subject->convertQueryToDoctrineQueryBuilder($queryProphecy->reveal());133 }134 /**135 * @test136 */137 public function convertQueryToDoctrineQueryBuilderAddsNotConstraint()138 {139 // Prepare subject, turn off initialize qb method and inject qb prophecy revelation140 $subject = $this->getAccessibleMock(141 Typo3DbQueryParser::class,142 // Shut down some methods not important for this test143 ['initializeQueryBuilder', 'parseOrderings', 'addTypo3Constraints', 'parseComparison'],144 [],145 '',146 false147 );148 $queryBuilderProphecy = $this->prophesize(QueryBuilder::class);149 $subject->_set('queryBuilder', $queryBuilderProphecy->reveal());150 $queryProphecy = $this->prophesize(QueryInterface::class);151 $sourceProphecy = $this->prophesize(SourceInterface::class);152 $queryProphecy->getSource()->willReturn($sourceProphecy->reveal());153 $queryProphecy->getOrderings()->willReturn([]);154 $queryProphecy->getStatement()->willReturn(null);155 $constraintProphecy = $this->prophesize(NotInterface::class);156 $subConstraintProphecy = $this->prophesize(ComparisonInterface::class);157 $constraintProphecy->getConstraint()->shouldBeCalled()->willReturn($subConstraintProphecy->reveal());158 $queryProphecy->getConstraint()->willReturn($constraintProphecy->reveal());159 $subject->expects(self::once())->method('parseComparison')->willReturn('heinz');160 $queryBuilderProphecy->andWhere(' NOT(heinz)')->shouldBeCalled();161 $subject->convertQueryToDoctrineQueryBuilder($queryProphecy->reveal());162 }163 /**164 * @test165 */166 public function convertQueryToDoctrineQueryBuilderAddsAndConstraint()167 {168 // Prepare subject, turn off initialize qb method and inject qb prophecy revelation169 $subject = $this->getAccessibleMock(170 Typo3DbQueryParser::class,171 // Shut down some methods not important for this test172 ['initializeQueryBuilder', 'parseOrderings', 'addTypo3Constraints', 'parseComparison'],173 [],174 '',175 false176 );177 $queryBuilderProphecy = $this->prophesize(QueryBuilder::class);178 $subject->_set('queryBuilder', $queryBuilderProphecy->reveal());179 $queryProphecy = $this->prophesize(QueryInterface::class);180 $sourceProphecy = $this->prophesize(SourceInterface::class);181 $queryProphecy->getSource()->willReturn($sourceProphecy->reveal());182 $queryProphecy->getOrderings()->willReturn([]);183 $queryProphecy->getStatement()->willReturn(null);184 $constraintProphecy = $this->prophesize(AndInterface::class);185 $queryProphecy->getConstraint()->willReturn($constraintProphecy->reveal());186 $constraint1Prophecy = $this->prophesize(ComparisonInterface::class);187 $constraintProphecy->getConstraint1()->willReturn($constraint1Prophecy->reveal());188 $constraint2Prophecy = $this->prophesize(ComparisonInterface::class);189 $constraintProphecy->getConstraint2()->willReturn($constraint2Prophecy->reveal());190 $subject->expects(self::any())->method('parseComparison')->willReturn('heinz');191 $expressionProphecy = $this->prophesize(ExpressionBuilder::class);192 $queryBuilderProphecy->expr()->shouldBeCalled()->willReturn($expressionProphecy->reveal());193 $compositeExpressionProphecy = $this->prophesize(CompositeExpression::class);194 $compositeExpressionProphecy->__toString()->willReturn('heinz AND heinz');195 $compositeExpressionRevelation = $compositeExpressionProphecy->reveal();196 $expressionProphecy->andX('heinz', 'heinz')->shouldBeCalled()->willReturn($compositeExpressionRevelation);197 $queryBuilderProphecy->andWhere($compositeExpressionRevelation)->shouldBeCalled();198 $subject->convertQueryToDoctrineQueryBuilder($queryProphecy->reveal());199 }200 /**201 * @test202 */203 public function convertQueryToDoctrineQueryBuilderAddsOrConstraint()204 {205 // Prepare subject, turn off initialize qb method and inject qb prophecy revelation206 $subject = $this->getAccessibleMock(207 Typo3DbQueryParser::class,208 // Shut down some methods not important for this test209 ['initializeQueryBuilder', 'parseOrderings', 'addTypo3Constraints', 'parseComparison'],210 [],211 '',212 false213 );214 $queryBuilderProphecy = $this->prophesize(QueryBuilder::class);215 $subject->_set('queryBuilder', $queryBuilderProphecy->reveal());216 $queryProphecy = $this->prophesize(QueryInterface::class);217 $sourceProphecy = $this->prophesize(SourceInterface::class);218 $queryProphecy->getSource()->willReturn($sourceProphecy->reveal());219 $queryProphecy->getOrderings()->willReturn([]);220 $queryProphecy->getStatement()->willReturn(null);221 $constraintProphecy = $this->prophesize(OrInterface::class);222 $queryProphecy->getConstraint()->willReturn($constraintProphecy->reveal());223 $constraint1Prophecy = $this->prophesize(ComparisonInterface::class);224 $constraintProphecy->getConstraint1()->willReturn($constraint1Prophecy->reveal());225 $constraint2Prophecy = $this->prophesize(ComparisonInterface::class);226 $constraintProphecy->getConstraint2()->willReturn($constraint2Prophecy->reveal());227 $subject->expects(self::any())->method('parseComparison')->willReturn('heinz');228 $expressionProphecy = $this->prophesize(ExpressionBuilder::class);229 $queryBuilderProphecy->expr()->shouldBeCalled()->willReturn($expressionProphecy->reveal());230 $compositeExpressionProphecy = $this->prophesize(CompositeExpression::class);231 $compositeExpressionProphecy->__toString()->willReturn('heinz OR heinz');232 $compositeExpressionRevelation = $compositeExpressionProphecy->reveal();233 $expressionProphecy->orX('heinz', 'heinz')->shouldBeCalled()->willReturn($compositeExpressionRevelation);234 $queryBuilderProphecy->andWhere($compositeExpressionRevelation)->shouldBeCalled();235 $subject->convertQueryToDoctrineQueryBuilder($queryProphecy->reveal());236 }237 /**238 * @return \Prophecy\Prophecy\ObjectProphecy239 */240 protected function getQueryBuilderWithExpressionBuilderProphet()241 {242 $connectionProphet = $this->prophesize(Connection::class);243 $connectionProphet->quoteIdentifier(Argument::cetera())->willReturnArgument(0);244 $queryBuilderProphet = $this->prophesize(QueryBuilder::class, $connectionProphet->reveal());245 $expr = GeneralUtility::makeInstance(ExpressionBuilder::class, $connectionProphet->reveal());246 $queryBuilderProphet->expr()->willReturn($expr);247 return $queryBuilderProphet;248 }249 /**250 * @return \Prophecy\Prophecy\ObjectProphecy251 */252 protected function getQueryBuilderProphetWithQueryBuilderForSubselect()253 {254 $connectionProphet = $this->prophesize(Connection::class);255 $connectionProphet->quoteIdentifier(Argument::cetera())->willReturnArgument(0);256 $queryBuilderProphet = $this->prophesize(QueryBuilder::class, $connectionProphet->reveal());257 $expr = GeneralUtility::makeInstance(ExpressionBuilder::class, $connectionProphet->reveal());258 $queryBuilderProphet->expr()->willReturn(259 $expr260 );261 $queryBuilderProphet->getConnection()->willReturn($connectionProphet->reveal());262 $queryBuilderForSubselectMock = $this->getMockBuilder(QueryBuilder::class)263 ->setMethods(['expr', 'unquoteSingleIdentifier'])264 ->setConstructorArgs([$connectionProphet->reveal()])265 ->getMock();266 $connectionProphet->createQueryBuilder()->willReturn($queryBuilderForSubselectMock);267 $queryBuilderForSubselectMock->expects(self::any())->method('expr')->willReturn($expr);268 $queryBuilderForSubselectMock->expects(self::any())->method('unquoteSingleIdentifier')->willReturnCallback(function ($identifier) {269 return $identifier;270 });271 return $queryBuilderProphet;272 }273 /**274 * @test275 */276 public function addGetLanguageStatementWorksForDefaultLanguage()277 {278 $table = StringUtility::getUniqueId('tx_coretest_table');279 $GLOBALS['TCA'][$table]['ctrl'] = [280 'languageField' => 'sys_language_uid'281 ];282 $querySettings = new Typo3QuerySettings(283 new Context(),284 $this->prophesize(ConfigurationManagerInterface::class)->reveal()285 );286 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);287 $queryBuilderProphet = $this->getQueryBuilderWithExpressionBuilderProphet();288 $mockTypo3DbQueryParser->_set('queryBuilder', $queryBuilderProphet->reveal());289 $sql = $mockTypo3DbQueryParser->_call('getLanguageStatement', $table, $table, $querySettings);290 $expectedSql = $table . '.sys_language_uid IN (0, -1)';291 self::assertSame($expectedSql, $sql);292 }293 /**294 * @test295 */296 public function addGetLanguageStatementWorksForNonDefaultLanguage()297 {298 $table = StringUtility::getUniqueId('tx_coretest_table');299 $GLOBALS['TCA'][$table]['ctrl'] = [300 'languageField' => 'sys_language_uid'301 ];302 $querySettings = new Typo3QuerySettings(303 new Context(),304 $this->prophesize(ConfigurationManagerInterface::class)->reveal()305 );306 $querySettings->setLanguageUid('1');307 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);308 $queryBuilderProphet = $this->getQueryBuilderWithExpressionBuilderProphet();309 $mockTypo3DbQueryParser->_set('queryBuilder', $queryBuilderProphet->reveal());310 $sql = $mockTypo3DbQueryParser->_call('getLanguageStatement', $table, $table, $querySettings);311 $result = $table . '.sys_language_uid IN (1, -1)';312 self::assertSame($result, $sql);313 }314 /**315 * @test316 */317 public function addGetLanguageStatementWorksInBackendContextWithNoGlobalTypoScriptFrontendControllerAvailable()318 {319 $table = StringUtility::getUniqueId('tx_coretest_table');320 $GLOBALS['TCA'][$table]['ctrl'] = [321 'languageField' => 'sys_language_uid'322 ];323 $querySettings = new Typo3QuerySettings(324 new Context(),325 $this->prophesize(ConfigurationManagerInterface::class)->reveal()326 );327 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);328 $queryBuilderProphet = $this->getQueryBuilderWithExpressionBuilderProphet();329 $mockTypo3DbQueryParser->_set('queryBuilder', $queryBuilderProphet->reveal());330 $sql = $mockTypo3DbQueryParser->_call('getLanguageStatement', $table, $table, $querySettings);331 $expectedSql = $table . '.sys_language_uid IN (0, -1)';332 self::assertSame($expectedSql, $sql);333 }334 /**335 * @test336 */337 public function addGetLanguageStatementWorksForDefaultLanguageWithoutDeleteStatementReturned()338 {339 $table = StringUtility::getUniqueId('tx_coretest_table');340 $GLOBALS['TCA'][$table]['ctrl'] = [341 'languageField' => 'sys_language_uid',342 'delete' => 'deleted'343 ];344 $querySettings = new Typo3QuerySettings(345 new Context(),346 $this->prophesize(ConfigurationManagerInterface::class)->reveal()347 );348 $querySettings->setLanguageUid(0);349 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);350 $queryBuilderProphet = $this->getQueryBuilderWithExpressionBuilderProphet();351 $mockTypo3DbQueryParser->_set('queryBuilder', $queryBuilderProphet->reveal());352 $sql = $mockTypo3DbQueryParser->_call('getLanguageStatement', $table, $table, $querySettings);353 $expectedSql = $table . '.sys_language_uid IN (0, -1)';354 self::assertSame($expectedSql, $sql);355 }356 /**357 * @test358 */359 public function addGetLanguageStatementWorksForForeignLanguageWithoutSubselection()360 {361 $table = StringUtility::getUniqueId('tx_coretest_table');362 $GLOBALS['TCA'][$table]['ctrl'] = [363 'languageField' => 'sys_language_uid'364 ];365 $querySettings = new Typo3QuerySettings(366 new Context(),367 $this->prophesize(ConfigurationManagerInterface::class)->reveal()368 );369 $querySettings->setLanguageUid(2);370 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);371 $queryBuilderProphet = $this->getQueryBuilderWithExpressionBuilderProphet();372 $mockTypo3DbQueryParser->_set('queryBuilder', $queryBuilderProphet->reveal());373 $sql = $mockTypo3DbQueryParser->_call('getLanguageStatement', $table, $table, $querySettings);374 $expectedSql = $table . '.sys_language_uid IN (2, -1)';375 self::assertSame($expectedSql, $sql);376 }377 /**378 * @test379 */380 public function addGetLanguageStatementWorksForForeignLanguageWithSubselectionWithoutDeleteStatementReturned()381 {382 $table = StringUtility::getUniqueId('tx_coretest_table');383 $GLOBALS['TCA'][$table]['ctrl'] = [384 'languageField' => 'sys_language_uid',385 'transOrigPointerField' => 'l10n_parent'386 ];387 $querySettings = new Typo3QuerySettings(388 new Context(),389 $this->prophesize(ConfigurationManagerInterface::class)->reveal()390 );391 $querySettings->setIgnoreEnableFields(true);392 $querySettings->setIncludeDeleted(true);393 $querySettings->setLanguageOverlayMode(true);394 $querySettings->setLanguageUid(2);395 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);396 $queryBuilderProphet = $this->getQueryBuilderProphetWithQueryBuilderForSubselect();397 $mockTypo3DbQueryParser->_set('queryBuilder', $queryBuilderProphet->reveal());398 $compositeExpression = $mockTypo3DbQueryParser->_call('getLanguageStatement', $table, $table, $querySettings);399 $expectedSql = '(' . $table . '.sys_language_uid = -1) OR ((' . $table . '.sys_language_uid = 2) AND (' . $table . '.l10n_parent IN (SELECT ' . $table . '_dl.uid FROM ' . $table . ' ' . $table . '_dl WHERE (' . $table . '_dl.l10n_parent = 0) AND (' . $table . '_dl.sys_language_uid = 0)))) OR ((' . $table . '.sys_language_uid = 0) AND (' . $table . '.uid NOT IN (SELECT ' . $table . '_to.l10n_parent FROM ' . $table . ' ' . $table . '_dl, ' . $table . ' ' . $table . '_to WHERE (' . $table . '_to.l10n_parent > 0) AND (' . $table . '_to.sys_language_uid = 2))))';400 self::assertSame($expectedSql, $compositeExpression->__toString());401 }402 /**403 * @test404 */405 public function addGetLanguageStatementWorksForForeignLanguageWithSubselectionTakesDeleteStatementIntoAccountIfNecessary()406 {407 $table = StringUtility::getUniqueId('tx_coretest_table');408 $GLOBALS['TCA'][$table]['ctrl'] = [409 'languageField' => 'sys_language_uid',410 'transOrigPointerField' => 'l10n_parent',411 'delete' => 'deleted'412 ];413 $querySettings = new Typo3QuerySettings(414 new Context(),415 $this->prophesize(ConfigurationManagerInterface::class)->reveal()416 );417 $querySettings->setLanguageUid(2);418 $querySettings->setIgnoreEnableFields(true);419 $querySettings->setIncludeDeleted(true);420 $querySettings->setLanguageOverlayMode(true);421 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);422 $queryBuilderProphet = $this->getQueryBuilderProphetWithQueryBuilderForSubselect();423 $mockTypo3DbQueryParser->_set('queryBuilder', $queryBuilderProphet->reveal());424 $compositeExpression= $mockTypo3DbQueryParser->_call('getLanguageStatement', $table, $table, $querySettings);425 $expectedSql = '(' . $table . '.sys_language_uid = -1) OR ((' . $table . '.sys_language_uid = 2) AND (' . $table . '.l10n_parent IN (SELECT ' . $table . '_dl.uid FROM ' . $table . ' ' . $table . '_dl WHERE (' . $table . '_dl.l10n_parent = 0) AND (' . $table . '_dl.sys_language_uid = 0) AND (' . $table . '_dl.deleted = 0)))) OR ((' . $table . '.sys_language_uid = 0) AND (' . $table . '.uid NOT IN (SELECT ' . $table . '_to.l10n_parent FROM ' . $table . ' ' . $table . '_dl, ' . $table . ' ' . $table . '_to WHERE (' . $table . '_to.l10n_parent > 0) AND (' . $table . '_to.sys_language_uid = 2) AND ((' . $table . '_dl.deleted = 0) AND (' . $table . '_to.deleted = 0)))))';426 self::assertSame($expectedSql, $compositeExpression->__toString());427 }428 /**429 * @test430 */431 public function addGetLanguageStatementWorksInBackendContextWithSubselectionTakesDeleteStatementIntoAccountIfNecessary()432 {433 $table = 'tt_content';434 $GLOBALS['TCA'][$table]['ctrl'] = [435 'languageField' => 'sys_language_uid',436 'transOrigPointerField' => 'l10n_parent',437 'delete' => 'deleted'438 ];439 $querySettings = new Typo3QuerySettings(440 new Context(),441 $this->prophesize(ConfigurationManagerInterface::class)->reveal()442 );443 $querySettings->setLanguageUid(2);444 $querySettings->setIgnoreEnableFields(true);445 $querySettings->setIncludeDeleted(true);446 $querySettings->setLanguageOverlayMode(true);447 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);448 $queryBuilderProphet = $this->getQueryBuilderProphetWithQueryBuilderForSubselect();449 $mockTypo3DbQueryParser->_set('queryBuilder', $queryBuilderProphet->reveal());450 $compositeExpression = $mockTypo3DbQueryParser->_call('getLanguageStatement', $table, $table, $querySettings);451 $expectedSql = '(' . $table . '.sys_language_uid = -1) OR ((' . $table . '.sys_language_uid = 2) AND (' . $table . '.l10n_parent IN (SELECT ' . $table . '_dl.uid FROM ' . $table . ' ' . $table . '_dl WHERE (' . $table . '_dl.l10n_parent = 0) AND (' . $table . '_dl.sys_language_uid = 0) AND (' . $table . '_dl.deleted = 0)))) OR ((' . $table . '.sys_language_uid = 0) AND (' . $table . '.uid NOT IN (SELECT ' . $table . '_to.l10n_parent FROM ' . $table . ' ' . $table . '_dl, ' . $table . ' ' . $table . '_to WHERE (' . $table . '_to.l10n_parent > 0) AND (' . $table . '_to.sys_language_uid = 2) AND ((' . $table . '_dl.deleted = 0) AND (' . $table . '_to.deleted = 0)))))';452 self::assertSame($expectedSql, $compositeExpression->__toString());453 }454 /**455 * @test456 */457 public function orderStatementGenerationWorks()458 {459 $mockSource = $this->getMockBuilder(Selector::class)460 ->setMethods(['getNodeTypeName'])461 ->disableOriginalConstructor()462 ->getMock();463 $mockSource->expects(self::any())->method('getNodeTypeName')->willReturn('foo');464 $mockDataMapper = $this->getMockBuilder(DataMapper::class)465 ->setMethods(['convertPropertyNameToColumnName', 'convertClassNameToTableName'])466 ->disableOriginalConstructor()467 ->getMock();468 $mockDataMapper->expects(self::once())->method('convertClassNameToTableName')->with('foo')->willReturn('tx_myext_tablename');469 $mockDataMapper->expects(self::once())->method('convertPropertyNameToColumnName')->with('fooProperty', 'foo')->willReturn('converted_fieldname');470 $queryBuilderProphet = $this->prophesize(QueryBuilder::class);471 $queryBuilderProphet->addOrderBy('tx_myext_tablename.converted_fieldname', 'ASC')->shouldBeCalledTimes(1);472 $orderings = ['fooProperty' => QueryInterface::ORDER_ASCENDING];473 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);474 $mockTypo3DbQueryParser->_set('dataMapper', $mockDataMapper);475 $mockTypo3DbQueryParser->_set('queryBuilder', $queryBuilderProphet->reveal());476 $mockTypo3DbQueryParser->_call('parseOrderings', $orderings, $mockSource);477 }478 /**479 * @test480 */481 public function orderStatementGenerationThrowsExceptionOnUnsupportedOrder()482 {483 $this->expectException(UnsupportedOrderException::class);484 $this->expectExceptionCode(1242816074);485 $mockSource = $this->getMockBuilder(Selector::class)486 ->setMethods(['getNodeTypeName'])487 ->disableOriginalConstructor()488 ->getMock();489 $mockSource->expects(self::never())->method('getNodeTypeName');490 $mockDataMapper = $this->getMockBuilder(DataMapper::class)491 ->setMethods(['convertPropertyNameToColumnName', 'convertClassNameToTableName'])492 ->disableOriginalConstructor()493 ->getMock();494 $mockDataMapper->expects(self::never())->method('convertClassNameToTableName');495 $mockDataMapper->expects(self::never())->method('convertPropertyNameToColumnName');496 $orderings = ['fooProperty' => 'unsupported_order'];497 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);498 $mockTypo3DbQueryParser->_set('dataMapper', $mockDataMapper);499 $mockTypo3DbQueryParser->_call('parseOrderings', $orderings, $mockSource);500 }501 /**502 * @test503 */504 public function orderStatementGenerationWorksWithMultipleOrderings()505 {506 $mockSource = $this->getMockBuilder(Selector::class)507 ->setMethods(['getNodeTypeName'])508 ->disableOriginalConstructor()509 ->getMock();510 $mockSource->expects(self::any())->method('getNodeTypeName')->willReturn('Tx_MyExt_ClassName');511 $mockDataMapper = $this->getMockBuilder(DataMapper::class)512 ->setMethods(['convertPropertyNameToColumnName', 'convertClassNameToTableName'])513 ->disableOriginalConstructor()514 ->getMock();515 $mockDataMapper->expects(self::any())->method('convertClassNameToTableName')->with('Tx_MyExt_ClassName')->willReturn('tx_myext_tablename');516 $mockDataMapper->expects(self::any())->method('convertPropertyNameToColumnName')->willReturn('converted_fieldname');517 $orderings = [518 'fooProperty' => QueryInterface::ORDER_ASCENDING,519 'barProperty' => QueryInterface::ORDER_DESCENDING520 ];521 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);522 $mockTypo3DbQueryParser->_set('dataMapper', $mockDataMapper);523 $queryBuilder = $this->getMockBuilder(QueryBuilder::class)524 ->disableOriginalConstructor()525 ->setMethods(['addOrderBy'])526 ->getMock();527 $queryBuilder->expects(self::exactly(2))->method('addOrderBy')528 ->withConsecutive(529 ['tx_myext_tablename.converted_fieldname', 'ASC'],530 ['tx_myext_tablename.converted_fieldname', 'DESC']531 );532 $mockTypo3DbQueryParser->_set('queryBuilder', $queryBuilder);533 $mockTypo3DbQueryParser->_call('parseOrderings', $orderings, $mockSource);534 }535 public function providerForVisibilityConstraintStatement()536 {537 return [538 'in be: include all' => ['BE', true, [], true, ''],539 'in be: ignore enable fields but do not include deleted' => ['BE', true, [], false, 'tx_foo_table.deleted_column=0'],540 'in be: respect enable fields but include deleted' => ['BE', false, [], true, '(tx_foo_table.disabled_column = 0) AND (tx_foo_table.starttime_column <= 1451779200)'],541 'in be: respect enable fields and do not include deleted' => ['BE', false, [], false, '(tx_foo_table.disabled_column = 0) AND (tx_foo_table.starttime_column <= 1451779200) AND tx_foo_table.deleted_column=0'],542 'in fe: include all' => ['FE', true, [], true, ''],543 'in fe: ignore enable fields but do not include deleted' => ['FE', true, [], false, 'tx_foo_table.deleted_column=0'],544 'in fe: ignore only starttime and do not include deleted' => ['FE', true, ['starttime'], false, '(tx_foo_table.deleted_column = 0) AND (tx_foo_table.disabled_column = 0)'],545 'in fe: respect enable fields and do not include deleted' => ['FE', false, [], false, '(tx_foo_table.deleted_column = 0) AND (tx_foo_table.disabled_column = 0) AND (tx_foo_table.starttime_column <= 1451779200)']546 ];547 }548 /**549 * @test550 * @dataProvider providerForVisibilityConstraintStatement551 */552 public function visibilityConstraintStatementIsGeneratedAccordingToTheQuerySettings($mode, $ignoreEnableFields, $enableFieldsToBeIgnored, $deletedValue, $expectedSql)553 {554 $tableName = 'tx_foo_table';555 $GLOBALS['TCA'][$tableName]['ctrl'] = [556 'enablecolumns' => [557 'disabled' => 'disabled_column',558 'starttime' => 'starttime_column'559 ],560 'delete' => 'deleted_column'561 ];562 // simulate time for backend enable fields563 $GLOBALS['SIM_ACCESS_TIME'] = 1451779200;564 // simulate time for frontend (PageRepository) enable fields565 $dateAspect = new DateTimeAspect(new \DateTimeImmutable('@1451779200'));566 $context = new Context(['date' => $dateAspect]);567 GeneralUtility::setSingletonInstance(Context::class, $context);568 $connectionProphet = $this->prophesize(Connection::class);569 $connectionProphet->quoteIdentifier(Argument::cetera())->willReturnArgument(0);570 $connectionProphet->getExpressionBuilder()->willReturn(571 GeneralUtility::makeInstance(ExpressionBuilder::class, $connectionProphet->reveal())572 );573 $queryBuilderProphet = $this->prophesize(QueryBuilder::class);574 $queryBuilderProphet->expr()->willReturn(575 GeneralUtility::makeInstance(ExpressionBuilder::class, $connectionProphet->reveal())576 );577 $queryBuilderProphet->createNamedParameter(Argument::cetera())->willReturnArgument(0);578 $connectionPoolProphet = $this->prophesize(ConnectionPool::class);579 $connectionPoolProphet->getConnectionForTable(Argument::any($tableName, 'pages'))->willReturn($connectionProphet->reveal());580 $connectionPoolProphet->getQueryBuilderForTable(Argument::any($tableName, 'pages'))->willReturn($queryBuilderProphet->reveal());581 GeneralUtility::addInstance(ConnectionPool::class, $connectionPoolProphet->reveal());582 GeneralUtility::addInstance(ConnectionPool::class, $connectionPoolProphet->reveal());583 $mockQuerySettings = $this->getMockBuilder(Typo3QuerySettings::class)584 ->setMethods(['getIgnoreEnableFields', 'getEnableFieldsToBeIgnored', 'getIncludeDeleted'])585 ->disableOriginalConstructor()586 ->getMock();587 $mockQuerySettings->expects(self::once())->method('getIgnoreEnableFields')->willReturn($ignoreEnableFields);588 $mockQuerySettings->expects(self::once())->method('getEnableFieldsToBeIgnored')->willReturn($enableFieldsToBeIgnored);589 $mockQuerySettings->expects(self::once())->method('getIncludeDeleted')->willReturn($deletedValue);590 if ($mode === 'FE') {591 $GLOBALS['TYPO3_REQUEST'] = (new ServerRequest())592 ->withAttribute('applicationType', SystemEnvironmentBuilder::REQUESTTYPE_FE);593 }594 $mockTypo3DbQueryParser = $this->getAccessibleMock(Typo3DbQueryParser::class, ['dummy'], [], '', false);595 $resultSql = $mockTypo3DbQueryParser->_call('getVisibilityConstraintStatement', $mockQuerySettings, $tableName, $tableName);596 self::assertSame($expectedSql, $resultSql);597 unset($GLOBALS['TCA'][$tableName]);598 }599 public function providerForRespectEnableFields()600 {601 return [602 'in be: respectEnableFields=false' => ['BE', false, ''],603 'in be: respectEnableFields=true' => ['BE', true, '(tx_foo_table.disabled_column = 0) AND (tx_foo_table.starttime_column <= 1451779200) AND tx_foo_table.deleted_column=0'],604 'in FE: respectEnableFields=false' => ['FE', false, ''],605 'in FE: respectEnableFields=true' => ['FE', true, '(tx_foo_table.deleted_column = 0) AND (tx_foo_table.disabled_column = 0) AND (tx_foo_table.starttime_column <= 1451779200)']606 ];607 }608 /**609 * @test610 * @dataProvider providerForRespectEnableFields611 */612 public function respectEnableFieldsSettingGeneratesCorrectStatement($mode, $respectEnableFields, $expectedSql)613 {614 $tableName = 'tx_foo_table';615 $GLOBALS['TCA'][$tableName]['ctrl'] = [616 'enablecolumns' => [617 'disabled' => 'disabled_column',618 'starttime' => 'starttime_column'619 ],620 'delete' => 'deleted_column'621 ];622 // simulate time for backend enable fields623 $GLOBALS['SIM_ACCESS_TIME'] = 1451779200;624 // simulate time for frontend (PageRepository) enable fields625 $dateAspect = new DateTimeAspect(new \DateTimeImmutable('@1451779200'));626 $context = new Context(['date' => $dateAspect]);627 GeneralUtility::setSingletonInstance(Context::class, $context);628 $connectionProphet = $this->prophesize(Connection::class);629 $connectionProphet->quoteIdentifier(Argument::cetera())->willReturnArgument(0);630 $connectionProphet->getExpressionBuilder(Argument::cetera())->willReturn(631 GeneralUtility::makeInstance(ExpressionBuilder::class, $connectionProphet->reveal())632 );633 $queryBuilderProphet = $this->prophesize(QueryBuilder::class);634 $queryBuilderProphet->expr()->willReturn(635 GeneralUtility::makeInstance(ExpressionBuilder::class, $connectionProphet->reveal())636 );637 $queryBuilderProphet->createNamedParameter(Argument::cetera())->willReturnArgument(0);638 $connectionPoolProphet = $this->prophesize(ConnectionPool::class);639 $connectionPoolProphet->getQueryBuilderForTable(Argument::any($tableName, 'pages'))->willReturn($queryBuilderProphet->reveal());640 $connectionPoolProphet->getConnectionForTable(Argument::any($tableName, 'pages'))->willReturn($connectionProphet->reveal());641 GeneralUtility::addInstance(ConnectionPool::class, $connectionPoolProphet->reveal());642 GeneralUtility::addInstance(ConnectionPool::class, $connectionPoolProphet->reveal());643 /** @var \TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings $mockQuerySettings */644 $mockQuerySettings = $this->getMockBuilder(Typo3QuerySettings::class)645 ->setMethods(['dummy'])646 ->disableOriginalConstructor()647 ->getMock();648 $mockQuerySettings->setIgnoreEnableFields(!$respectEnableFields);649 $mockQuerySettings->setIncludeDeleted(!$respectEnableFields);650 if ($mode === 'FE') {651 $GLOBALS['TYPO3_REQUEST'] = (new ServerRequest())652 ->withAttribute('applicationType', SystemEnvironmentBuilder::REQUESTTYPE_FE);...

Full Screen

Full Screen

FormMiddlewareCest.php

Source:FormMiddlewareCest.php Github

copy

Full Screen

...24{25 public function testNotWritableLogDir(\UnitTester $I)26 {27 $prophet = new Prophet();28 $appState = $prophet->prophesize(AppState::class);29 $appState->getMiddlewareConfig()->willReturn([30 'form' => ['form1' => ['handlers' => [['logHandlerConfig', 'type' => 'log']]]],31 ]);32 $fs = new FileSystem();33 $fs->createDirectory('/sites/www.example.com/var/log', true, 0);34 $appState->getSiteDir()->willReturn($fs->path('/sites/www.example.com'));35 $mw = $this->getMw($appState, $prophet);36 $I->expectThrowable(LogDirectoryNotWritableException::class, function () use ($mw) {37 $mw(new ServerRequest(), new Response(), function () {38 });39 });40 }41 public function testInvalidFormName(\UnitTester $I)42 {43 $prophet = new Prophet();44 $appState = $prophet->prophesize(AppState::class);45 $appState->getMiddlewareConfig()->willReturn(['form' => ['invalid-form-name!' => ['handlers' => [['logHandlerConfig', 'type' => 'log']],46 ]]]);47 $appState->getScheme()->willReturn('http');48 $csrfTokenGenerator = $prophet->prophesize(CsrfTokenGenerator::class);49 $csrfTokenGenerator->generateToken()->willReturn('token');50 $formValidator = $prophet->prophesize(FormValidator::class);51 $handlerFactory = $prophet->prophesize(FormHandlerFactory::class);52 $translatorFactory = $prophet->prophesize(TranslatorFactory::class);53 $siteTranslatorFactory = $prophet->prophesize(SiteTranslatorFactory::class);54 $fs = new FileSystem();55 $fs->createDirectory('/sites/www.example.com/var/log', true);56 $appState->getSiteDir()->willReturn($fs->path('/sites/www.example.com'));57 $mw = new FormMiddleware(58 $appState->reveal(),59 $csrfTokenGenerator->reveal(),60 $formValidator->reveal(),61 $handlerFactory->reveal(),62 $translatorFactory->reveal(),63 $siteTranslatorFactory->reveal(),64 'var/log'65 );66 $I->expectThrowable(InvalidFormNameException::class, function () use ($mw) {67 $mw(new ServerRequest(), new Response(), function () {68 return new Response();69 });70 });71 }72 public function testValidFormName(\UnitTester $I)73 {74 $prophet = new Prophet();75 $appState = $prophet->prophesize(AppState::class);76 $appState->getMiddlewareConfig()->willReturn(['form' => ['valid_form_n4m3' => ['handlers' => [['logHandlerConfig', 'type' => 'log']],77 ]]]);78 $appState->getScheme()->willReturn('http');79 $appState->setForm(['valid_form_n4m3' => [80 'data' => ['csrf_token' => 'token'],81 ]])->shouldBeCalled();82 $fs = new FileSystem();83 $fs->createDirectory('/sites/www.example.com/var/log', true);84 $appState->getSiteDir()->willReturn($fs->path('/sites/www.example.com'));85 $csrfTokenGenerator = $prophet->prophesize(CsrfTokenGenerator::class);86 $csrfTokenGenerator->generateToken()->willReturn('token');87 $formValidator = $prophet->prophesize(FormValidator::class);88 $handlerFactory = $prophet->prophesize(FormHandlerFactory::class);89 $translatorFactory = $prophet->prophesize(TranslatorFactory::class);90 $siteTranslatorFactory = $prophet->prophesize(SiteTranslatorFactory::class);91 $mw = new FormMiddleware(92 $appState->reveal(),93 $csrfTokenGenerator->reveal(),94 $formValidator->reveal(),95 $handlerFactory->reveal(),96 $translatorFactory->reveal(),97 $siteTranslatorFactory->reveal(),98 'var/log'99 );100 try {101 $mw(new ServerRequest(), new Response(), function () {102 return new Response();103 });104 } catch (InvalidFormNameException $ex) {105 $I->fail('Unexpected exception InvalidFormNameException');106 }107 }108 public function testPassIfConfigNotPresent(\UnitTester $I)109 {110 $prophet = new Prophet();111 $appState = $prophet->prophesize(AppState::class);112 $appState->getMiddlewareConfig()->willReturn([]);113 $appState->getScheme()->willReturn('http');114 $csrfTokenGenerator = $prophet->prophesize(CsrfTokenGenerator::class);115 $formValidator = $prophet->prophesize(FormValidator::class);116 $handlerFactory = $prophet->prophesize(FormHandlerFactory::class);117 $translatorFactory = $prophet->prophesize(TranslatorFactory::class);118 $translatorFactory->getTranslator(new TypeToken('string'))->willReturn(new Translator('en'));119 $siteTranslatorFactory = $prophet->prophesize(SiteTranslatorFactory::class);120 $siteTranslatorFactory->getTranslator(new TypeToken('string'))->willReturn(new Translator('en'));121 $mw = new FormMiddleware(122 $appState->reveal(),123 $csrfTokenGenerator->reveal(),124 $formValidator->reveal(),125 $handlerFactory->reveal(),126 $translatorFactory->reveal(),127 $siteTranslatorFactory->reveal(),128 'var/log'129 );130 $mw(new ServerRequest(), new Response(), function () {131 return new Response();132 });133 $I->assertTrue(true);134 }135 public function testPassIfFieldsMapNotPresent(\UnitTester $I)136 {137 $prophet = new Prophet();138 $appState = $prophet->prophesize(AppState::class);139 $appState->setForm(new TypeToken('array'))->shouldBeCalled();140 $appState->getScheme()->willReturn('http');141 $appState->getLocale()->willReturn('en');142 $appState->getMiddlewareConfig()->willReturn([143 'form' => [144 'form1' => [145 'success_flash_message' => 'flash_message',146 'handlers' => [147 ['formHandler', 'type' => 'handlerType'],148 ],149 ],150 ],151 ]);152 $csrfTokenGenerator = $prophet->prophesize(CsrfTokenGenerator::class);153 $csrfTokenGenerator->generateToken()->willReturn('token');154 $formValidator = $prophet->prophesize(FormValidator::class);155 $formValidator156 ->validate([], [], new TypeToken('array'), new TypeToken('string'), new TypeToken(Translator::class), null)157 ->shouldBeCalled();158 $formValidator->getFlashMessage()->willReturn('flash_message')->shouldBeCalled();159 $formValidator->getFlashMessageType()->willReturn('success')->shouldBeCalled();160 $formValidator->getErrors()->willReturn([])->shouldBeCalled();161 $handlerFactory = $prophet->prophesize(FormHandlerFactory::class);162 $translatorFactory = $prophet->prophesize(TranslatorFactory::class);163 $translatorFactory->getTranslator(new TypeToken('string'))->willReturn(new Translator('en'));164 $siteTranslatorFactory = $prophet->prophesize(SiteTranslatorFactory::class);165 $siteTranslatorFactory->getTranslator(new TypeToken('string'))->willReturn(new Translator('en'));166 $mw = new FormMiddleware(167 $appState->reveal(),168 $csrfTokenGenerator->reveal(),169 $formValidator->reveal(),170 $handlerFactory->reveal(),171 $translatorFactory->reveal(),172 $siteTranslatorFactory->reveal(),173 'var/log'174 );175 $mw($this->getRequest()->withCookieParams(['twigyard_csrf_token' => 'token']), new Response(), function () {176 return new Response();177 });178 $I->assertTrue(true);179 }180 public function setCookieAndCsrfOnGetRequest(\UnitTester $I, $scheme = 'http', $secure = false)181 {182 $prophet = new Prophet();183 $appState = $prophet->prophesize(AppState::class);184 $appState->setForm(['form1' => [185 'data' => ['csrf_token' => 'token'],186 'flash_message' => 'Flash message',187 'flash_message_type' => 'success',188 ]])->shouldBeCalled();189 $appState->getScheme()->willReturn($scheme);190 $fs = $this->getFs();191 $appState->getSiteDir()->willReturn($fs->path('/sites/www.example.com'));192 $mw = $this->getMw($appState, $prophet);193 $request = (new ServerRequest())->withCookieParams([194 'twigyard_flash_message' => 'Flash message',195 'twigyard_flash_message_type' => 'success',196 ]);197 $response = $mw($request, new Response(), function () {198 return new Response();199 });200 $prophet->checkPredictions();201 $flashMessageCookie = SetCookies::fromResponse($response)->get('twigyard_flash_message');202 $flashMessageTypeCookie = SetCookies::fromResponse($response)->get('twigyard_flash_message_type');203 $csrfTokenCookie = SetCookies::fromResponse($response)->get('twigyard_csrf_token');204 $I->assertEquals('token', $csrfTokenCookie->getValue());205 $I->assertEquals(null, $flashMessageCookie->getValue());206 $I->assertEquals(null, $flashMessageTypeCookie->getValue());207 $I->assertEquals($secure, $csrfTokenCookie->getSecure());208 $I->assertEquals($secure, $flashMessageCookie->getSecure());209 $I->assertEquals($secure, $flashMessageTypeCookie->getSecure());210 }211 public function setCookieAndCsrfOnHttpsGetRequest(\UnitTester $I)212 {213 $this->setCookieAndCsrfOnGetRequest($I, 'https', true);214 }215 public function validatePostRequestValidData(\UnitTester $I)216 {217 $this->validateWithValidData($I);218 }219 public function validatePostRequestValidDataAnchorAndFlashSuccessMultilang(\UnitTester $I)220 {221 $this->validateWithValidData($I, 'anchor-name', 'custom success flash message', true);222 }223 public function validatePostRequestInvalidData(\UnitTester $I)224 {225 $prophet = new Prophet();226 $appState = $this->getAppState($prophet);227 $appState->setForm(['form1' => [228 'data' => ['csrf_token' => 'token', 'field1' => 'value1'],229 'flash_message' => 'Flash message',230 'flash_message_type' => 'error-validation',231 'errors' => [],232 ]])->shouldBeCalled();233 $appState->getScheme()->willReturn('http');234 $appState->getLocale()->willReturn('en');235 $fs = $this->getFs();236 $appState->getSiteDir()->willReturn($fs->path('/sites/www.example.com'));237 $formValidator = $prophet->prophesize(FormValidator::class);238 $formValidator239 ->validate(240 [],241 [],242 ['csrf_token' => 'token', 'field1' => 'value1'],243 'invalid',244 Argument::type(Translator::class),245 null246 )247 ->willReturn(false);248 $formValidator->getErrors()->willReturn([]);249 $formValidator->getFlashMessage()->willReturn('Flash message');250 $formValidator->getFlashMessageType()->willReturn('error-validation')->shouldBeCalled();251 $mw = $this->getMw($appState, $prophet, $formValidator, $this->getHandlerFactory($prophet));252 $request = $this->getRequest()->withCookieParams(['twigyard_csrf_token' => 'invalid']);253 $response = $mw($request, new Response(), function () {254 return new Response();255 });256 $csrfToken = SetCookies::fromResponse($response)->get('twigyard_csrf_token')->getValue();257 $I->assertEquals('token', $csrfToken);258 }259 public function refreshCsrfToken(\UnitTester $I)260 {261 $prophet = new Prophet();262 $appState = $this->getAppState($prophet);263 $appState->setForm(['form1' => [264 'data' => ['csrf_token' => 'token', 'field1' => 'value1'],265 ]])->shouldBeCalled();266 $appState->getScheme()->willReturn('http');267 $appState->getLocale()->willReturn('en');268 $fs = $this->getFs();269 $appState->getSiteDir()->willReturn($fs->path('/sites/www.example.com'));270 $appState->isSingleLanguage()->willReturn(true);271 $formValidator = $prophet->prophesize(FormValidator::class);272 $formValidator273 ->validate(274 [],275 [],276 ['csrf_token' => 'old_token', 'field1' => 'value1'],277 'old_token',278 Argument::type(Translator::class),279 null280 )281 ->willReturn(true);282 $mw = $this->getMw($appState, $prophet, $formValidator, $this->getHandlerFactory($prophet, 'old_token'));283 $request = $this->getRequest()284 ->withCookieParams(['twigyard_csrf_token' => 'old_token'])285 ->withMethod('post')286 ->withParsedBody(['form1' => ['csrf_token' => 'old_token', 'field1' => 'value1']]);287 $response = $mw($request, new Response(), function () {288 return null;289 });290 $I->assertNotNull($response);291 $I->assertEquals(302, $response->getStatusCode());292 }293 /**294 * @param \Prophecy\Prophecy\ObjectProphecy $appState295 * @param \Prophecy\Prophet $prophet296 * @param \Prophecy\Prophecy\ObjectProphecy $formValidator297 * @param \Prophecy\Prophecy\ObjectProphecy $handlerFactory298 * @param array $confParams299 * @return FormMiddleware300 */301 private function getMw(302 $appState,303 $prophet,304 $formValidator = null,305 $handlerFactory = null,306 array $confParams = null307 ) {308 $config = ['form' => [309 'form1' => [310 'handlers' => [['emailHandlerConfig', 'type' => 'email'], ['logHandlerConfig', 'type' => 'log']],311 'fields' => [],312 ],313 ]];314 if (!empty($confParams['anchor'])) {315 $config['form']['form1']['anchor'] = $confParams['anchor'];316 }317 if (!empty($confParams['success_flash_message'])) {318 $config['form']['form1']['success_flash_message'] = $confParams['success_flash_message'];319 }320 $appState->getMiddlewareConfig()->willReturn($config);321 $csrfTokenGenerator = $prophet->prophesize(CsrfTokenGenerator::class);322 $csrfTokenGenerator->generateToken()->willReturn('token');323 $formValidator = $formValidator ? $formValidator : $prophet->prophesize(FormValidator::class);324 $handlerFactory = $handlerFactory ? $handlerFactory : $prophet->prophesize(FormHandlerFactory::class);325 $translatorFactory = $prophet->prophesize(TranslatorFactory::class);326 $translatorFactory->getTranslator(new TypeToken('string'))->willReturn(new Translator('en'));327 $siteTranslatorFactory = $prophet->prophesize(SiteTranslatorFactory::class);328 $siteTranslatorFactory->getTranslator(new TypeToken('string'), new TypeToken('string'))329 ->willReturn(new Translator('en'));330 return new FormMiddleware(331 $appState->reveal(),332 $csrfTokenGenerator->reveal(),333 $formValidator->reveal(),334 $handlerFactory->reveal(),335 $translatorFactory->reveal(),336 $siteTranslatorFactory->reveal(),337 'var/log'338 );339 }340 /**341 * @param string $token342 * @return \Prophecy\Prophecy\ObjectProphecy343 */344 private function getHandlerFactory(Prophet $prophet, $token = 'token')345 {346 $emailHandler = $prophet->prophesize(HandlerInterface::class);347 $emailHandler->handle(['csrf_token' => $token, 'field1' => 'value1'])->shouldBeCalled();348 $logHandler = $prophet->prophesize(LogHandler::class);349 $logHandler->handle(new TypeToken('array'))->shouldBeCalled();350 $handlerFactory = $prophet->prophesize(FormHandlerFactory::class);351 $handlerFactory->build(['emailHandlerConfig', 'type' => 'email'])->willReturn($emailHandler->reveal());352 $handlerFactory->build(['logHandlerConfig', 'type' => 'log'])->willReturn($logHandler->reveal());353 return $handlerFactory;354 }355 /**356 * @return \Prophecy\Prophecy\ObjectProphecy357 */358 private function getAppState(Prophet $prophet)359 {360 $appState = $prophet->prophesize(AppState::class);361 $appState->getForm()->willReturn(['form1' => ['data' => ['csrf_token' => 'token']]]);362 return $appState;363 }364 /**365 * @return \Psr\Http\Message\RequestInterface366 */367 private function getRequest()368 {369 return (new ServerRequest(['REMOTE_ADDR' => '127.0.0.1']))370 ->withMethod('pOsT') // Ensure method name case gets converted371 ->withParsedBody(['form1' => ['csrf_token' => 'token', 'field1' => 'value1']])372 ->withUri((new Uri())->withPath('/form/page'));373 }374 /**375 * @param string $anchor376 * @param string $successFlashMessage377 * @param null $isMultiLang378 */379 private function validateWithValidData(380 \UnitTester $I,381 $anchor = null,382 $successFlashMessage = null,383 $isMultiLang = null384 ) {385 $prophet = new Prophet();386 $appState = $this->getAppState($prophet);387 $formAppState = ['form1' => ['data' => ['csrf_token' => 'token', 'field1' => 'value1']]];388 if ($anchor) {389 $formAppState['form1']['anchor'] = $anchor;390 }391 $appState->setForm($formAppState)->shouldBeCalled();392 $appState->getScheme()->willReturn('http');393 $appState->getLocale()->willReturn('en');394 $fs = $this->getFs();395 $appState->getSiteDir()->willReturn($fs->path('/sites/www.example.com'));396 $appState->isSingleLanguage()->willReturn(true);397 if ($isMultiLang) {398 $appState->getLanguageCode()->willReturn('cs');399 $appState->isSingleLanguage()->willReturn(false);400 }401 $formValidator = $prophet->prophesize(FormValidator::class);402 $formValidator403 ->validate([], [], ['csrf_token' => 'token', 'field1' => 'value1'], 'token', Argument::type(Translator::class), null)404 ->willReturn(true);405 $config = [];406 if ($anchor) {407 $config['anchor'] = $anchor;408 }409 if ($successFlashMessage) {410 $config['success_flash_message'] = $successFlashMessage;411 }412 $mw = $this->getMw($appState, $prophet, $formValidator, $this->getHandlerFactory($prophet), $config);413 $request = $this->getRequest()->withCookieParams(['twigyard_csrf_token' => 'token']);414 $response = $mw($request, new Response(), function () {415 return new Response();...

Full Screen

Full Screen

TcaSelectTreeItemsTest.php

Source:TcaSelectTreeItemsTest.php Github

copy

Full Screen

...47 * the testsuite.48 */49 protected function mockDatabaseConnection()50 {51 $connectionProphet = $this->prophesize(Connection::class);52 $connectionProphet->quote(Argument::cetera())->will(function ($arguments) {53 return "'" . $arguments[0] . "'";54 });55 $connectionProphet->quoteIdentifier(Argument::cetera())->will(function ($arguments) {56 return '`' . $arguments[0] . '`';57 });58 /** @var Statement|ObjectProphecy $statementProphet */59 $statementProphet = $this->prophesize(Statement::class);60 $statementProphet->fetch()->shouldBeCalled();61 $restrictionProphet = $this->prophesize(DefaultRestrictionContainer::class);62 $restrictionProphet->removeAll()->willReturn($restrictionProphet->reveal());63 $restrictionProphet->add(Argument::cetera())->willReturn($restrictionProphet->reveal());64 $queryBuilderProphet = $this->prophesize(QueryBuilder::class);65 $queryBuilderProphet->expr()->willReturn(66 GeneralUtility::makeInstance(ExpressionBuilder::class, $connectionProphet->reveal())67 );68 $queryBuilderProphet->getRestrictions()->willReturn($restrictionProphet->reveal());69 $queryBuilderProphet->quoteIdentifier(Argument::cetera())->will(function ($arguments) {70 return '`' . $arguments[0] . '`';71 });72 $connectionPoolProphet = $this->prophesize(ConnectionPool::class);73 $connectionPoolProphet->getConnectionForTable('foreignTable')74 ->willReturn($connectionProphet->reveal());75 $connectionPoolProphet->getQueryBuilderForTable('foreignTable')76 ->shouldBeCalled()77 ->willReturn($queryBuilderProphet->reveal());78 $queryBuilderProphet->select('foreignTable.uid')79 ->shouldBeCalled()80 ->willReturn($queryBuilderProphet->reveal());81 $queryBuilderProphet->from('foreignTable')82 ->shouldBeCalled()83 ->willReturn($queryBuilderProphet->reveal());84 $queryBuilderProphet->from('pages')85 ->shouldBeCalled()86 ->willReturn($queryBuilderProphet->reveal());87 $queryBuilderProphet->where('')88 ->shouldBeCalled()89 ->willReturn($queryBuilderProphet->reveal());90 $queryBuilderProphet->andWhere(' 1=1')91 ->shouldBeCalled()92 ->willReturn($queryBuilderProphet->reveal());93 $queryBuilderProphet->andWhere('`pages.uid` = `foreignTable.pid`')94 ->shouldBeCalled()95 ->willReturn($queryBuilderProphet->reveal());96 $queryBuilderProphet->execute()97 ->shouldBeCalled()98 ->willReturn($statementProphet->reveal());99 // Two instances are needed due to the push/pop behavior of addInstance()100 GeneralUtility::addInstance(ConnectionPool::class, $connectionPoolProphet->reveal());101 GeneralUtility::addInstance(ConnectionPool::class, $connectionPoolProphet->reveal());102 }103 /**104 * @test105 */106 public function addDataAddsTreeConfigurationForSelectTreeElement()107 {108 $GLOBALS['TCA']['foreignTable'] = [];109 $iconFactoryProphecy = $this->prophesize(IconFactory::class);110 GeneralUtility::addInstance(IconFactory::class, $iconFactoryProphecy->reveal());111 GeneralUtility::addInstance(IconFactory::class, $iconFactoryProphecy->reveal());112 $fileRepositoryProphecy = $this->prophesize(FileRepository::class);113 $fileRepositoryProphecy->findByRelation(Argument::cetera())->shouldNotBeCalled();114 GeneralUtility::setSingletonInstance(FileRepository::class, $fileRepositoryProphecy->reveal());115 /** @var BackendUserAuthentication|ObjectProphecy $backendUserProphecy */116 $backendUserProphecy = $this->prophesize(BackendUserAuthentication::class);117 $GLOBALS['BE_USER'] = $backendUserProphecy->reveal();118 $backendUserProphecy->getPagePermsClause(Argument::cetera())->willReturn(' 1=1');119 $languageService = $this->prophesize(LanguageService::class);120 $GLOBALS['LANG'] = $languageService->reveal();121 $languageService->sL(Argument::cetera())->willReturnArgument(0);122 $this->mockDatabaseConnection();123 /** @var DatabaseTreeDataProvider|ObjectProphecy $treeDataProviderProphecy */124 $treeDataProviderProphecy = $this->prophesize(DatabaseTreeDataProvider::class);125 GeneralUtility::addInstance(DatabaseTreeDataProvider::class, $treeDataProviderProphecy->reveal());126 /** @var TableConfigurationTree|ObjectProphecy $treeDataProviderProphecy */127 $tableConfigurationTreeProphecy = $this->prophesize(TableConfigurationTree::class);128 GeneralUtility::addInstance(TableConfigurationTree::class, $tableConfigurationTreeProphecy->reveal());129 $tableConfigurationTreeProphecy->setDataProvider(Argument::cetera())->shouldBeCalled();130 $tableConfigurationTreeProphecy->setNodeRenderer(Argument::cetera())->shouldBeCalled();131 $tableConfigurationTreeProphecy->render()->shouldBeCalled()->willReturn(['fake', 'tree', 'data']);132 $input = [133 'tableName' => 'aTable',134 'effectivePid' => 42,135 'databaseRow' => [136 'uid' => 5,137 'aField' => '1'138 ],139 'processedTca' => [140 'columns' => [141 'aField' => [142 'config' => [143 'type' => 'select',144 'renderType' => 'selectTree',145 'treeConfig' => [146 'childrenField' => 'childrenField'147 ],148 'foreign_table' => 'foreignTable',149 'items' => [],150 'maxitems' => 1151 ],152 ],153 ],154 ],155 'selectTreeCompileItems' => true,156 ];157 $expected = $input;158 $expected['databaseRow']['aField'] = ['1'];159 $expected['processedTca']['columns']['aField']['config']['items'] = [160 'fake', 'tree', 'data',161 ];162 self::assertEquals($expected, (new TcaSelectTreeItems())->addData($input));163 }164 /**165 * @test166 */167 public function addDataHandsPageTsConfigSettingsOverToTableConfigurationTree()168 {169 $GLOBALS['TCA']['foreignTable'] = [];170 $iconFactoryProphecy = $this->prophesize(IconFactory::class);171 GeneralUtility::addInstance(IconFactory::class, $iconFactoryProphecy->reveal());172 GeneralUtility::addInstance(IconFactory::class, $iconFactoryProphecy->reveal());173 $fileRepositoryProphecy = $this->prophesize(FileRepository::class);174 $fileRepositoryProphecy->findByRelation(Argument::cetera())->shouldNotBeCalled();175 GeneralUtility::setSingletonInstance(FileRepository::class, $fileRepositoryProphecy->reveal());176 /** @var BackendUserAuthentication|ObjectProphecy $backendUserProphecy */177 $backendUserProphecy = $this->prophesize(BackendUserAuthentication::class);178 $GLOBALS['BE_USER'] = $backendUserProphecy->reveal();179 $backendUserProphecy->getPagePermsClause(Argument::cetera())->willReturn(' 1=1');180 $languageService = $this->prophesize(LanguageService::class);181 $GLOBALS['LANG'] = $languageService->reveal();182 $languageService->sL(Argument::cetera())->willReturnArgument(0);183 $this->mockDatabaseConnection();184 /** @var DatabaseTreeDataProvider|ObjectProphecy $treeDataProviderProphecy */185 $treeDataProviderProphecy = $this->prophesize(DatabaseTreeDataProvider::class);186 GeneralUtility::addInstance(DatabaseTreeDataProvider::class, $treeDataProviderProphecy->reveal());187 /** @var TableConfigurationTree|ObjectProphecy $treeDataProviderProphecy */188 $tableConfigurationTreeProphecy = $this->prophesize(TableConfigurationTree::class);189 GeneralUtility::addInstance(TableConfigurationTree::class, $tableConfigurationTreeProphecy->reveal());190 $tableConfigurationTreeProphecy->render()->willReturn([]);191 $tableConfigurationTreeProphecy->setDataProvider(Argument::cetera())->shouldBeCalled();192 $tableConfigurationTreeProphecy->setNodeRenderer(Argument::cetera())->shouldBeCalled();193 $input = [194 'tableName' => 'aTable',195 'effectivePid' => 42,196 'databaseRow' => [197 'uid' => 5,198 'aField' => '1'199 ],200 'processedTca' => [201 'columns' => [202 'aField' => [...

Full Screen

Full Screen

prophesize

Using AI Code Generation

copy

Full Screen

1$prophet = new Prophet();2$prophet->prophesize('SomeClass');3$prophet->checkPredictions();4$prophet = new Prophet();5$prophet->prophesize('SomeClass');6$prophet->checkPredictions();7$prophet = new Prophet();8$prophet->prophesize('SomeClass');9$prophet->checkPredictions();10$prophet = new Prophet();11$prophet->prophesize('SomeClass');12$prophet->checkPredictions();13$prophet = new Prophet();14$prophet->prophesize('SomeClass');15$prophet->checkPredictions();16$prophet = new Prophet();17$prophet->prophesize('SomeClass');18$prophet->checkPredictions();19$prophet = new Prophet();20$prophet->prophesize('SomeClass');21$prophet->checkPredictions();22$prophet = new Prophet();23$prophet->prophesize('SomeClass');24$prophet->checkPredictions();25$prophet = new Prophet();26$prophet->prophesize('SomeClass');27$prophet->checkPredictions();28$prophet = new Prophet();29$prophet->prophesize('SomeClass');30$prophet->checkPredictions();31$prophet = new Prophet();32$prophet->prophesize('SomeClass');33$prophet->checkPredictions();

Full Screen

Full Screen

prophesize

Using AI Code Generation

copy

Full Screen

1$prophet = new Prophet();2$prophet->prophesize('ClassA');3$prophet->prophesize('ClassB');4$prophet->prophesize('ClassC');5$prophet->prophesize('ClassD');6$prophet->prophesize('ClassE');7$prophet = new Prophet();8$prophet->prophesize('ClassA');9$prophet->prophesize('ClassB');10$prophet->prophesize('ClassC');11$prophet->prophesize('ClassD');12$prophet->prophesize('ClassE');13$prophet = new Prophet();14$prophet->prophesize('ClassA');15$prophet->prophesize('ClassB');16$prophet->prophesize('ClassC');17$prophet->prophesize('ClassD');18$prophet->prophesize('ClassE');19$prophet = new Prophet();20$prophet->prophesize('ClassA');21$prophet->prophesize('ClassB');22$prophet->prophesize('ClassC');23$prophet->prophesize('ClassD');24$prophet->prophesize('ClassE');25$prophet = new Prophet();26$prophet->prophesize('ClassA');27$prophet->prophesize('ClassB');28$prophet->prophesize('ClassC');29$prophet->prophesize('ClassD');30$prophet->prophesize('ClassE');31$prophet = new Prophet();32$prophet->prophesize('ClassA');33$prophet->prophesize('ClassB');34$prophet->prophesize('ClassC');35$prophet->prophesize('ClassD');36$prophet->prophesize('ClassE');

Full Screen

Full Screen

prophesize

Using AI Code Generation

copy

Full Screen

1$prophet = new Prophet();2$hello = $prophet->prophesize('Hello');3$hello->hello()->willReturn('Hello World');4$hello->hello()->shouldBeCalled();5echo $hello->reveal()->hello();6$hello = $this->prophesize('Hello');7$hello->hello()->willReturn('Hello World');8$hello->hello()->shouldBeCalled();9echo $hello->reveal()->hello();10$prophet = new Prophet();11$hello = $prophet->prophesize('Hello');12$hello->hello()->willReturn('Hello World');13$hello->hello()->shouldBeCalled();14echo $hello->reveal()->hello();15$hello = $this->prophesize('Hello');16$hello->hello()->willReturn('Hello World');17$hello->hello()->shouldBeCalled();18echo $hello->reveal()->hello();19$prophet = new Prophet();20$hello = $prophet->prophesize('Hello');21$hello->hello()->willReturn('Hello World');22$hello->hello()->shouldBeCalled();23echo $hello->reveal()->hello();24$hello = $this->prophesize('Hello');25$hello->hello()->willReturn('Hello World');26$hello->hello()->shouldBeCalled();27echo $hello->reveal()->hello();28$prophet = new Prophet();29$hello = $prophet->prophesize('Hello');30$hello->hello()->willReturn('Hello World');31$hello->hello()->shouldBeCalled();32echo $hello->reveal()->hello();33$hello = $this->prophesize('Hello');34$hello->hello()->willReturn('Hello World');35$hello->hello()->shouldBeCalled();36echo $hello->reveal()->hello();37$prophet = new Prophet();38$hello = $prophet->prophesize('Hello');

Full Screen

Full Screen

prophesize

Using AI Code Generation

copy

Full Screen

1$prophet = new Prophet();2$prophecy = $prophet->prophesize('NonExistentClass');3$prophecy->nonExistentMethod()->willReturn('foo');4$prophet = new Prophet();5$prophecy = $prophet->prophesize('DateTime');6$prophecy->format('Y-m-d')->willReturn('2014-12-25');7$dateTime = $prophecy->reveal();8echo $dateTime->format('Y-m-d');9$prophet = new Prophet();10$prophecy = $prophet->prophesize('DateTime');11$prophecy->format('Y-m-d')->willReturn('2014-12-25');12$dateTime = $prophecy->reveal();13echo $dateTime->format('Y-m-d');14$prophet = new Prophet();15$prophecy = $prophet->prophesize('DateTime');16$prophecy->format('Y-m-d')->willReturn('2014-12-25');17$dateTime = $prophecy->reveal();18echo $dateTime->format('Y-m-d');19$prophet = new Prophet();20$prophecy = $prophet->prophesize('DateTime');21$prophecy->format('Y-m-d')->willReturn('2014-12-25');22$dateTime = $prophecy->reveal();23echo $dateTime->format('Y-m-d');24$prophet = new Prophet();

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Prophecy automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Trigger prophesize code on LambdaTest Cloud Grid

Execute automation tests with prophesize on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful