To make the actual request, you need to implement the doRequest() method. If you want to be able to run requests in their own process (insulated flag), you need to also implement the getScript() method.
Author: Fabien Potencier (fabien@symfony.com)
 /**
  * @return AuthenticateResponse
  */
 public function authenticate()
 {
     $this->client->request('POST', self::SING_IN_URI, ['username' => $this->username, 'password' => $this->password], [], ['HTTP_ACCEPT' => 'application/json']);
     $loginResponse = json_decode($this->client->getResponse()->getContent());
     $authenticateHeaders = ['HTTP_TOKEN' => isset($loginResponse->Token) ? $loginResponse->Token : null, 'HTTP_EXPIREAT' => isset($loginResponse->ExpireAt) ? $loginResponse->ExpireAt : null, 'HTTP_USERNAME' => isset($loginResponse->Username) ? $loginResponse->Username : null];
     return new AuthenticateResponse([], $authenticateHeaders);
 }
 /**
  * @param $uri
  * @param $format
  * @return \PHPExcel
  */
 protected function getDocument($uri, $format = 'xlsx')
 {
     // generate source
     static::$client->request('GET', $uri);
     $source = static::$client->getResponse()->getContent();
     // create source directory if necessary
     if (!file_exists(__DIR__ . static::$TEMP_PATH)) {
         mkdir(__DIR__ . static::$TEMP_PATH);
     }
     // save source
     file_put_contents(__DIR__ . static::$TEMP_PATH . 'simple' . '.' . $format, $source);
     // load source
     switch ($format) {
         case 'ods':
             $reader = new PHPExcel_Reader_OOCalc();
             break;
         case 'xls':
             $reader = new PHPExcel_Reader_Excel5();
             break;
         case 'xlsx':
             $reader = new PHPExcel_Reader_Excel2007();
             break;
         default:
             throw new InvalidArgumentException();
     }
     return $reader->load(__DIR__ . static::$TEMP_PATH . 'simple' . '.' . $format);
 }
 /**
  * Initializes Goutte driver.
  *
  * @param Symfony\Component\BrowserKit\Client $client BrowserKit client instance
  */
 public function __construct(Client $client = null)
 {
     // create new kernel, that could be easily rebooted
     $class = get_class($client->getKernel());
     $kernel = new $class('Behat', 'config.yml', $client->getKernel()->getEnvironment(), $client->getKernel()->isDebug());
     $kernel->boot();
     parent::__construct($kernel->getContainer()->get('test.client'));
 }
 /**
  * Initializes BrowserKit driver.
  *
  * @param Client      $client  BrowserKit client instance
  * @param string|null $baseUrl Base URL for HttpKernel clients
  */
 public function __construct(Client $client, $baseUrl = null)
 {
     $this->client = $client;
     $this->client->followRedirects(true);
     if ($baseUrl !== null && $client instanceof HttpKernelClient) {
         $client->setServerParameter('SCRIPT_FILENAME', parse_url($baseUrl, PHP_URL_PATH));
     }
 }
 public function testIndex()
 {
     $this->client = static::createClient();
     $this->client->setServerParameters(['CONTENT_TYPE' => 'application/json', 'HTTP_HOST' => 'localhost:8000']);
     // create user
     $userName = md5(microtime());
     $registration = $this->makeRequest('/user/create', ["user" => ["name" => $userName]]);
     $this->assertEquals($registration->getMessage(), 'Ok');
     $userId = $registration->getData()->id;
     // try to create duplicate
     $registration = $this->makeRequest('/user/create', ["user" => ["name" => $userName]]);
     $this->assertEquals($registration->getMessage(), 'User already exists');
     // create opponents
     for ($i = 0; $i <= 10; $i++) {
         $registration = $this->makeRequest('/user/create', ["user" => ["name" => md5(microtime() + $i)]]);
         $this->assertEquals($registration->getMessage(), 'Ok');
     }
     // login
     $login = $this->makeRequest('/user/login', ["token" => $userName]);
     $this->assertEquals($login->getMessage(), 'Ok');
     $this->assertEquals($login->getData()->id, $userId);
     // opponent
     $opponents = $this->makeRequest('/user/opponents', ["token" => $userName]);
     $this->assertEquals($opponents->getMessage(), 'Ok');
     $opponentId = $opponents->getData()[0]->id;
     $opponentName = $opponents->getData()[0]->name;
     // invite
     $response = $this->makeRequest('/combat/invite', ["token" => $userName, "id" => $opponentId]);
     $this->assertEquals($response->getMessage(), 'Ok');
     $combatId = $response->getData()->combatId;
     $attackFirst = $response->getData()->youFirst;
     // attack
     $response = $this->makeRequest('/combat/attack', ["token" => $attackFirst ? $opponentName : $userName, "combatId" => $combatId, "skillId" => 2]);
     $this->assertEquals($response->getMessage(), 'It is not your turn');
     // attack
     $response = $this->makeRequest('/combat/attack', ["token" => $attackFirst ? $userName : $opponentName, "combatId" => $combatId, "skillId" => 2]);
     $this->assertEquals($response->getMessage(), 'Ok');
     // attack
     $response = $this->makeRequest('/combat/attack', ["token" => $attackFirst ? $opponentName : $userName, "combatId" => $combatId, "skillId" => 2]);
     $this->assertEquals($response->getMessage(), 'This skill already used');
     // collect
     $response = $this->makeRequest('/combat/collect', ["token" => $attackFirst ? $opponentName : $userName, "combatId" => $combatId]);
     $this->assertEquals($response->getMessage(), 'Combat is not finished');
     // attack
     $response = $this->makeRequest('/combat/attack', ["token" => $attackFirst ? $opponentName : $userName, "combatId" => $combatId, "skillId" => 1]);
     $this->assertEquals($response->getMessage(), 'Ok');
     // attack
     $response = $this->makeRequest('/combat/attack', ["token" => $attackFirst ? $userName : $opponentName, "combatId" => $combatId, "skillId" => 3]);
     $this->assertEquals($response->getMessage(), 'Ok');
     // attack
     $response = $this->makeRequest('/combat/attack', ["token" => $attackFirst ? $opponentName : $userName, "combatId" => $combatId, "skillId" => 1]);
     $this->assertEquals($response->getMessage(), 'Combat was finished');
     // collect
     $response = $this->makeRequest('/combat/collect', ["token" => $opponentName, "combatId" => $combatId]);
     // collect
     $response = $this->makeRequest('/combat/collect', ["token" => $userName, "combatId" => $combatId]);
 }
 public function setUp()
 {
     parent::setUp();
     $this->db('ORM')->purgeDatabase();
     $this->client = $this->createAuthenticatedClient();
     $this->searchManager = $this->client->getContainer()->get('massive_search.search_manager');
     $this->entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
     $this->createUser();
     $this->indexProducts();
 }
