/** * @testdox Creates paginator via paginator service using request parameters. * @dataProvider providePaginatorCreationData * * * @param $paginatorName * @param $params * @param $defaultParams * @param $usePostParams * @param $expect */ public function testPaginatorCreation($paginatorName, $params, $defaultParams, $usePostParams, $expect) { if ($defaultParams) { $options = array_merge($params, $defaultParams); } else { $options = $params; } $request = new Request(); if ($usePostParams) { $request->setPost(new Parameters($params)); } else { $request->setQuery(new Parameters($params)); } $paginator = $this->getMockBuilder('\\Zend\\Paginator\\Paginator')->disableOriginalConstructor()->getMock(); $paginator->expects($this->once())->method('setCurrentPageNumber')->with($expect['page'])->will($this->returnSelf()); $paginator->expects($this->once())->method('setItemCountPerPage')->with($expect['count'])->will($this->returnSelf()); $paginator->expects($this->once())->method('setPageRange')->with($expect['range'])->will($this->returnSelf()); $paginators = $this->getMockBuilder('\\Core\\Paginator\\PaginatorService')->disableOriginalConstructor()->getMock(); $paginators->expects($this->once())->method('get')->with($paginatorName, $options)->willReturn($paginator); $sm = $this->getMockBuilder('\\Zend\\ServiceManager\\ServiceManager')->disableOriginalConstructor()->getMock(); $event = $this->getMockBuilder(CreatePaginatorEvent::class)->disableOriginalConstructor()->getMock(); $em = $this->getMockBuilder(EventManager::class)->disableOriginalConstructor()->setMethods(['getEvent', 'trigger'])->getMock(); $sm->expects($this->exactly(2))->method('get')->withConsecutive(['Core/PaginatorService'], ['Core/CreatePaginator/Events'])->willReturnOnConsecutiveCalls($paginators, $em); // check if event create paginator is triggered $em->expects($this->once())->method('getEvent')->with(CreatePaginator::EVENT_CREATE_PAGINATOR)->willReturn($event); $em->expects($this->once())->method('trigger')->with($event); $controller = $this->getMockBuilder('\\Zend\\Mvc\\Controller\\AbstractActionController')->setMethods(['getServiceLocator', 'getRequest'])->getMockForAbstractClass(); $controller->expects($this->once())->method('getRequest')->willReturn($request); $target = new CreatePaginator($sm); $target->setController($controller); $pager = false === $defaultParams ? $target($paginatorName, $usePostParams) : $target($paginatorName, $defaultParams, $usePostParams); $this->assertSame($paginator, $pager); }
public function createAjaxRequestWithSpecificPostData($postData) { $request = new Request(); $request->getHeaders()->addHeaders(['X_REQUESTED_WITH' => 'XMLHttpRequest']); $parameters = new \Zend\Stdlib\Parameters(); $parameters->fromArray($postData); $request->setPost($parameters); return $request; }
private function preparePostRequest($post) { $postRequest = new Request(); $postRequest->setMethod(Request::METHOD_POST); $postRequest->setPost($post); $postRequest->setUri($this->url); $postRequest->getHeaders()->addHeaders(['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8']); return $postRequest; }
public function testParameterRetrievalDefaultValue() { $request = new Request(); $p = new \Zend\Stdlib\Parameters(array('foo' => 'bar')); $request->setQuery($p); $request->setPost($p); $request->setFiles($p); $default = 15; $this->assertSame($default, $request->getQuery('baz', $default)); $this->assertSame($default, $request->getPost('baz', $default)); $this->assertSame($default, $request->getFiles('baz', $default)); $this->assertSame($default, $request->getHeaders('baz', $default)); $this->assertSame($default, $request->getHeader('baz', $default)); }
public function testRequestAllowsSettingOfParameterContainer() { $request = new Request(); $p = new \Zend\Stdlib\Parameters(); $request->setQuery($p); $request->setPost($p); $request->setFile($p); $request->setServer($p); $request->setEnv($p); $this->assertSame($p, $request->query()); $this->assertSame($p, $request->post()); $this->assertSame($p, $request->file()); $this->assertSame($p, $request->server()); $this->assertSame($p, $request->env()); }
public function testValidateIncomingData() { $inputFilter = new SimpleInputFilter(); $inputFilterPluginManager = $this->getMock(InputFilterPluginManager::class); $inputFilterPluginManager->expects($this->any())->method('get')->with(SimpleInputFilter::class)->willReturn($inputFilter); $request = new HttpRequest(); $request->setPost(new Parameters(['fields1' => 'value1', 'fields2' => 'value2'])); $request->setContent(json_encode(['fields3' => 'value3'])); $controller = $this->getMock(AbstractRestfulController::class); $controller->expects($this->at(0))->method('getRequest')->willReturn($request); $controller->expects($this->at(1))->method('getRequest')->willReturn($request); $plugin = new ValidateIncomingData($inputFilterPluginManager); $plugin->setController($controller); $expected = ['fields1' => 'value1', 'fields2' => 'value2', 'fields3' => 'value3']; $result = $plugin(SimpleInputFilter::class); $this->assertEquals($expected, $result); }
public function testCreate() { $userArray = array('className' => 'Sds\\DoctrineExtensionsModule\\Test\\TestAsset\\Document\\User', 'id' => 'superdweebie', 'location' => 'here', 'groups' => array(array('name' => 'groupA'), array('name' => 'groupB')), 'password' => 'secret', 'profile' => array('firstname' => 'Tim', 'lastname' => 'Roediger')); $request = new Request(); $request->setMethod(Request::METHOD_POST); $request->setPost(new Parameters($userArray)); $event = new MvcEvent(); $event->setRouteMatch(new RouteMatch(array())); $event->setApplication($this->serviceManager->get('application')); $response = null; $this->controller->setEvent($event); $consoleModel = $this->controller->dispatch($request, $response); $id = $consoleModel->getResult(); $repository = $this->documentManager->getRepository('Sds\\DoctrineExtensionsModule\\Test\\TestAsset\\Document\\User'); $this->documentManager->clear(); $user = $repository->find($id); $this->assertEquals('superdweebie', $user->getId()); $this->assertEquals('here', $user->location()); $this->assertEquals('groupA', $user->getGroups()[0]); $this->assertEquals('Tim', $user->getProfile()->getFirstName()); }
/** * @covers Application\Controller\BusstopController::pathAction */ public function testPathActionWithoutBusstop() { $entityManager = $this->getMock('Doctrine\\ORM\\EntityManager', array(), array(), '', false); $entityRepository = $this->getMock('Doctrine\\ORM\\EntityRepository', array(), array(), '', false); $busstopLeft = new BusStop(); $busstopLeft->setCode("HTM:2719"); $busstopRight = new BusStop(); $busstopRight->setCode("HTM:2901"); $params = new Parameters(array('busstopFrom' => 'HTM:2719', 'busstopTo' => 'HTM:2901')); $this->request->setMethod("POST"); $this->request->setPost($params); //find busstopfrom and busstopto $entityManager->expects($this->any())->method('getRepository')->with('Application\\Entity\\BusStop')->will($this->returnValue($entityRepository)); $entityRepository->expects($this->any())->method('findOneBy')->will($this->returnValue(null)); $this->controller->setEntityManager($entityManager); $this->routeMatch->setParam('action', 'path'); $this->routeMatch->setParam('from', 'HTM:2719'); $result = $this->controller->dispatch($this->request); $response = $this->controller->getResponse(); $this->assertEquals(200, $response->getStatusCode()); $this->assertInstanceOf('Zend\\View\\Model\\ViewModel', $result); }
public function testDeleteFeed() { $newId = 12; $this->routeMatch->setParam('action', 'delete'); $currentUserMock = $this->login(); $data = ['id' => $newId]; #Current user create mock $currentUserMock->method('getId')->will($this->returnValue(1)); #End current user create mock # Define test entity $findedText = new Text(); $findedText->setId($newId); $findedText->setUser($currentUserMock); # #emMock $emMock = $this->getEmMock(); #Mock find method $emMock->expects($this->once())->method('find')->with('Texsts\\Entity\\Text', $newId)->will($this->returnValue($findedText)); # #Mock pesist method $persistedObject = null; $emMock->expects($this->once())->method('remove')->will($this->returnCallback(function ($object) use(&$persistedObject) { $persistedObject = $object; })); # $emMock->expects($this->once())->method('flush'); $this->service->getRepository()->setEm($emMock); #end emMock $this->request->setPost(new Parameters($data)); $result = $this->controller->dispatch($this->request); $response = $this->controller->getResponse(); $this->assertEquals(200, $response->getStatusCode()); if (!$result->getVariables()['success']) { $this->fail("Fail with deleting"); } $this->assertEquals($newId, $persistedObject->getId()); }
/** * @param $uri * @param string $method * @param array $postParams * @param array $queryParams * @return mixed */ protected function sendRequest($uri, $method = HttpRequest::METHOD_GET, $postParams = array(), $queryParams = array()) { $request = new HttpRequest(); $request->setUri(self::URI_BASE . $uri); $request->setMethod($method); $request->setQuery($this->prepareParameters($queryParams)); $request->setPost($this->prepareParameters($postParams)); $response = $this->httpClient->send($request); $this->checkErrors($response); return Json::decode($response->getBody(), JSON::TYPE_ARRAY); }
public function testProcessPatchRequestWithGenericJsonMediaTypeReturnsUpdatedConfigurationKeys() { $config = ['foo' => 'FOO', 'bar' => ['baz' => 'bat'], 'baz' => 'BAZ']; $configResource = new ConfigResource($config, $this->file, $this->writer); $controller = new ConfigController($configResource); $controller->setPluginManager($this->plugins); $request = new Request(); $request->setMethod('patch'); $request->setPost(new Parameters(['bar.baz' => 'UPDATED', 'baz' => 'UPDATED'])); $request->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $controller->setRequest($request); $result = $controller->processAction(); $this->assertInternalType('array', $result); $expected = ['bar.baz' => 'UPDATED', 'baz' => 'UPDATED']; $this->assertEquals($expected, $result); }
protected function dispatchRequestAndDecodeResponse($url, $method, $data = null) { $request = new Request(); $this->lastResponse = null; $request->getHeaders()->addHeaders(array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept' => 'application/json', 'User-Agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:37.0) Gecko/20100101 Firefox/37.0')); if (!empty($this->host)) { $request->getHeaders()->addHeaders(array('Host' => $this->host)); } if (!empty($this->key)) { $request->getHeaders()->addHeaders(array('Authorization' => 'Bearer ' . $this->key)); } $request->setUri($url); $request->setMethod($method); if (is_null($data)) { $data = array(); } if (isset($this->key)) { $data["auth"] = $this->key; } if ($method == "POST" || $method == "PUT") { $request->setPost(new Parameters($data)); if (isset($this->key)) { $request->setQuery(new Parameters(array('auth' => $this->key))); } } else { $request->setQuery(new Parameters($data)); } $this->lastResponse = $this->httpClient->send($request); if ($this->lastResponse->isSuccess()) { return json_decode($this->lastResponse->getBody(), true); } else { return array('error' => true, 'headers' => array("code" => $this->lastResponse->getStatusCode(), "reasons" => $this->lastResponse->getReasonPhrase()), 'body' => json_decode($this->lastResponse->getBody(), true)); } }
public function testCollectionInputFilterIsInitializedBeforePluginRetrievesIt() { $fieldset = new TestAsset\InputFilterProviderFieldset(); $collectionSpec = ['name' => 'test_collection', 'type' => 'collection', 'options' => ['target_element' => $fieldset]]; $form = new Form(); $form->add($collectionSpec); $postData = ['test_collection' => [['test_field' => 'foo'], ['test_field' => 'bar']]]; // test POST $request = new Request(); $request->setMethod('POST'); $request->setPost(new Parameters($postData)); $this->controller->dispatch($request, $this->response); $plugin = $this->plugin; $plugin($form, '/someurl', true); $data = $form->getData(); $this->assertArrayHasKey(0, $data['test_collection']); $this->assertArrayHasKey(1, $data['test_collection']); $this->assertSame('FOO', $data['test_collection'][0]['test_field']); $this->assertSame('BAR', $data['test_collection'][1]['test_field']); // now test GET with a brand new form instance $form = new Form(); $form->add($collectionSpec); $request = new Request(); $this->controller->dispatch($request, $this->response); $plugin($form, '/someurl', true); $data = $form->getData(); $this->assertArrayHasKey(0, $data['test_collection']); $this->assertArrayHasKey(1, $data['test_collection']); $this->assertSame('FOO', $data['test_collection'][0]['test_field']); $this->assertSame('BAR', $data['test_collection'][1]['test_field']); }
protected function execute($url, $method, array $query = null, array $rawdata = null, Headers $headers = null) { $request = new Request(); // Headers $request->getHeaders()->addHeaders(array('Content-Type' => $this->getContentType())); if ($headers) { $request->getHeaders()->addHeaders($headers); } // Query if ($query) { $request->setQuery(new Parameters($query)); } $request->setUri($url)->setMethod($method); switch ($method) { case self::HTTP_VERB_POST: case self::HTTP_VERB_PUT: case self::HTTP_VERB_PATCH: if ($rawdata) { $request->setPost(new Parameters($rawdata)); } break; } $client = new HttpClient('', $this->_httpClientOptions); $adapter = $client->getAdapter(); /* @var $adapter Curl */ $secure = $request->getUri()->getScheme() == 'https'; $adapter->connect($request->getUri()->getHost(), $request->getUri()->getPort(), $secure); $ch = $adapter->getHandle(); // Set URL curl_setopt($ch, CURLOPT_URL, $request->getUriString() . '?' . $request->getQuery()->toString()); // ensure correct curl call $curlValue = true; switch ($method) { case 'GET': $curlMethod = CURLOPT_HTTPGET; break; case 'POST': $curlMethod = CURLOPT_POST; break; case 'PUT': case 'PATCH': case 'DELETE': case 'OPTIONS': case 'TRACE': case 'HEAD': $curlMethod = CURLOPT_CUSTOMREQUEST; $curlValue = $method; break; default: // For now, through an exception for unsupported request methods throw new Exception("Method '{$method}' currently not supported"); } // mark as HTTP request and set HTTP method curl_setopt($ch, CURL_HTTP_VERSION_1_1, true); curl_setopt($ch, $curlMethod, $curlValue); // ensure actual response is returned curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // set callback function if ($this->getCallbackWriteFunction() instanceof \Closure) { curl_setopt($ch, CURLOPT_WRITEFUNCTION, $this->getCallbackWriteFunction()); } // ensure headers are also returned curl_setopt($ch, CURLOPT_HEADER, false); // set callback function if ($this->getCallbackHeaderFunction() instanceof \Closure) { curl_setopt($ch, CURLOPT_HEADERFUNCTION, $this->getCallbackHeaderFunction()); } // Treating basic auth headers in a special way if ($request->getHeaders() instanceof Headers) { $headersArray = $request->getHeaders()->toArray(); if (array_key_exists('Authorization', $headersArray) && 'Basic' == substr($headersArray['Authorization'], 0, 5)) { curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERPWD, base64_decode(substr($headersArray['Authorization'], 6))); unset($headersArray['Authorization']); } // set additional headers if (!isset($headersArray['Accept'])) { $headersArray['Accept'] = ''; } $curlHeaders = array(); foreach ($headersArray as $key => $value) { $curlHeaders[] = $key . ': ' . $value; } curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders); } // POST body switch ($method) { case 'POST': case 'PUT': case 'PATCH': curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPost()->toArray()); break; } $this->_handlers[uniqid()] = $ch; end($this->_handlers); return key($this->_handlers); }
public function testForm02() { $auth = new AuthenticationService(); $result = $auth->authenticate(new TestAdapter((object) ['id' => 1, 'is_admin' => 1])); $result->isValid(); $this->routeMatch->setParam('action', 'create'); $request = new Request(); $request->setMethod(Request::METHOD_POST); $request->setPost(new Parameters(array('title' => 'Hani krummi', 'summary' => 'Hani krummi', 'body' => 'Hani krummi', 'venue' => 'Hani krummi', 'authors' => [1, 2, 3]))); $response = $this->controller->getResponse(); $this->assertEquals(302, $response->getStatusCode()); }
public function testAdminCanUpdateAndThisIsNoAdmin() { $auth = new AuthenticationService(); $result = $auth->authenticate(new TestAdapter((object) ['id' => 2])); $result->isValid(); $this->routeMatch->setParam('action', 'update'); $this->routeMatch->setParam('id', 'name1'); $request = new Request(); $request->setMethod(Request::METHOD_POST); $request->setPost(new Parameters(array())); $result = $this->controller->dispatch($request); $response = $this->controller->getResponse(); $this->assertEquals(401, $response->getStatusCode()); }