Author: Fabien Potencier (fabien@symfony.com)
Inheritance: extends Symfony\Component\HttpKernel\Client
Ejemplo n.º 1
1
 public function setUp()
 {
     $this->client = static::createClient();
     $this->client->followRedirects();
     $this->container = $this->client->getContainer();
     $this->loadFixtures($this->getFixtures());
 }
 /**
  * Test token creation and usage
  */
 public function testTokenCreation()
 {
     $headers = array('PHP_AUTH_USER' => 'test_key', 'PHP_AUTH_PW' => 'test_secret', 'HTTP_username' => 'p-admin', 'HTTP_password' => 'p-admin');
     $this->client->request('GET', '/oauth/access_token?grant_type=password', array(), array(), $headers);
     $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
     $this->assertSame('application/json', $this->client->getResponse()->headers->get('content-type'));
 }
Ejemplo n.º 3
0
 public function testControllerNoticeToException()
 {
     $this->client = $this->createClient();
     $errorOccured = false;
     $syslogProcessorMock = $this->getMockBuilder('Keboola\\Syrup\\Monolog\\Processor\\SyslogProcessor')->disableOriginalConstructor()->getMock();
     $syslogProcessorMock->expects($this->any())->method("processRecord")->with($this->callback(function ($subject) use(&$errorOccured) {
         if ($subject['message'] == 'Notice: Undefined offset: 3') {
             $e = $subject['context']['exception'];
             $errorOccured = true;
             return $e instanceof \Symfony\Component\Debug\Exception\ContextErrorException;
         }
         return true;
     }))->willReturn(['level' => 100]);
     $container = $this->client->getContainer();
     $container->set('syrup.monolog.syslog_processor', $syslogProcessorMock);
     $this->client->request('GET', '/tests/notice');
     $response = $this->client->getResponse();
     $responseJson = json_decode($response->getContent(), true);
     $this->assertEquals('error', $responseJson['status']);
     $this->assertEquals('Application error', $responseJson['error']);
     $this->assertEquals(500, $responseJson['code']);
     $this->assertArrayHasKey('exceptionId', $responseJson);
     $this->assertArrayHasKey('runId', $responseJson);
     $this->assertTrue($errorOccured);
 }
 public function testSearchPage()
 {
     $this->client->request('GET', '/search?keyword=samsung sync master');
     $response = $this->client->getResponse();
     $this->assertTrue($response->isSuccessful());
     $this->assertEquals('application/json', $response->headers->get('Content-Type'));
 }
Ejemplo n.º 5
0
 public static function setUpBeforeClass()
 {
     static::$client = static::createClient();
     static::$router = self::$client->getContainer()->get('router');
     static::$em = self::$client->getContainer()->get('doctrine.orm.entity_manager');
     static::$container = self::getContainer();
 }
 /**
  * {@inheritdoc}
  */
 protected static function createClient(array $options = array(), array $server = array())
 {
     static::bootKernel($options);
     $client = new Client(static::$kernel);
     $client->setServerParameters($server);
     return $client;
 }
 /**
  * @depends testPut
  */
 public function testDeleteMultiple()
 {
     $data = [2, 3];
     $uri = self::$router->generate('post_assets') . '.json';
     self::$client->request('DELETE', $uri, ['images' => json_encode($data)]);
     $this->assertTrue(self::$client->getResponse()->isRedirect());
 }
Ejemplo n.º 8
0
 /**
  * @param \Symfony\Bundle\FrameworkBundle\Client $client
  *
  * @return string
  */
 protected function getErrorMessage(Client $client)
 {
     /** @var $profile \Symfony\Component\HttpKernel\Profiler\Profile */
     $profile = $client->getProfile();
     if (!$profile) {
         return '';
     }
     /** @var $exception \Symfony\Component\HttpKernel\DataCollector\ExceptionDataCollector */
     $exception = $profile->getCollector('exception');
     if (!$exception->hasException()) {
         return '';
     }
     $arrayTrace = array();
     foreach (array_slice($exception->getTrace(), 0, 10) as $position => $traceLine) {
         if (isset($traceLine['class'])) {
             $arrayTrace[] = sprintf('[%d] %s(%d) %s%s%s(%s)', $position, $traceLine['file'], $traceLine['line'], $traceLine['short_class'], $traceLine['type'], $traceLine['function'], isset($traceLine['args']) ? implode(', ', array_map(function ($v) {
                 switch ($v[0]) {
                     case 'array':
                         return 'array(' . count($v[1]) . ')';
                     case 'object':
                         return $v[1];
                     default:
                         return $v[1];
                 }
             }, $traceLine['args'])) : '');
         }
     }
     if (count($arrayTrace) < count($exception->getTrace())) {
         $arrayTrace[] = '...';
     }
     return $exception->getMessage() . PHP_EOL . PHP_EOL . implode(PHP_EOL, $arrayTrace) . PHP_EOL;
 }