Beispiel #7
0
 public function logIn(Client $client)
 {
     $session = $client->getContainer()->get('session');
     $firewall = 'admin';
     $token = new UsernamePasswordToken('admin', null, $firewall, array('ROLE_USER'));
     $session->set('_security_' . $firewall, serialize($token));
     $session->save();
     $cookie = new Cookie($session->getName(), $session->getId());
     $client->getCookieJar()->set($cookie);
 }
 private function addToCart($mealName, $quantity, Crawler $crawler, Client $client)
 {
     $titles = $crawler->filter('h4')->reduce(function ($crawler) use($mealName) {
         return false !== strpos($crawler->text(), $mealName);
     });
     if (count($titles) !== 1) {
         throw new \RuntimeException(sprintf('Expected 1 title containing "%s", found %s.', $mealName, count($titles)));
     }
     $link = $titles->eq(0)->parents()->first()->filter('input[data-meal]');
     $mealId = $link->attr('data-meal');
     $client->request('POST', '/cart', array('meal' => $mealId, 'mode' => 'add', 'quantity' => $quantity));
     $this->assertEquals(200, $client->getResponse()->getStatusCode());
 }
Beispiel #9
0
 protected function setCookiesFromOptions()
 {
     if (isset($this->config['cookies']) && is_array($this->config['cookies']) && !empty($this->config['cookies'])) {
         $domain = parse_url($this->config['url'], PHP_URL_HOST);
         $cookieJar = $this->client->getCookieJar();
         foreach ($this->config['cookies'] as &$cookie) {
             if (!is_array($cookie) || !array_key_exists('Name', $cookie) || !array_key_exists('Value', $cookie)) {
                 throw new \InvalidArgumentException('Cookies must have at least Name and Value attributes');
             }
             if (!isset($cookie['Domain'])) {
                 $cookie['Domain'] = $domain;
             }
             if (!isset($cookie['Expires'])) {
                 $cookie['Expires'] = null;
             }
             if (!isset($cookie['Path'])) {
                 $cookie['Path'] = '/';
             }
             if (!isset($cookie['Secure'])) {
                 $cookie['Secure'] = false;
             }
             if (!isset($cookie['HttpOnly'])) {
                 $cookie['HttpOnly'] = false;
             }
             $cookieJar->set(new \Symfony\Component\BrowserKit\Cookie($cookie['Name'], $cookie['Value'], $cookie['Expires'], $cookie['Path'], $cookie['Domain'], $cookie['Secure'], $cookie['HttpOnly']));
         }
     }
 }
