public function testAcceptToStringReturnsHeaderFormattedString() { $this->markTestIncomplete('Accept needs to be completed'); $acceptHeader = new Accept(); // @todo set some values, then test output $this->assertEmpty('Accept: xxx', $acceptHeader->toString()); }
public function testGetDojoSrc() { $accept = new Accept(); $accept->addMediaType('application/javascript'); $this->getRequest()->setMethod('GET')->getHeaders()->addHeader($accept); $this->dispatch('/dojo/Sds/DoctrineExtensionsModule/Test/TestAsset/Document/Author.js'); $this->assertContains('This code generated by Sds\\DoctrineExtensions\\Dojo', $this->getResponse()->getContent()); $this->assertResponseStatusCode(200); }
public function testSchemeFail() { $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod(Request::METHOD_GET)->getHeaders()->addHeaders([$accept, GenericHeader::fromString('Authorization: Basic ' . base64_encode('toby:password1'))]); $this->dispatch('http://test.com/test'); $response = $this->getResponse(); $this->assertResponseStatusCode(403); $content = $response->getContent(); $this->assertEquals(0, strlen($content)); }
public function testNoException() { $this->getApplicationServiceLocator()->get('Sds\\ExceptionModule\\JsonExceptionStrategy')->setDisplayExceptions(true); $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('GET')->getHeaders()->addHeader($accept); $this->dispatch('/test_exception/noException'); $this->assertResponseStatusCode(200); $result = json_decode($this->getResponse()->getContent(), true); $this->assertEquals('all good', $result['value']); }
public function testGetLimitedList() { $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('GET')->getHeaders()->addHeader($accept); $this->dispatch('/rest/review'); $result = json_decode($this->getResponse()->getContent(), true); $this->assertResponseStatusCode(200); $this->assertControllerName('shard.rest.review'); $this->assertControllerClass('RestfulController'); $this->assertMatchedRouteName('rest'); $this->assertCount(2, $result); $this->assertEquals('Content-Range: 0-1/3', $this->getResponse()->getHeaders()->get('Content-Range')->toString()); }
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 testPrioritizesValuesBasedOnQParameter() { $header = Accept::fromString('Accept: text/plain; q=0.5, text/html, text/xml; q=0, text/x-dvi; q=0.8, text/x-c'); $expected = array('text/html', 'text/x-c', 'text/x-dvi', 'text/plain'); $test = array(); foreach ($header->getPrioritized() as $type) { $test[] = $type; } $this->assertEquals($expected, $test); }
public function testWildcharMediaType() { $acceptHeader = new Accept(); $acceptHeader->addMediaType('text/*', 0.8)->addMediaType('application/*', 1)->addMediaType('*/*', 0.4); $this->assertTrue($acceptHeader->hasMediaType('text/html')); $this->assertTrue($acceptHeader->hasMediaType('application/atom+xml')); $this->assertTrue($acceptHeader->hasMediaType('audio/basic')); $this->assertEquals('Accept: text/*;q=0.8,application/*,*/*;q=0.4', $acceptHeader->toString()); }
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'])); }
public function testGetEmptyList() { self::tearDownAfterClass(); $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('GET')->getHeaders()->addHeader($accept); $this->dispatch('/rest/author'); $result = json_decode($this->getResponse()->getContent(), true); $this->assertResponseStatusCode(204); $this->assertControllerName('shard.rest.author'); $this->assertControllerClass('RestfulController'); $this->assertMatchedRouteName('rest'); $this->assertFalse(isset($result)); }
public function testDeleteList() { $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('DELETE')->getHeaders()->addHeader($accept); $this->dispatch('/rest/author', 'DELETE'); $result = json_decode($this->getResponse()->getContent(), true); $this->assertFalse(isset($result)); $this->assertResponseStatusCode(204); $this->assertControllerName('rest.default.author'); $this->assertControllerClass('JsonRestfulController'); $this->assertMatchedRouteName('rest.default'); $cursor = $this->documentManager->getRepository('Sds\\DoctrineExtensionsModule\\Test\\TestAsset\\Document\\Author')->findAll(); $this->assertCount(0, $cursor); }
public function runAction() { $sm = $this->getServiceLocator(); /* @var $console AdapterInterface */ /* @var $config array */ /* @var $mm ModuleManager */ $console = $sm->get('console'); $config = $sm->get('Configuration'); $mm = $sm->get('ModuleManager'); $verbose = $this->params()->fromRoute('verbose', false); $debug = $this->params()->fromRoute('debug', false); $quiet = !$verbose && !$debug && $this->params()->fromRoute('quiet', false); $breakOnFailure = $this->params()->fromRoute('break', false); $checkGroupName = $this->params()->fromRoute('filter', false); // Get basic diag configuration $config = isset($config['diagnostics']) ? $config['diagnostics'] : array(); // Collect diag tests from modules $modules = $mm->getLoadedModules(false); foreach ($modules as $moduleName => $module) { if (is_callable(array($module, 'getDiagnostics'))) { $checks = $module->getDiagnostics(); if (is_array($checks)) { $config[$moduleName] = $checks; } // Exit the loop early if we found check definitions for // the only check group that we want to run. if ($checkGroupName && $moduleName == $checkGroupName) { break; } } } // Filter array if a check group name has been provided if ($checkGroupName) { $config = array_intersect_ukey($config, array($checkGroupName => 1), 'strcasecmp'); if (empty($config)) { $m = new ConsoleModel(); $m->setResult($console->colorize(sprintf("Unable to find a group of diagnostic checks called \"%s\". Try to use module name (i.e. \"%s\").\n", $checkGroupName, 'Application'), ColorInterface::YELLOW)); $m->setErrorLevel(1); return $m; } } // Check if there are any diagnostic checks defined if (empty($config)) { $m = new ConsoleModel(); $m->setResult($console->colorize("There are no diagnostic checks currently enabled for this application - please add one or more " . "entries into config \"diagnostics\" array or add getDiagnostics() method to your Module class. " . "\n\nMore info: https://github.com/zendframework/ZFTool/blob/master/docs/" . "DIAGNOSTICS.md#adding-checks-to-your-module\n", ColorInterface::YELLOW)); $m->setErrorLevel(1); return $m; } // Analyze check definitions and construct check instances $checkCollection = array(); foreach ($config as $checkGroupName => $checks) { foreach ($checks as $checkLabel => $check) { // Do not use numeric labels. if (!$checkLabel || is_numeric($checkLabel)) { $checkLabel = false; } // Handle a callable. if (is_callable($check)) { $check = new Callback($check); if ($checkLabel) { $check->setLabel($checkGroupName . ': ' . $checkLabel); } $checkCollection[] = $check; continue; } // Handle check object instance. if (is_object($check)) { if (!$check instanceof CheckInterface) { throw new RuntimeException('Cannot use object of class "' . get_class($check) . '" as check. ' . 'Expected instance of ZendDiagnostics\\Check\\CheckInterface'); } // Use duck-typing for determining if the check allows for setting custom label if ($checkLabel && is_callable(array($check, 'setLabel'))) { $check->setLabel($checkGroupName . ': ' . $checkLabel); } $checkCollection[] = $check; continue; } // Handle an array containing callback or identifier with optional parameters. if (is_array($check)) { if (!count($check)) { throw new RuntimeException('Cannot use an empty array() as check definition in "' . $checkGroupName . '"'); } // extract check identifier and store the remainder of array as parameters $testName = array_shift($check); $params = $check; } elseif (is_scalar($check)) { $testName = $check; $params = array(); } else { throw new RuntimeException('Cannot understand diagnostic check definition "' . gettype($check) . '" in "' . $checkGroupName . '"'); } // Try to expand check identifier using Service Locator if (is_string($testName) && $sm->has($testName)) { $check = $sm->get($testName); // Try to use the ZendDiagnostics namespace } elseif (is_string($testName) && class_exists('ZendDiagnostics\\Check\\' . $testName)) { $class = new \ReflectionClass('ZendDiagnostics\\Check\\' . $testName); $check = $class->newInstanceArgs($params); // Try to use the ZFTool namespace } elseif (is_string($testName) && class_exists('ZFTool\\Diagnostics\\Check\\' . $testName)) { $class = new \ReflectionClass('ZFTool\\Diagnostics\\Check\\' . $testName); $check = $class->newInstanceArgs($params); // Check if provided with a callable inside an array } elseif (is_callable($testName)) { $check = new Callback($testName, $params); if ($checkLabel) { $check->setLabel($checkGroupName . ': ' . $checkLabel); } $checkCollection[] = $check; continue; // Try to expand check using class name } elseif (is_string($testName) && class_exists($testName)) { $class = new \ReflectionClass($testName); $check = $class->newInstanceArgs($params); } else { throw new RuntimeException('Cannot find check class or service with the name of "' . $testName . '" (' . $checkGroupName . ')'); } if (!$check instanceof CheckInterface) { // not a real check throw new RuntimeException('The check object of class ' . get_class($check) . ' does not implement ' . 'ZendDiagnostics\\Check\\CheckInterface'); } // Use duck-typing for determining if the check allows for setting custom label if ($checkLabel && is_callable(array($check, 'setLabel'))) { $check->setLabel($checkGroupName . ': ' . $checkLabel); } $checkCollection[] = $check; } } // Configure check runner $runner = new Runner(); $runner->addChecks($checkCollection); $runner->getConfig()->setBreakOnFailure($breakOnFailure); if (!$quiet && $this->getRequest() instanceof ConsoleRequest) { if ($verbose || $debug) { $runner->addReporter(new VerboseConsole($console, $debug)); } else { $runner->addReporter(new BasicConsole($console)); } } // Run tests $results = $runner->run(); $request = $this->getRequest(); // Return result if ($request instanceof ConsoleRequest) { // Return appropriate error code in console $model = new ConsoleModel(); $model->setVariable('results', $results); if ($results->getFailureCount() > 0) { $model->setErrorLevel(1); } else { $model->setErrorLevel(0); } return $model; } if ($request instanceof Request) { $defaultAccept = new Accept(); $defaultAccept->addMediaType('text/html'); $acceptHeader = $request->getHeader('Accept', $defaultAccept); $viewModel = function () use($results) { $model = new ViewModel(); $model->setVariable('results', $results); return $model; }; if ($acceptHeader->match('text/html')) { // Display results as a web page $model = $viewModel(); } else { if ($acceptHeader->match('application/json')) { // Display results as json $model = new JsonModel(); $model->setVariables($this->getResultCollectionToArray($results)); } else { $model = $viewModel(); } } return $model; } }
public function testGetReallyDeep() { $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod('GET')->getHeaders()->addHeader($accept); $this->dispatch('/rest/review/great-review/game/author/country/authors/thomas'); $result = json_decode($this->getResponse()->getContent(), true); $this->assertResponseStatusCode(200); $this->assertControllerClass('RestfulController'); $this->assertMatchedRouteName('rest'); $this->assertEquals('thomas', $result['name']); }
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 testInvalidModel() { $arr = array('DoesNotExist' => 'text/xml'); $header = Accept::fromString('Accept: */*'); $this->request->getHeaders()->addHeader($header); $this->setExpectedException('\\Zend\\Mvc\\Exception\\InvalidArgumentException'); $this->plugin->getViewModel($arr); }
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); }
private function getPlaceTypesRequest() { $acceptHeader = new Accept(); $acceptHeader->addMediaType('application/json'); $req = new Request(); $req->setUri('http://mon-partenaire.loc/api/place-type'); $req->getHeaders()->addHeader($acceptHeader); return $req; }
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 testPrioritizing_2() { $accept = Accept::fromString("Accept: application/text, \tapplication/*"); $res = $accept->getPrioritized(); $this->assertEquals('application/text', $res[0]->raw); $this->assertEquals('application/*', $res[1]->raw); $accept = Accept::fromString("Accept: \tapplication/*, application/text"); $res = $accept->getPrioritized(); $this->assertEquals('application/text', $res[0]->raw); $this->assertEquals('application/*', $res[1]->raw); $accept = Accept::fromString("Accept: text/xml, application/xml"); $res = $accept->getPrioritized(); $this->assertEquals('application/xml', $res[0]->raw); $this->assertEquals('text/xml', $res[1]->raw); $accept = Accept::fromString("Accept: application/xml, text/xml"); $res = $accept->getPrioritized(); $this->assertEquals('application/xml', $res[0]->raw); $this->assertEquals('text/xml', $res[1]->raw); $accept = Accept::fromString("Accept: application/vnd.foobar+xml; q=0.9, text/xml"); $res = $accept->getPrioritized(); $this->assertEquals(1.0, $res[0]->getPriority()); $this->assertEquals(0.9, $res[1]->getPriority()); $this->assertEquals('application/vnd.foobar+xml', $res[1]->getTypeString()); $this->assertEquals('vnd.foobar+xml', $res[1]->getSubtypeRaw()); $this->assertEquals('vnd.foobar', $res[1]->getSubtype()); $this->assertEquals('xml', $res[1]->getFormat()); $accept = Accept::fromString('Accept: text/xml, application/vnd.foobar+xml; version="\'Ѿ"'); $res = $accept->getPrioritized(); $this->assertEquals('application/vnd.foobar+xml; version="\'Ѿ"', $res[0]->getRaw()); }
public function testSessionTheftWithRememberMe() { $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 = 'wrong token'; $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_GET)->getHeaders()->addHeaders([$accept, $requestCookie]); $this->dispatch('/rest/authenticatedUser'); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertResponseStatusCode(204); $this->assertFalse(isset($result)); $responseCookie = $response->getHeaders()->get('SetCookie')[0]; $this->assertEquals('rememberMe', $responseCookie->getName()); $this->assertEquals('', $responseCookie->getValue()); }
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)); }
/** * Attempt to match the accept criteria * * If it matches, but on "*\/*", return false. * * Otherwise, return based on whether or not one or more criteria match. * * @param AcceptHeader $accept * @return bool */ protected function matchAcceptCriteria(AcceptHeader $accept) { foreach ($this->acceptFilters as $type) { $match = $accept->match($type); if ($match && $match->getTypeString() != '*/*') { return true; } } return false; }
private function processHttpRequest(Request $request, Collection $results) { $defaultAccept = new Accept(); $defaultAccept->addMediaType(self::CONTENT_TYPE_HTML); $acceptHeader = $request->getHeader('Accept', $defaultAccept); if ($acceptHeader->match(self::CONTENT_TYPE_HTML) || !$acceptHeader->match(self::CONTENT_TYPE_JSON)) { // Display results as a web page return new ViewModel(array('results' => $results)); } return new JsonModel($this->getResultCollectionToArray($results)); }
public function testUnknownAccept() { $this->config['diagnostics']['group']['test1'] = $check1 = new AlwaysSuccessCheck(); ob_start(); $request = new \Zend\Http\Request(); $request->getHeaders()->addHeader(\Zend\Http\Header\Accept::fromString('Accept: application/baz')); $result = $this->controller->dispatch($request); $this->assertEquals('', ob_get_clean()); $this->assertInstanceOf('Zend\\View\\Model\\ViewModel', $result); $this->assertInstanceOf('ZendDiagnostics\\Result\\Collection', $result->getVariable('results')); }
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 testGetWithoutAuthenticatedIdentity() { $accept = new Accept(); $accept->addMediaType('application/json'); $this->getRequest()->setMethod(Request::METHOD_GET)->getHeaders()->addHeader($accept); $this->dispatch('/rest/authenticatedIdentity'); $response = $this->getResponse(); $result = json_decode($response->getContent(), true); $this->assertResponseStatusCode(204); $this->assertFalse(isset($result)); }