Ejemplo n.º 9
0
 public function testPutPlayerAction()
 {
     $em = self::$kernel->getContainer()->get('doctrine')->getManager();
     $queryBuilder = $em->createQueryBuilder();
     $players = $queryBuilder->select('p')->from('DraftBundle:Player', 'p')->setMaxResults(1)->getQuery()->execute();
     if (is_array($players)) {
         $player = $players[0];
     } else {
         $player = $players;
     }
     $name = $player->getName();
     $team = $player->getNflTeam();
     $position = $player->getPosition();
     $toEncode = array('name' => 'willy wonka', 'position' => 'QB', 'nflTeam' => 'SF', 'draftYear' => '2016');
     $postData = json_encode($toEncode);
     $this->client->request('PUT', '/api/players/' . $player->getId(), array(), array(), array('CONTENT_TYPE' => 'application/json'), $postData);
     $response = $this->client->getResponse();
     $content = $response->getContent();
     $this->assertTrue($response->isSuccessful());
     $this->assertEmpty($content);
     $updatedPlayer = $em->getRepository('DraftBundle:Player')->find($player->getId());
     $this->assertEquals('willy wonka', $updatedPlayer->getName());
     $updatedPlayer->setName($name);
     $updatedPlayer->setNflTeam($team);
     $updatedPlayer->setPosition($position);
     $em->persist($updatedPlayer);
     $em->flush();
 }
Ejemplo n.º 10
0
 /**
  * Performs logout action and returns same client after log out.
  *
  * @param Client $client
  *
  * @return Client
  */
 public function logoutAction(Client $client)
 {
     $crawler = $client->request('GET', '/settings/login');
     $link = $crawler->filter('a:contains("Logout")')->link();
     $client->click($link);
     return $client;
 }
Ejemplo n.º 11
0
 /**
  * Create settings cookies and set it in the cookie jar.
  *
  * @param Client $client
  * @param array  $cookies
  */
 public static function setSettingsCookie(Client $client, array $cookies)
 {
     foreach ($cookies as $name => $cookieSettings) {
         $cookie = new Cookie($name, json_encode($cookieSettings));
         $client->getCookieJar()->set($cookie);
     }
 }
Ejemplo n.º 12
0
 protected function assertApiGetResponse($apiUri, $expectedStatusCode, $expectedJsonString)
 {
     static::$client->request('GET', $apiUri);
     $this->assertStatusCode($expectedStatusCode, static::$client);
     $responseBody = static::$client->getResponse()->getContent();
     static::assertJson($responseBody);
     static::assertJsonStringEqualsJsonString($expectedJsonString, $responseBody);
 }
Ejemplo n.º 13
0
 public function testGetUnpublished()
 {
     /** @var $service PhpcrBlockLoader */
     $service = $this->client->getContainer()->get('cmf.block.service');
     $this->assertInstanceOf('Symfony\Cmf\Bundle\BlockBundle\Doctrine\Phpcr\SimpleBlock', $service->load(array('name' => '/test/blocks/block-1')));
     // this block is not published, should be empty
     $this->assertInstanceOf('Sonata\BlockBundle\Model\EmptyBlock', $service->load(array('name' => '/test/blocks/block-2')));
 }
Ejemplo n.º 14
0
 /**
  * @param string $method
  * @param array $parameters
  * @return Page
  */
 public function open($method = 'GET', $parameters = [])
 {
     $this->crawler = $this->client->request($method, $this->unmaskUrl($parameters));
     if (!in_array($this->client->getResponse()->getStatusCode(), [200, 302])) {
         throw new \RuntimeException(sprintf("Can't open \"%s\"", $this->getUrl()));
     }
     return $this;
 }