Beispiel #10
0
 /**
  *  override to allow redirect history recording
  *     
  *  @see  parent::followRedirect
  */
 public function followRedirect()
 {
     if (!empty($this->redirect)) {
         $this->redirect_list[] = $this->redirect;
     }
     //if
     return parent::followRedirect();
 }
Beispiel #11
0
 /**
  * Checks response code.
  *
  * @param $num
  */
 public function seeResponseCodeIs($num)
 {
     if (method_exists($this->client->getResponse(), 'getStatusCode')) {
         \PHPUnit_Framework_Assert::assertEquals($num, $this->client->getResponse()->getStatusCode());
     } else {
         \PHPUnit_Framework_Assert::assertEquals($num, $this->client->getResponse()->getStatus());
     }
 }
Beispiel #12
0
    /**
     * Constructor.
     *
     * @param HttpKernelInterface $kernel    An HttpKernel instance
     * @param array               $server    The server parameters (equivalent of $_SERVER)
     * @param History             $history   A History instance to store the browser history
     * @param CookieJar           $cookieJar A CookieJar instance to store the cookies
     */
    public function __construct(HttpKernelInterface $kernel, array $server = array(), History $history = null, CookieJar $cookieJar = null)
    {
        $this->kernel = $kernel;

        parent::__construct($server, $history, $cookieJar);

        $this->followRedirects = false;
    }
Beispiel #13
0
 /**
  * testing savePerDiem action.
  */
 public function testSavePerDiemAction()
 {
     // Empty request
     $crawler = $this->client->request('POST', '/secured/travel/admin/save/perdiem');
     $this->assertJson($this->client->getResponse()->getContent(), 'testSavePerDiemAction: The response\'s content is not a JSON object.');
     $this->assertTrue($this->client->getResponse()->headers->contains('Content-Type', 'application/json'), 'testSavePerDiemAction: The content-type is not a json.');
     // Filled up request
     $crawler = $this->client->request('POST', '/secured/travel/admin/save/perdiem', array('perdiem' => array(0 => array('id' => 1, 'hours' => 14, 'amount' => 24), 1 => array('id' => null, 'hours' => 12, 'amount' => 12))));
     $this->assertTrue($this->client->getResponse()->headers->contains('Content-Type', 'text/html; charset=UTF-8'), 'testSavePerDiemAction: The content-type is not html.');
 }
Beispiel #14
0
 public function request($method, $uri, array $parameters = array(), array $files = array(), array $server = array(), $content = null, $changeHistory = true)
 {
     $parameters = array_merge($this->parameters, $parameters);
     $crawler = parent::request($method, $uri, $parameters, $files, $server, $content, $changeHistory);
     if ($crawler->getNode(0) === null) {
         return $this->response->getContent();
     } else {
         return $crawler;
     }
 }
Beispiel #15
0
 public function grabTextFrom($cssOrXPathOrRegex)
 {
     $nodes = $this->match($cssOrXPathOrRegex);
     if ($nodes) {
         return $nodes->first()->text();
     }
     if (@preg_match($cssOrXPathOrRegex, $this->client->getResponse()->getContent(), $matches)) {
         return $matches[1];
     }
     $this->fail("Element that matches '{$cssOrXPathOrRegex}' not found");
 }
Beispiel #16
0
 /**
  * Create authorized client
  *
  * @link http://stackoverflow.com/questions/14957807/symfony2-tests-with-fosuserbundle/27223293#27223293
  * @return Client
  */
 public static function authorizeClient(Client $client)
 {
     $container = $client->getContainer();
     $session = $container->get('session');
     /** @var $userManager \FOS\UserBundle\Doctrine\UserManager */
     $userManager = $container->get('fos_user.user_manager');
     /** @var $loginManager \FOS\UserBundle\Security\LoginManager */
     $loginManager = $container->get('fos_user.security.login_manager');
     $firewallName = $container->getParameter('fos_user.firewall_name');
     /// @todo create fixture for this
     $testUser = $container->getParameter('test_user');
     $user = $userManager->findUserBy(array('username' => $testUser));
     $loginManager->loginUser($firewallName, $user);
     // save the login token into the session and put it in a cookie
     $token = $container->get('security.context')->getToken();
     $session->set('_security_' . $firewallName, serialize($token));
     $session->save();
     $cookie = new Cookie($session->getName(), $session->getId());
     $client->getCookieJar()->set($cookie);
     return $client;
 }
 protected function login(Client $client, $username = '******', $password = '******')
 {
     $client->restart();
     $crawler = $client->request('GET', '/login');
     $this->assertTrue($client->getResponse()->isSuccessful(), 'Response should be successful');
     $form = $crawler->selectButton('Login')->form();
     $client->submit($form, array('_username' => $username, '_password' => $password));
     $this->assertTrue($client->getResponse()->isRedirect(), 'Response should be redirect');
     $crawler = $client->followRedirect();
     $this->assertGreaterThan(0, $crawler->filter('html:contains("Benvenuto")')->count());
 }
