/** * Method to test duplicate(). * * @param string $label * @param string $icon * @param string $id * @param string $prefix * @param string $task * * @covers \Windwalker\Bootstrap\Dropdown::duplicate * @dataProvider duplicateProvider */ public function testDuplicate($label, $icon, $id, $prefix, $task) { // Clean dropDownList property $this->refDropDownList->setValue(array()); Dropdown::duplicate($id, $prefix); $this->assertEquals(array('<li>' . '<a href = "javascript://" onclick="listItemTask(\'cb' . $id . '\', \'' . $task . '\')">' . ($icon ? '<span class="icon-' . $icon . '"></span> ' : '') . $label . '</a>' . '</li>'), $this->refDropDownList->getValue()); }
protected function doInjection($instance, $className) { $propertiesAnnotations = $this->annotationManager->getPropertiesAnnotations($className); foreach ($propertiesAnnotations as $propertyName => $annotations) { if (isset($annotations['Inject'])) { /** @var \A7\Annotations\Inject $inject */ $inject = $annotations['Inject']; $reflectionProperty = new \ReflectionProperty($instance, $propertyName); $reflectionProperty->setAccessible(true); if (isset($annotations['var'])) { $inject->setVar($annotations['var']); } $inject->isInjectObject(); if ($inject->isInjectObject()) { $reflectionProperty->setValue($instance, $this->a7->get($inject->getName())); } else { $name = $inject->getName(); if (isset($name) && isset($this->parameters[$name])) { $reflectionProperty->setValue($instance, $this->parameters[$name]); } } } } return $instance; }
/** * __set. * * Overloading method to set any $key property to $this->class or if not static, * to $this->object. * * @param $key * @param $value * @return $this */ public function __set($key, $value) { $property = new \ReflectionProperty($this->class, $key); $property->setAccessible(true); $property->isStatic() ? $property->setValue($value) : $property->setValue($this->object, $value); return $this; }
public function doMockResponse($set_minimal, $body_id, $set_title) { $restoreInstance = PMA\libraries\Response::getInstance(); // mock footer $mockFooter = $this->getMockBuilder('PMA\\libraries\\Footer')->disableOriginalConstructor()->setMethods(array('setMinimal'))->getMock(); $mockFooter->expects($this->exactly($set_minimal))->method('setMinimal')->with(); // mock header $mockHeader = $this->getMockBuilder('PMA\\libraries\\Header')->disableOriginalConstructor()->setMethods(array('setBodyId', 'setTitle', 'disableMenuAndConsole', 'addHTML'))->getMock(); $mockHeader->expects($this->exactly($body_id))->method('setBodyId')->with('loginform'); $mockHeader->expects($this->exactly($set_title))->method('setTitle')->with('Access denied!'); $mockHeader->expects($this->exactly($set_title))->method('disableMenuAndConsole')->with(); // set mocked headers and footers $mockResponse = $this->getMockBuilder('PMA\\libraries\\Response')->disableOriginalConstructor()->setMethods(array('getHeader', 'getFooter', 'addHTML', 'header', 'headersSent'))->getMock(); $mockResponse->expects($this->exactly($set_title))->method('getFooter')->with()->will($this->returnValue($mockFooter)); $mockResponse->expects($this->exactly($set_title))->method('getHeader')->with()->will($this->returnValue($mockHeader)); $mockResponse->expects($this->any())->method('headersSent')->with()->will($this->returnValue(false)); $mockResponse->expects($this->exactly($set_title * 6))->method('addHTML')->with(); $attrInstance = new ReflectionProperty('PMA\\libraries\\Response', '_instance'); $attrInstance->setAccessible(true); $attrInstance->setValue($mockResponse); $headers = array_slice(func_get_args(), 3); $header_method = $mockResponse->expects($this->exactly(count($headers)))->method('header'); call_user_func_array(array($header_method, 'withConsecutive'), $headers); try { $this->assertFalse($this->object->auth()); } finally { $attrInstance->setValue($restoreInstance); } }
/** * @expectedException \InvalidArgumentException */ public function testStringifyFail() { $ip = TestDataGenerator::ipString(); $range = new Range(new IP($ip), new IP($ip)); $mockConverter = $this->getMock('Bankiru\\IPTools\\Interfaces\\RangeConverterInterface'); $mockConverter->expects($this->once())->method('stringify')->with($this->equalTo($range))->willThrowException(new \InvalidArgumentException('INVALID RANGE')); $this->refProp->setValue(null, array($mockConverter)); $this->instance->stringify($range); $this->fail('parse should fail on invalid input'); }
public function testRemoveApiKey() { $user = User::create('Ma27', '123456', '*****@*****.**', new PhpPasswordHasher()); $p = new \ReflectionProperty($user, 'apiKey'); $p->setAccessible(true); $this->assertEmpty($user->getApiKey()); $p->setValue($user, 'key'); $this->assertNotEmpty($user->getApiKey()); $p->setValue($user, null); $this->assertEmpty($user->getApiKey()); }
public function testStreamIncludeWithRealFile() { $property = new ReflectionProperty('rex_stream', 'useRealFiles'); $property->setAccessible(true); $property->setValue(true); $content = 'foo <?php echo "bar";'; $streamUrl = rex_stream::factory('test-stream/2', $content); ob_start(); require $streamUrl; $result = ob_get_clean(); $this->assertEquals('foo bar', $result); $property->setValue(null); }
public function testGetOptions() { $this->getModel($this->validatorMock); $appStateProperty = new \ReflectionProperty('Magento\\Framework\\Session\\Config', 'options'); $appStateProperty->setAccessible(true); $original = $appStateProperty->getValue($this->config); $valueForTest = ['test' => 'test2']; $appStateProperty->setValue($this->config, $valueForTest); $this->assertEquals($valueForTest, $this->config->getOptions()); $this->assertEquals($valueForTest, $this->config->toArray()); $appStateProperty->setValue($this->config, $original); $this->assertEquals($original, $this->config->getOptions()); $this->assertEquals($original, $this->config->toArray()); }
/** * Set protected/private attribute of object * * @param object &$object Object containing attribute * @param string $attributeName Attribute name to change * @param string $value Value to set attribute to * * @return null */ public function setAttribute(&$object, $attributeName, $value) { $class = is_object($object) ? get_class($object) : $object; $reflection = new \ReflectionProperty($class, $attributeName); $reflection->setAccessible(true); $reflection->setValue($object, $value); }
/** * Constructs the exception. * @link http://php.net/manual/en/errorexception.construct.php * @param $message [optional] * @param $code [optional] * @param $severity [optional] * @param $filename [optional] * @param $lineno [optional] * @param $previous [optional] */ public function __construct($message = '', $code = 0, $severity = 1, $filename = __FILE__, $lineno = __LINE__, \Exception $previous = null) { parent::__construct($message, $code, $severity, $filename, $lineno, $previous); if (function_exists('xdebug_get_function_stack')) { $trace = array_slice(array_reverse(xdebug_get_function_stack()), 3, -1); foreach ($trace as &$frame) { if (!isset($frame['function'])) { $frame['function'] = 'unknown'; } // XDebug < 2.1.1: http://bugs.xdebug.org/view.php?id=695 if (!isset($frame['type']) || $frame['type'] === 'static') { $frame['type'] = '::'; } elseif ($frame['type'] === 'dynamic') { $frame['type'] = '->'; } // XDebug has a different key name if (isset($frame['params']) && !isset($frame['args'])) { $frame['args'] = $frame['params']; } } $ref = new \ReflectionProperty('Exception', 'trace'); $ref->setAccessible(true); $ref->setValue($this, $trace); } }
/** * setup mocks for all functions */ public function setUp() { $this->_objectHelper = new \Magento\TestFramework\Helper\ObjectManager($this); $this->_orderMock = $this->getMockBuilder('\\Magento\\Sales\\Model\\Order')->disableOriginalConstructor()->setMethods(array('__wakeup', 'getRealOrderId'))->getMock(); $this->_messageMock = $this->getMockBuilder('\\Magento\\Framework\\Message')->disableOriginalConstructor()->setMethods(array('addError'))->getMock(); $titleMock = $this->getMock('\\Magento\\Framework\\App\\Action\\Title', array('__wakeup', 'add'), array(), '', false); $viewMock = $this->getMockForAbstractClass('\\Magento\\Framework\\App\\ViewInterface'); /** * @TODO: * - Methods of object under test MUST NOT be mocked * - Protected properties MUST NOT be set from outside, inject via context passed to constructor instead */ $this->_controllerMock = $this->getMockBuilder('\\Magento\\Sales\\Controller\\Adminhtml\\Order\\View')->disableOriginalConstructor()->setMethods(array('__wakeup', '_initOrder', '_initAction', '__', 'renderLayout', '_redirect'))->getMock(); $this->_controllerMock->expects($this->any())->method('__')->will($this->returnArgument(0)); $reflectionProperty = new \ReflectionProperty('\\Magento\\Sales\\Controller\\Adminhtml\\Order', '_title'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->_controllerMock, $titleMock); $reflectionProperty->setAccessible(false); $reflectionProperty = new \ReflectionProperty('\\Magento\\Sales\\Controller\\Adminhtml\\Order', '_view'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->_controllerMock, $viewMock); $reflectionProperty->setAccessible(false); $reflectionProperty = new \ReflectionProperty('\\Magento\\Sales\\Controller\\Adminhtml\\Order', 'messageManager'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->_controllerMock, $this->_messageMock); $reflectionProperty->setAccessible(false); }
public function testValidateSetEntityAttributeValuesWithoutResource() { $product = $this->getMock('Magento\\Framework\\Model\\AbstractModel', ['someMethod', 'getResource', 'load'], [], '', false); $this->_condition->setAttribute('someAttribute'); $product->setAtribute('attribute'); $product->setId(12); $this->_configProperty->setValue($this->_condition, $this->getMock('Magento\\Eav\\Model\\Config', [], [], '', false)); $this->_entityAttributeValuesProperty->setValue($this->_condition, $this->getMock('Magento\\Eav\\Model\\Config', [], [], '', false)); $attribute = new \Magento\Framework\DataObject(); $attribute->setBackendType('multiselect'); $newResource = $this->getMock('\\Magento\\Catalog\\Model\\ResourceModel\\Product', ['getAttribute'], [], '', false); $newResource->expects($this->any())->method('getAttribute')->with('someAttribute')->will($this->returnValue($attribute)); $newResource->_config = $this->getMock('Magento\\Eav\\Model\\Config', [], [], '', false); $product->expects($this->atLeastOnce())->method('getResource')->willReturn($newResource); $this->_entityAttributeValuesProperty->setValue($this->_condition, [1 => [''], 2 => ['option1,option2,option3'], 3 => ['option1,option2,option3']]); $this->assertFalse($this->_condition->validate($product)); $attribute = new \Magento\Framework\DataObject(); $attribute->setBackendType(null); $attribute->setFrontendInput('multiselect'); $newResource = $this->getMock('\\Magento\\Catalog\\Model\\ResourceModel\\Product', ['getAttribute'], [], '', false); $newResource->expects($this->any())->method('getAttribute')->with('someAttribute')->will($this->returnValue($attribute)); $newResource->_config = $this->getMock('Magento\\Eav\\Model\\Config', [], [], '', false); $product->setResource($newResource); $product->setId(1); $product->setData('someAttribute', 'value'); $this->assertFalse($this->_condition->validate($product)); }
private function enableOpenSSL() { $ref = new \ReflectionProperty('Bitpay\\Util\\SecureRandom', 'hasOpenSSL'); $ref->setAccessible(true); $ref->setValue(null); $ref->setAccessible(false); }
/** * @param object $object * @param string $property * @param mixed $value * @return $this */ protected function setProperty($object, $property, $value) { $reflection = new \ReflectionProperty(get_class($object), $property); $reflection->setAccessible(true); $reflection->setValue($object, $value); return $this; }
/** * @covers ArticleQualityService::searchPercentile */ public function testSearchPercentile() { $mock = $this->getMockBuilder("\\ArticleQualityService")->disableOriginalConstructor()->setMethods(['__construct'])->getMock(); $refl = new \ReflectionMethod($mock, 'searchPercentile'); $refl->setAccessible(true); $prop = new \ReflectionProperty($mock, 'percentiles'); $prop->setAccessible(true); $prop->setValue($mock, [1 => 0.1, 2 => 0.2, 3 => 0.3, 4 => 0.4]); $this->assertEquals(2, $refl->invoke($mock, 0.25)); $this->assertEquals(4, $refl->invoke($mock, 0.5)); $this->assertEquals(1, $refl->invoke($mock, 0.05)); $prop->setValue($mock, [-1 => -0.1, 0 => 0.05, 1 => 0.8]); $this->assertEquals(-1, $refl->invoke($mock, -2)); $this->assertEquals(0, $refl->invoke($mock, 0.4)); $this->assertEquals(1, $refl->invoke($mock, 1)); }
protected function updateRevision(AbstractRevision $revision, AbstractRevision $previous = null) { $this->contentLengthProperty->setValue($revision, $this->calcContentLength($revision)); if ($previous !== null) { $this->previousContentLengthProperty->setValue($revision, $this->calcContentLength($previous)); } }
public function testIndex() { $logger = $this->getMock('Psr\\Log\\LoggerInterface'); $logger->expects($this->once())->method('info'); $controller = new Controller($logger); $prop = new \ReflectionProperty(__NAMESPACE__ . '\\Controller', 'response'); $prop->setAccessible(true); $prop->setValue($controller, new \SS_HTTPResponse()); $req = new \SS_HTTPRequest('GET', '/'); $req->setBody(<<<JSON { "csp-report": { "document-uri": "http://example.com/signup.html", "referrer": "", "blocked-uri": "http://example.com/css/style.css", "violated-directive": "style-src cdn.example.com", "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports" } } JSON ); $response = $controller->index($req); $this->assertEquals(204, $response->getStatusCode()); $this->assertEquals('', $response->getBody()); }
/** * ExpressionLanguage constructor. * * @param ParserCacheInterface|null $cache The cache * @param array $providers Providers */ public function __construct(ParserCacheInterface $cache = null, array $providers = array()) { parent::__construct($cache, $providers); $reflectionProperty = new \ReflectionProperty('\\Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage', 'lexer'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this, new Lexer()); }
public function tearDown() { $property = new \ReflectionProperty('\\Magento\\Setup\\Module\\I18n\\ServiceLocator', '_dictionaryGenerator'); $property->setAccessible(true); $property->setValue(null); $property->setAccessible(false); }
/** * @covers ::getContextValue * @dataProvider providerGetContextValue */ public function testGetContextValue($expected, $context_value, $is_required, $data_type) { // Mock a Context object. $mock_context = $this->getMockBuilder('Drupal\\Component\\Plugin\\Context\\Context')->disableOriginalConstructor()->setMethods(array('getContextDefinition'))->getMock(); // If the context value exists, getContextValue() behaves like a normal // getter. if ($context_value) { // Set visibility of contextValue. $ref_context_value = new \ReflectionProperty($mock_context, 'contextValue'); $ref_context_value->setAccessible(TRUE); // Set contextValue to a testable state. $ref_context_value->setValue($mock_context, $context_value); // Exercise getContextValue(). $this->assertEquals($context_value, $mock_context->getContextValue()); } else { // Create a mock definition. $mock_definition = $this->getMockBuilder('Drupal\\Component\\Plugin\\Context\\ContextDefinitionInterface')->setMethods(array('isRequired', 'getDataType'))->getMockForAbstractClass(); // Set expectation for isRequired(). $mock_definition->expects($this->once())->method('isRequired')->willReturn($is_required); // Set expectation for getDataType(). $mock_definition->expects($this->exactly($is_required ? 1 : 0))->method('getDataType')->willReturn($data_type); // Set expectation for getContextDefinition(). $mock_context->expects($this->once())->method('getContextDefinition')->willReturn($mock_definition); // Set expectation for exception. if ($is_required) { $this->setExpectedException('Drupal\\Component\\Plugin\\Exception\\ContextException', sprintf("The %s context is required and not present.", $data_type)); } // Exercise getContextValue(). $this->assertEquals($context_value, $mock_context->getContextValue()); } }
function reflectProperty($class, $property) { $propInfo = new ReflectionProperty($class, $property); echo "**********************************\n"; echo "Reflecting on property {$class}::{$property}\n\n"; echo "__toString():\n"; var_dump($propInfo->__toString()); echo "export():\n"; var_dump(ReflectionProperty::export($class, $property, true)); echo "export():\n"; var_dump(ReflectionProperty::export($class, $property, false)); echo "getName():\n"; var_dump($propInfo->getName()); echo "isPublic():\n"; var_dump($propInfo->isPublic()); echo "isPrivate():\n"; var_dump($propInfo->isPrivate()); echo "isProtected():\n"; var_dump($propInfo->isProtected()); echo "isStatic():\n"; var_dump($propInfo->isStatic()); $instance = new $class(); if ($propInfo->isPublic()) { echo "getValue():\n"; var_dump($propInfo->getValue($instance)); $propInfo->setValue($instance, "NewValue"); echo "getValue() after a setValue():\n"; var_dump($propInfo->getValue($instance)); } echo "\n**********************************\n"; }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $property = new \ReflectionProperty('Drupal\\Component\\Utility\\Html', 'seenIdsInit'); $property->setAccessible(TRUE); $property->setValue(NULL); }
/** * @param string|object $classOrObject * @param string $attributeName * @param mixed $attributeValue */ public function writeAttribute($classOrObject, $attributeName, $attributeValue) { $rp = new \ReflectionProperty($classOrObject, $attributeName); $rp->setAccessible(true); $rp->setValue($classOrObject, $attributeValue); $rp->setAccessible(false); }
/** * Makes a given model-property accessible. * * @param object $model * @param int $value * @param string $property * * @return mixed */ public function reflect($model, $value, $property = 'id') { $attribute = new \ReflectionProperty($model, $property); $attribute->setAccessible(true); $attribute->setValue($model, $value); return $model; }
public function initialize($object) { $reflectionClass = new ReflectionClass($object); $reader = new Phake_Annotation_Reader($reflectionClass); if ($this->useDoctrineParser()) { $parser = new \Doctrine\Common\Annotations\PhpParser(); } $properties = $reader->getPropertiesWithAnnotation('Mock'); foreach ($properties as $property) { $annotations = $reader->getPropertyAnnotations($property); if ($annotations['Mock'] !== true) { $mockedClass = $annotations['Mock']; } else { $mockedClass = $annotations['var']; } if (isset($parser)) { // Ignore it if the class start with a backslash if (substr($mockedClass, 0, 1) !== '\\') { $useStatements = $parser->parseClass($reflectionClass); $key = strtolower($mockedClass); if (array_key_exists($key, $useStatements)) { $mockedClass = $useStatements[$key]; } } } $reflProp = new ReflectionProperty(get_class($object), $property); $reflProp->setAccessible(true); $reflProp->setValue($object, Phake::mock($mockedClass)); } }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $request = $event->getRequest(); $this->logException($exception, sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine())); $attributes = array('_controller' => $this->controller, 'exception' => FlattenException::create($exception), 'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null, 'format' => $request->getRequestFormat()); $request = $request->duplicate(null, null, $attributes); $request->setMethod('GET'); try { $response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, false); } catch (\Exception $e) { $this->logException($e, sprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), false); $wrapper = $e; while ($prev = $wrapper->getPrevious()) { if ($exception === ($wrapper = $prev)) { throw $e; } } $prev = new \ReflectionProperty('Exception', 'previous'); $prev->setAccessible(true); $prev->setValue($wrapper, $exception); throw $e; } $event->setResponse($response); }
/** * Force connection setter injection on setup model using reflection * * @param $setup * @param $connection */ protected function _setConnectionOnInstaller($setup, $connection) { $prop = new ReflectionProperty($setup, '_conn'); $prop->setAccessible(true); $prop->setValue($setup, $connection); $prop->setAccessible(false); }
protected function openPresenter($fqa) { /** @var IntegrationTestCase|PresenterRunner $this */ $sl = $this->getContainer(); //insert fake HTTP Request for Presenter - for presenter->link() etc. $params = $sl->getParameters(); $this->fakeUrl = new Nette\Http\UrlScript(isset($params['console']['url']) ? $params['console']['url'] : 'localhost'); $sl->removeService('httpRequest'); $sl->addService('httpRequest', new HttpRequest($this->fakeUrl, NULL, [], [], [], [], PHP_SAPI, '127.0.0.1', '127.0.0.1')); /** @var Nette\Application\IPresenterFactory $presenterFactory */ $presenterFactory = $sl->getByType('Nette\\Application\\IPresenterFactory'); $name = substr($fqa, 0, $namePos = strrpos($fqa, ':')); $class = $presenterFactory->getPresenterClass($name); if (!class_exists($overriddenPresenter = 'DamejidloTests\\' . $class)) { $classPos = strrpos($class, '\\'); eval('namespace DamejidloTests\\' . substr($class, 0, $classPos) . '; class ' . substr($class, $classPos + 1) . ' extends \\' . $class . ' { ' . 'protected function startup() { if ($this->getParameter("__terminate") == TRUE) { $this->terminate(); } parent::startup(); } ' . 'public static function getReflection() { return parent::getReflection()->getParentClass(); } ' . '}'); } $this->presenter = $sl->createInstance($overriddenPresenter); $sl->callInjects($this->presenter); $app = $this->getService('Nette\\Application\\Application'); $appRefl = new \ReflectionProperty($app, 'presenter'); $appRefl->setAccessible(TRUE); $appRefl->setValue($app, $this->presenter); $this->presenter->autoCanonicalize = FALSE; $this->presenter->run(new Nette\Application\Request($name, 'GET', ['action' => substr($fqa, $namePos + 1) ?: 'default', '__terminate' => TRUE])); }
public function testSchedule() { $testIntegrationType = 'testIntegrationType'; $testConnectorType = 'testConnectorType'; $testId = 22; $integration = new Integration(); $integration->setType($testIntegrationType); $integration->setEnabled(true); $ref = new \ReflectionProperty(get_class($integration), 'id'); $ref->setAccessible(true); $ref->setValue($integration, $testId); $this->typesRegistry->addChannelType($testIntegrationType, new TestIntegrationType()); $this->typesRegistry->addConnectorType($testConnectorType, $testIntegrationType, new TestTwoWayConnector()); $that = $this; $uow = $this->getMockBuilder('Doctrine\\ORM\\UnitOfWork')->disableOriginalConstructor()->getMock(); $this->em->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($uow)); $metadataFactory = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\ClassMetadataFactory')->disableOriginalConstructor()->getMock(); $metadataFactory->expects($this->once())->method('getMetadataFor')->will($this->returnValue(new ClassMetadata('testEntity'))); $this->em->expects($this->once())->method('getMetadataFactory')->will($this->returnValue($metadataFactory)); $uow->expects($this->once())->method('persist')->with($this->isInstanceOf('JMS\\JobQueueBundle\\Entity\\Job'))->will($this->returnCallback(function (Job $job) use($that, $testId, $testConnectorType) { $expectedArgs = ['--integration=' . $testId, sprintf('--connector=testConnectorType', $testConnectorType), '--params=a:0:{}']; $that->assertEquals($expectedArgs, $job->getArgs()); })); $uow->expects($this->once())->method('computeChangeSet'); $this->scheduler->schedule($integration, $testConnectorType, [], false); }
public function __construct(InputInterface $input, OutputInterface $output) { parent::__construct($input, $output); $ref = new \ReflectionProperty(get_parent_class($this), 'lineLength'); $ref->setAccessible(true); $ref->setValue($this, 120); }