Ejemplo n.º 15
0
 public function testCreateTransAndRedirectToTpv()
 {
     $this->transaction = new Transaction(1);
     $this->manager->update($this->transaction);
     /** @var $crawler */
     $crawler = $this->client->request('GET', $this->route_index);
     $this->assertEquals($crawler->filter('body:contains(form)')->count(), 1);
 }
Ejemplo n.º 16
0
 /**
  * Create a JSON request
  *
  * @param Client $client
  * @param string $method
  * @param string $url
  * @param string $content
  * @param string $token
  */
 public function makeJsonRequest(Client $client, $method, $url, $content = null, $token = null, $files = array())
 {
     $headers = ['HTTP_ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json'];
     if (!empty($token)) {
         $headers['HTTP_X-JWT-Authorization'] = 'Token ' . $token;
     }
     $client->request($method, $url, [], $files, $headers, $content);
 }
Ejemplo n.º 17
0
 /**
  * {@inheritDoc}
  */
 public function setUp()
 {
     $this->client = static::createClient();
     $this->container = $this->client->getContainer();
     $this->em = $this->container->get('doctrine')->getManager();
     $this->validator = $this->container->get('validator');
     $this->setCurrentShop();
 }
 /**
  * Test AjaxDeleteFromBookmark action
  */
 public function testAjaxDeleteFromBookmarkAction()
 {
     $fixtures = $this->loadFixtures(['AppBundle\\DataFixtures\\ORM\\LoadUserData', 'AppBundle\\DataFixtures\\ORM\\LoadUserGroupData', 'AppBundle\\DataFixtures\\ORM\\LoadGroupData'])->getReferenceRepository();
     $this->loginAs($fixtures->getReference('user-admin'), 'main');
     $this->client = static::makeClient();
     $this->client->request('GET', '/group/jinjer/bookmark/delete', [], [], ['HTTP_X-Requested-With' => 'XMLHttpRequest']);
     $this->assertStatusCode(Response::HTTP_OK, $this->client);
 }
Ejemplo n.º 19
0
 /**
  * Request to API, return result
  * @param string $url URL of API call
  * @param string $method HTTP method of API call
  * @param array $params parameters of POST call
  * @return array
  */
 protected function callApi($url, $method = 'POST', $params = array())
 {
     $this->httpClient->request($method, $url, [], [], [], json_encode($params));
     $response = $this->httpClient->getResponse();
     /* @var \Symfony\Component\HttpFoundation\Response $response */
     $responseJson = json_decode($response->getContent(), true);
     $this->assertNotEmpty($responseJson, sprintf("Response of API call '%s' after json decoding should not be empty. Raw response:\n%s\n", $url, $response->getContent()));
     return $responseJson;
 }
Ejemplo n.º 20
0
 protected function runCommand(array $arguments = [])
 {
     $application = new Application($this->client->getKernel());
     $application->setAutoExit(false);
     $arguments['--quiet'] = true;
     $arguments['-e'] = 'test';
     $input = new ArrayInput($arguments);
     $application->run($input, new ConsoleOutput());
 }
Ejemplo n.º 21
0
 protected function setUp()
 {
     parent::setUp();
     $this->client = static::createClient();
     $this->client->followRedirects();
     $this->kern = $this->client->getKernel();
     $this->container = $this->client->getContainer();
     $this->em = $this->container->get('doctrine.orm.entity_manager');
 }
 private function executeCommand(Command $command, Input $input)
 {
     $command->setApplication($this->application);
     $input->setInteractive(false);
     if ($command instanceof ContainerAwareCommand) {
         $command->setContainer($this->client->getContainer());
     }
     $command->run($input, new NullOutput());
 }
Ejemplo n.º 23
0
 public function tearDown()
 {
     foreach ($this->client->getContainer()->getMockedServices() as $id => $service) {
         $this->client->getContainer()->unmock($id);
     }
     \Mockery::close();
     $this->client = null;
     parent::tearDown();
 }