Beispiel #18
0
 protected function execute($method = 'GET', $url, $parameters = [], $files = [])
 {
     $this->debugSection("Request headers", $this->headers);
     foreach ($this->headers as $header => $val) {
         $header = str_replace('-', '_', strtoupper($header));
         $this->client->setServerParameter("HTTP_{$header}", $val);
         // Issue #1650 - Symfony BrowserKit changes HOST header to request URL
         if ($header === 'HOST') {
             $this->client->setServerParameter("HTTP_ HOST", $val);
         }
         // Issue #827 - symfony foundation requires 'CONTENT_TYPE' without HTTP_
         if ($this->isFunctional && $header === 'CONTENT_TYPE') {
             $this->client->setServerParameter($header, $val);
         }
     }
     // allow full url to be requested
     if (strpos($url, '://') === false) {
         $url = $this->config['url'] . $url;
     }
     $this->params = $parameters;
     $parameters = $this->encodeApplicationJson($method, $parameters);
     if (is_array($parameters) || $method === 'GET') {
         if (!empty($parameters) && $method === 'GET') {
             $url .= '?' . http_build_query($parameters);
         }
         if ($method == 'GET') {
             $this->debugSection("Request", "{$method} {$url}");
         } else {
             $this->debugSection("Request", "{$method} {$url} " . json_encode($parameters));
         }
         $this->client->request($method, $url, $parameters, $files);
     } else {
         $requestData = $parameters;
         if (!ctype_print($requestData) && false === mb_detect_encoding($requestData, mb_detect_order(), true)) {
             // if the request data has non-printable bytes and it is not a valid unicode string, reformat the
             // display string to signify the presence of request data
             $requestData = '[binary-data length:' . strlen($requestData) . ' md5:' . md5($requestData) . ']';
         }
         $this->debugSection("Request", "{$method} {$url} " . $requestData);
         $this->client->request($method, $url, [], $files, [], $parameters);
     }
     $this->response = (string) $this->connectionModule->_getResponseContent();
     $this->debugSection("Response", $this->response);
     if (count($this->client->getInternalRequest()->getCookies())) {
         $this->debugSection('Cookies', $this->client->getInternalRequest()->getCookies());
     }
     $this->debugSection("Headers", $this->client->getInternalResponse()->getHeaders());
     $this->debugSection("Status", $this->client->getInternalResponse()->getStatus());
 }
Beispiel #19
0
 /**
  * @param $result
  * @return mixed
  */
 protected function redirectIfNecessary($result, $maxRedirects, $redirectCount)
 {
     $locationHeader = $this->client->getInternalResponse()->getHeader('Location');
     if ($locationHeader) {
         if ($redirectCount == $maxRedirects) {
             throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $maxRedirects));
         }
         $this->debugSection('Redirecting to', $locationHeader);
         $result = $this->client->followRedirect();
         $this->debugResponse();
         return $this->redirectIfNecessary($result, $maxRedirects, $redirectCount + 1);
     }
     $this->client->followRedirects(true);
     return $result;
 }
Beispiel #20
0
 /**
  * Sends a XMLRPC method call to remote XMLRPC-server.
  *
  * @param string $methodName
  * @param array $parameters
  */
 public function sendXMLRPCMethodCall($methodName, $parameters = array())
 {
     if (!array_key_exists('Content-Type', $this->headers)) {
         $this->headers['Content-Type'] = 'text/xml';
     }
     foreach ($this->headers as $header => $val) {
         $this->client->setServerParameter("HTTP_{$header}", $val);
     }
     $url = $this->config['url'];
     if (is_array($parameters)) {
         $parameters = $this->scalarizeArray($parameters);
     }
     $requestBody = xmlrpc_encode_request($methodName, array_values($parameters));
     $this->debugSection('Request', $url . PHP_EOL . $requestBody);
     $this->client->request('POST', $url, array(), array(), array(), $requestBody);
     $this->response = $this->client->getInternalResponse()->getContent();
     $this->debugSection('Response', $this->response);
 }
