public function testContentTypeToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('ContentType needs to be completed'); $contentTypeHeader = new ContentType(); // @todo set some values, then test output $this->assertEmpty('Content-Type: xxx', $contentTypeHeader->toString()); }
/** * @param ContentTypeHeader $contentType * @param HttpRequest $request * @throws Exception\InvalidMultipartContentException if unable to detect MIME boundary */ public function __construct(ContentTypeHeader $contentType, HttpRequest $request) { if (!preg_match('/boundary=(?P<boundary>[^\\s]+)/', $contentType->getFieldValue(), $matches)) { throw new Exception\InvalidMultipartContentException(); } $this->boundary = $matches['boundary']; $this->request = $request; }
/** * Asserts response media type match with the media types defined. * * @param string $responseMediaType * @param SchemaManager $schemaManager * @param string $path percent-encoded path used on the request. * @param string $httpMethod * @param string $message */ public function assertResponseMediaTypeMatch($responseMediaType, SchemaManager $schemaManager, $path, $httpMethod, $message = '') { if (!$schemaManager->findPathInTemplates($path, $template, $params)) { throw new \RuntimeException('Request URI does not match with any swagger path definition'); } // Strip charset encoding $ctHeader = ContentType::fromString('Content-Type: ' . $responseMediaType); $responseMediaType = $ctHeader->getMediaType(); $constraint = new ResponseMediaTypeConstraint($schemaManager, $template, $httpMethod); Assert::assertThat($responseMediaType, $constraint, $message); }
public function persist(HelpReport $report) { $data = ['description' => 'Report generated via Ocramius CLI', 'files' => ['report.json' => ['content' => json_encode($report)]], 'public' => false]; $request = new Request(); $request->setUri('https://api.github.com/gists'); $request->setContent(json_encode($data)); $request->setMethod(Request::METHOD_POST); $request->getHeaders()->addHeader(ContentType::fromString('Content-Type: application/json')); $request->getHeaders()->addHeaderLine('X-Requested-With: Ocramius CLI'); $response = $this->client->send($request); if (!$response->isSuccess()) { throw new \UnexpectedValueException('Could not obtain a valid GIST from the github API'); } $response = json_decode($response->getBody(), true); return $response['html_url']; }
public function testChangeCredentialWithToken() { //complete the password recovery $text = file_get_contents(__DIR__ . '/../../../../email/test_mail.tmp'); preg_match('/\\/rest\\/forgotcredentialtoken\\/[a-zA-Z0-9]+/', $text, $match); $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod(Request::METHOD_PUT)->setContent('{"credential": "newPassword1"}')->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/json')]); $this->dispatch($match[0]); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertFalse(isset($result)); $this->assertResponseStatusCode(204); $identity = $this->documentManager->getRepository('Sds\\IdentityModule\\DataModel\\Identity')->findOneBy(['identityName' => 'toby']); $this->assertTrue(Hash::hashCredential($identity, 'newPassword1') == $identity->getCredential()); }
public function testCreateUser() { //create a user $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('POST')->setContent('{"username": "******"}')->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/json')]); $this->dispatch('/rest/user'); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertResponseStatusCode(201); $this->assertEquals('Location: /rest/user/paddington', $response->getHeaders()->get('Location')->toString()); $this->assertFalse(isset($result)); //look into the db and check the results $documentManagerUser = static::$staticServiceManager->get('doctrine.odm.documentmanager.user'); $users = $documentManagerUser->getRepository('Zoop\\ShardModule\\Test\\MultipleConnection\\TestAsset\\Document2\\User')->findAll(); $this->assertCount(1, $users); $this->assertEquals('paddington', $users[0]->getUsername()); }
public function testPost() { $request = new HttpRequest(); $request->setUri(Form::OGONE_TEST_URL); $request->setMethod(HttpRequest::METHOD_POST); $request->getPost()->set('PSPID', $this->form->getParam('PSPID')); $request->getPost()->set('orderID', $this->form->getParam('orderID')); $request->getPost()->set('amount', $this->form->getParam('amount')); $request->getPost()->set('currency', $this->form->getParam('currency')); $request->getPost()->set('language', $this->form->getParam('language')); $request->getPost()->set('CN', $this->form->getParam('CN')); $request->getPost()->set('EMAIL', $this->form->getParam('EMAIL')); $request->getPost()->set('accepturl', $this->form->getParam('accepturl')); $request->getPost()->set('declineurl', $this->form->getParam('declineurl')); $request->getPost()->set('exceptionurl', $this->form->getParam('exceptionurl')); $request->getPost()->set('cancelurl', $this->form->getParam('cancelurl')); $request->getPost()->set('SHASign', $this->form->getSha1Sign()); $request->getHeaders()->addHeader(\Zend\Http\Header\ContentType::fromString('Content-type: application/x-www-form-urlencoded')); $response = $this->httpClient->dispatch($request); $this->assertEquals(200, $response->getStatusCode(), 'Ogone response does not have the correct HTTP status code'); $this->assertSelectCount('form[name="OGONE_CC_FORM"]', 1, $response, 'Ogone response does not include the correct form'); }
public function testNewPasswordTemplate() { //first create the token $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod(Request::METHOD_POST)->setContent('{"username": "******"}')->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/json')]); $this->dispatch('/rest/recoverpasswordtoken'); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertFalse(isset($result)); $this->assertResponseStatusCode(201); $this->assertFalse($response->getHeaders()->has('Location')); //check the email $this->assertTrue(file_exists(__DIR__ . '/../../../../email/test_mail.tmp')); //second, use the code in the email to change the password $text = file_get_contents(__DIR__ . '/../../../../email/test_mail.tmp'); preg_match('/\\/rest\\/recoverpasswordtoken\\/[a-zA-Z0-9]+/', $text, $match); $this->getRequest()->setMethod('GET')->setContent('')->getHeaders()->clearHeaders(); //reset status code from last request $response->setStatusCode(200); $this->dispatch($match[0]); $response = $this->getResponse(); $this->assertResponseStatusCode(200); $this->assertTemplateName('zoop/gomi/new-password'); }
public function testOAuthClientDoesntOverrideExistingHeaders() { $mock = $this->getMock('ZendOAuth\\Http\\Utility', array('generateTimestamp', 'generateNonce')); $mock->expects($this->once())->method('generateTimestamp')->will($this->returnValue('123456789')); $mock->expects($this->once())->method('generateNonce')->will($this->returnValue('67648c83ba9a7de429bd1b773fb96091')); $token = new Token\Access(null, $mock); $token->setToken('123')->setTokenSecret('456'); $client = new OAuthClient(array('token' => $token), 'http://www.example.com'); $dummyHeader = Header\ContentType::fromString('Content-Type: application/octet-stream'); $headers = $client->getRequest()->getHeaders(); $headers->addHeaders(array($dummyHeader)); $client->prepareOAuth(); $this->assertTrue($client->getRequest()->getHeaders()->has('Content-Type')); $this->assertEquals($dummyHeader, $client->getRequest()->getHeaders()->get('Content-Type')); }
public function testPatchExistingDocumentId() { $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('PATCH')->setContent('{"name": "thomas-dean"}')->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/json')]); $this->dispatch('/rest/author/thomas'); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertResponseStatusCode(204); $this->assertFalse(isset($result)); $this->assertEquals('Location: /rest/author/thomas-dean', $response->getHeaders()->get('Location')->toString()); $this->documentManager->clear(); $author = $this->documentManager->getRepository('Zoop\\ShardModule\\Test\\TestAsset\\Document\\Author')->find('thomas'); $this->assertFalse(isset($author)); $author = $this->documentManager->getRepository('Zoop\\ShardModule\\Test\\TestAsset\\Document\\Author')->find('thomas-dean'); $this->assertTrue(isset($author)); $this->assertEquals('tommy', $author->getNickname()); $review = $this->documentManager->getRepository('Zoop\\ShardModule\\Test\\TestAsset\\Document\\Review')->find('bad-review'); $this->assertEquals('thomas-dean', $review->getAuthor()->getName()); }
public function testPatch405() { $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('PATCH')->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/json')]); $this->dispatch('/rest/batch'); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertResponseStatusCode(405); }
/** * @dataProvider multipleCriteria */ public function testReturnsMatchingMediaTypeOfFirstCriteriaToValidate($criteria) { $header = ContentType::fromString('Content-Type: application/vnd.foobar+json'); $result = $header->match($criteria); $this->assertEquals('application/vnd.*+json', $result); }
/** * Send Http request to retrieve datas * @access protected * @param string $service Service to call * @param string $type Resource type to retrieve (for search service) * @param array $parameters Parameters used for request * @throws \Zend\Http\Exception\RuntimeException * @return \stdClass */ protected function send($service, $type, $parameters) { // reset old parameters $this->getHttpClient()->resetParameters(); // setup Http headers $headers = array(ContentTypeHeader::fromString('Content-Type: ' . HttpClient::ENC_URLENCODED)); // setup HttpClient $this->getHttpClient()->setMethod(HttpRequest::METHOD_GET); $this->getHttpClient()->setParameterGet($parameters); $this->getHttpClient()->setHeaders($headers); // generate URI and set to HttpClient $this->getHttpClient()->setUri($this->generateURI($service, $type)); // get HttpResponse $this->response = $this->getHttpClient()->send(); // is HttpRequest ok ? if (!$this->response->isOk()) { // throw RuntimeException throw new ZendRuntimeException(sprintf('Invalid status code: %d', $this->response->getStatusCode())); } // return decode object return \Zend\Json\Decoder::decode($this->response->getBody()); }
public function testDeedNestedEmbeddedOneCreate() { //I something is wrong in AbstractControllerTestCase. The documentManager shouldn't have to be cleared here. $this->documentManager->clear(); $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('POST')->setContent('{"name": "samson"}')->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/json')]); $this->dispatch('/rest/game/seven-wonders/publisher/country/authors'); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertResponseStatusCode(201); $this->assertEquals('Location: /rest/game/seven-wonders/publisher/country/authors/samson', $response->getHeaders()->get('Location')->toString()); $this->assertFalse(isset($result)); $this->documentManager->clear(); $country = $this->documentManager->getRepository('Zoop\\ShardModule\\Test\\TestAsset\\Document\\Country')->find('belgum'); $this->assertEquals('samson', $country->getAuthors()[0]->getName()); }
public function testReloginWithRememberMeToken() { $authenticationService = $this->getApplicationServiceLocator()->get('Zend\\Authentication\\AuthenticationService'); //do inital login $authenticationService->login('toby', 'password1', true); //get the remember me object $rememberMeObject = $this->documentManager->getRepository('Zoop\\GatewayModule\\DataModel\\RememberMe')->findOneBy(['username' => 'toby']); //clear the authentication storage $authenticationService->getOptions()->getPerSessionStorage()->clear(); //create the remember me request cookie $series = $rememberMeObject->getSeries(); $token = $rememberMeObject->getToken(); $requestCookie = new SetCookie(); $requestCookie->setName('rememberMe'); $requestCookie->setValue("{$series}\n{$token}\ntoby"); $requestCookie->setExpires(time() + 3600); $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod(Request::METHOD_POST)->setContent('{"username": "******", "password": "******", "rememberMe": true}')->getHeaders()->addHeaders([$accept, $requestCookie, ContentType::fromString('Content-type: application/json')]); $this->dispatch('/rest/authenticated-user'); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertResponseStatusCode(200); $this->assertEquals('toby', $result['username']); $this->assertEquals('McQueen', $result['lastname']); $responseCookie = $response->getHeaders()->get('SetCookie')[0]; $this->assertEquals('rememberMe', $responseCookie->getName()); list($newSeries, $newToken, $newUsername) = explode("\n", $responseCookie->getValue()); $this->assertNotEquals($series, $newSeries); $this->assertNotEquals($token, $newToken); $this->assertEquals('toby', $newUsername); }
public function testLoginFailWithAuthenticatedIdentity() { $this->getApplicationServiceLocator()->get('Zend\\Authentication\\AuthenticationService')->login('toby', 'password'); $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod(Request::METHOD_POST)->setContent('{"identityName": "toby", "credential": "wrong password"}')->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/json')]); $this->dispatch('/rest/authenticatedIdentity'); $result = json_decode($this->getResponse()->getContent(), true); $this->assertResponseStatusCode(401); $this->assertEquals('Content-Type: application/api-problem+json', $this->getResponse()->getHeaders()->get('Content-Type')->toString()); $this->assertEquals('/exception/login-failed', $result['describedBy']); $this->assertEquals('Login failed', $result['title']); }
public function testReplaceList() { $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('PUT')->setContent('[ {"name": "dweebies", "type": "card"}, {"name": "exploding-chicken", "type": "dice"}, {"name": "kings-at-arms", "type": "card"} ]')->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/json')]); $this->dispatch('/rest/game', 'PUT'); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertResponseStatusCode(204); $this->assertFalse(isset($result)); $repository = $this->documentManager->getRepository('Sds\\DoctrineExtensionsModule\\Test\\TestAsset\\Document\\Game'); $game = $repository->find('dweebies'); $this->assertTrue(isset($game)); $game = $repository->find('exploding-chicken'); $this->assertTrue(isset($game)); $game = $repository->find('kings-at-arms'); $this->assertTrue(isset($game)); $game = $repository->find('feed-the-kitty'); $this->assertFalse(isset($game)); }
/** * Create an exception json view model, and set the HTTP status code * * @todo dispatch.error does not halt dispatch unless a response is * returned. As such, we likely need to trigger rendering as a low * priority dispatch.error event (or goto a render event) to ensure * rendering occurs, and that munging of view models occurs when * expected. * @param MvcEvent $e * @return void */ public function prepareExceptionViewModel(MvcEvent $e) { // Do nothing if no error in the event if (!($error = $e->getError())) { return; } // Do nothing if the result is a response object $result = $e->getResult(); if ($result instanceof Response) { return; } if ($error != Application::ERROR_EXCEPTION) { return; } if (!$e->getRequest() instanceof Request) { return; } $accept = $e->getRequest()->getHeaders()->get('Accept'); if (!($accept && $accept->match('application/json'))) { return; } if (!($exception = $e->getParam('exception'))) { return; } $modelData = $this->serializeException($exception); $e->setResult(new JsonModel($modelData)); $e->setError(false); $response = $e->getResponse(); if (!$response) { $response = new HttpResponse(); $e->setResponse($response); } if (isset($modelData['statusCode'])) { $response->setStatusCode($modelData['statusCode']); } else { $response->setStatusCode(500); } $response->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/api-problem+json')]); }
public function testBatchMixed() { $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('POST')->setContent('{ "request1": { "uri": "/rest/game", "method": "POST", "content": {"name": "forbidden-island", "type": "co-op"} }, "request2": { "uri": "/rest/author/harry", "method": "DELETE" }, "request3": { "uri": "/rest/game/feed-the-kitty", "method": "PUT", "content": {"type": "childrens", "author": {"$ref": "author/harry"}} }, "request4": { "uri": "/rest/game/feed-the-kitty", "method": "PATCH", "content": {"type": "kids"} } }')->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/json')]); $this->dispatch('/rest/batch'); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertResponseStatusCode(200); $this->assertEquals(201, $result['request1']['status']); $this->assertFalse(isset($result['request1']['content'])); $this->assertEquals('/rest/game/forbidden-island', $result['request1']['headers']['Location']); $this->assertEquals(204, $result['request2']['status']); $this->assertEquals(204, $result['request3']['status']); $this->assertFalse(isset($result['request3']['content'])); $this->assertEquals(204, $result['request4']['status']); $this->assertFalse(isset($result['request4']['content'])); }