Ejemplo n.º 24
0
 /**
  * @param  Client     $client
  * @throws \Exception
  */
 public function checkEventIsCaught(Client $client)
 {
     $profile = $client->getProfile();
     if (!$profile) {
         throw new \Exception("Hey Poser! The profiler should be enabled if you want to check events");
     }
     $eventCollector = $profile->getCollector('events');
     $eventName = 'kernel.controller.PUGX\\StatsBundle\\Listener\\StatsListener::onKernelController';
     $this->assertArrayHasKey($eventName, $eventCollector->getCalledListeners(), "stats listener has been called");
 }
Ejemplo n.º 25
0
 /**
  * @return \Symfony\Bundle\FrameworkBundle\Client
  */
 protected static function getInitClient()
 {
     if (self::$client) {
         return self::$client;
     }
     self::$client = self::createClient();
     static::$kernel = self::$client->getKernel();
     self::$container = self::$client->getContainer();
     return self::$client;
 }
Ejemplo n.º 26
0
 protected function adminLogIn(Client $client)
 {
     $session = $client->getContainer()->get('session');
     $firewall = 'secured_area';
     $token = new UsernamePasswordToken('admin', null, $firewall, array('ROLE_ADMIN'));
     $session->set('_security_' . $firewall, serialize($token));
     $session->save();
     $cookie = new Cookie($session->getName(), $session->getId());
     $client->getCookieJar()->set($cookie);
 }
 public function testRegisterSuccess()
 {
     $this->form[self::USERNAME_FIELD] = self::USERNAME;
     $this->form[self::EMAIL_FIELD] = self::EMAIL;
     $this->form[self::PASSWORD_FIELD] = self::PASSWORD;
     $this->form[self::REPEAT_PASSWORD_FIELD] = self::PASSWORD;
     $this->crawler = $this->client->submit($this->form);
     $this->assertEmpty($this->crawler->filter(self::ERROR_SELECTOR));
     $this->assertNotEquals(self::REGISTRATION_URL, $this->client->getRequest()->getRequestUri());
 }
Ejemplo n.º 28
0
 /**
  * @param \Symfony\Bundle\FrameworkBundle\Client $client
  * @param \Symfony\Component\DomCrawler\Crawler  $crawler
  * @param string                                 $method
  *
  * @return callable
  */
 protected function getSendRequestHandler(&$client, &$crawler, $method)
 {
     $generator = $this->getAsserterGenerator();
     $test = $this;
     return function ($path, array $parameters = array(), array $files = array(), array $server = array(), $content = null, $changeHistory = true) use(&$client, &$crawler, $method, $generator, $test) {
         /** @var $client \Symfony\Bundle\FrameworkBundle\Client */
         $crawler = $client->request($method, $path, $parameters, $files, $server, $content, $changeHistory);
         return $generator->getAsserterInstance('\\atoum\\AtoumBundle\\Test\\Asserters\\Response', array($client->getResponse()), $test);
     };
 }
 /**
  *
  */
 protected function signInAsAdmin()
 {
     $session = $this->client->getContainer()->get('session');
     $firewall = 'main';
     $token = new UsernamePasswordToken('admin', null, $firewall, array('ROLE_ADMIN'));
     $session->set('_security_' . $firewall, serialize($token));
     $session->save();
     $cookie = new Cookie($session->getName(), $session->getId());
     $this->client->getCookieJar()->set($cookie);
 }
 /**
  * Test for AppBundle\Controller\DefaultController::feedAction
  * Also test performance - Any PHP used should be limited to 32MB of memory
  *
  * @param string  $source
  * @param integer $start
  * @param integer $amount
  * @param integer $expectedAmount
  *
  * @dataProvider feedDataProvider
  */
 public function testFeed($source, $start, $amount, $expectedAmount)
 {
     $this->client->request('GET', '/feed', array('source' => $source, 'start' => $start, 'amount' => $amount));
     $response = $this->client->getResponse();
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertEquals('application/json', $response->headers->get('Content-type'));
     $this->assertCount($expectedAmount, json_decode($response->getContent(), true));
     $this->assertLessThan(1024 * 1024 * 32, memory_get_peak_usage(true));
     // 32 MB
 }