Beispiel #21
0
 protected function execute($method = 'GET', $url, $parameters = [], $files = [])
 {
     $this->debugSection("Request headers", $this->headers);
     if ($parameters instanceof \JsonSerializable) {
         $parameters = $parameters->jsonSerialize();
     }
     foreach ($this->headers as $header => $val) {
         $header = str_replace('-', '_', strtoupper($header));
         $this->client->setServerParameter("HTTP_{$header}", $val);
         // Issue #1650 - Symfony BrowserKit changes HOST header to request URL
         if (strtolower($header) == 'host') {
             $this->client->setServerParameter("HTTP_ HOST", $val);
         }
         // Issue #827 - symfony foundation requires 'CONTENT_TYPE' without HTTP_
         if ($this->isFunctional and $header == 'CONTENT_TYPE') {
             $this->client->setServerParameter($header, $val);
         }
     }
     // allow full url to be requested
     $url = (strpos($url, '://') === false ? $this->config['url'] : '') . $url;
     $this->params = $parameters;
     $parameters = $this->encodeApplicationJson($method, $parameters);
     if (is_array($parameters) || $method == 'GET') {
         if (!empty($parameters) && $method == 'GET') {
             $url .= '?' . http_build_query($parameters);
         }
         if ($method == 'GET') {
             $this->debugSection("Request", "{$method} {$url}");
         } else {
             $this->debugSection("Request", "{$method} {$url} " . json_encode($parameters));
         }
         $this->client->request($method, $url, $parameters, $files);
     } else {
         $this->debugSection("Request", "{$method} {$url} " . $parameters);
         $this->client->request($method, $url, [], $files, [], $parameters);
     }
     $this->response = (string) $this->client->getInternalResponse()->getContent();
     $this->debugSection("Response", $this->response);
     if (count($this->client->getInternalRequest()->getCookies())) {
         $this->debugSection('Cookies', $this->client->getInternalRequest()->getCookies());
     }
     $this->debugSection("Headers", $this->client->getInternalResponse()->getHeaders());
     $this->debugSection("Status", $this->client->getInternalResponse()->getStatus());
 }
 /**
  * test version action
  */
 public function testVersionAction()
 {
     $crawler = $this->client->request('GET', '/secured/opithrm/versions');
     $this->assertTrue($this->client->getResponse()->headers->contains('Content-Type', 'text/html; charset=UTF-8'), 'testVersionAction: The content-type is not a html file.');
 }
 /**
  * Set up the testing
  */
 public function setUp()
 {
     $this->client = static::createClient();
     $this->em = $this->client->getContainer()->get('doctrine')->getManager();
     $this->user = $this->em->getRepository('OpitOpitHrmUserBundle:User')->findOneByUsername('admin');
 }
Beispiel #24
0
 /**
  * {@inheritdoc}
  *
  * @return Response|null A Response instance
  */
 public function getResponse()
 {
     return parent::getResponse();
 }
Beispiel #25
0
 protected function assertPageNotContains($needle, $message = '')
 {
     $constraint = new PageConstraint($needle, $this->_getCurrentUri());
     $this->assertThatItsNot($this->client->getInternalResponse()->getContent(), $constraint, $message);
 }
 protected function debugCookieJar()
 {
     $cookies = $this->client->getCookieJar()->all();
     $cookieStrings = array_map('strval', $cookies);
     $this->debugSection('Cookie Jar', $cookieStrings);
 }
Beispiel #27
0
 /**
  * Constructor.
  *
  * @param array $server The server parameters (equivalent of $_SERVER)
  * @param History $history A History instance to store the browser history
  * @param CookieJar $cookieJar A CookieJar instance to store the cookies
  *
  * @api
  */
 public function __construct(array $server = [], History $history = null, CookieJar $cookieJar = null)
 {
     parent::__construct($server, $history, $cookieJar);
     // TODO: Change the autogenerated stub
 }
 private function createSession(Client $client)
 {
     $client->request('POST', '/sglivechat', array('name' => 'Ismael', 'email' => '*****@*****.**', 'question' => 'This is my comment'));
 }
 protected function createNote(Client $client, $message)
 {
     $client->request('POST', '/notes.json', array('note' => array('message' => $message)));
     $response = $client->getResponse();
     $this->assertJsonResponse($response, Response::HTTP_CREATED);
 }
Beispiel #30
0
 /**
  * Checks that response code is not equal to provided value.
  *
  * @param $code
  */
 public function dontSeeResponseCodeIs($code)
 {
     $this->assertNotEquals($code, $this->client->getInternalResponse()->getStatus());
 }