Skip to content

Instantly share code, notes, and snippets.

@ftdysa
Created February 5, 2014 23:42
Show Gist options
  • Save ftdysa/8835697 to your computer and use it in GitHub Desktop.
Save ftdysa/8835697 to your computer and use it in GitHub Desktop.
<?php
namespace Project\WebsiteBundle\Tests;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\BrowserKit\Cookie;
abstract class ProjectWebTestCase extends WebTestCase {
/*
* {@inheritDoc}
*/
protected static function createClient(array $options = array(), array $server = array())
{
$client = parent::createClient($options, $server);
if (empty($server)) {
$client->setServerParameters(array('HTTP_HOST' => 'devel.mynatnet.com'));
}
return $client;
}
protected function loginAs(Client $client, $username) {
$container = $client->getContainer();
/* @var $em \Doctrine\ORM\EntityManager */
$em = $container->get('doctrine.orm.entity_manager');
$user = $this->loadUser($em, $username);
$session = $container->get('session');
$options = $container->getParameter('session.storage.options');
if (!$options || !isset($options['name'])) {
throw new \InvalidArgumentException("Missing session.storage.options#name");
}
// Since the namespace of the session changed in symfony 2.1, instanceof can be used to check the version.
if ($session instanceof Session) {
$session->setId(uniqid());
}
$client->getCookieJar()->set(new Cookie($options['name'], $session->getId()));
$token = new UsernamePasswordToken($user, null, 'secured_area', $user->getRoles());
$container->get('security.context')->setToken($token);
$session->set('_security_' . 'secured_area', serialize($token));
$session->save();
return $client;
}
private function loadUser(EntityManager $em, $username) {
return $em->getRepository('E:User')->loadUserByUsername($username);
}
}
<?php
namespace Project\WebsiteBundle\Tests\Ticket;
use Project\WebsiteBundle\Tests\ProjectWebTestCase;
class TicketControllerTest extends ProjectWebTestCase {
public function testViewTicket() {
$client = $this->loginAs(static::createClient(), 'mnnsecondary');
$client->followRedirects();
$crawler = $client->request('GET', '/support/tickets/view/407097');
$this->assertGreaterThan(
0,
$crawler->filter('html:contains("Ticket# 407097. 1 X CentOS 5 (32 bit) Operating System service was added.")')->count()
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment