|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Tests; |
| 4 | + |
| 5 | +use Doctrine\ORM\EntityManager; |
| 6 | +use App\Entity\User; |
| 7 | +use Symfony\Bundle\FrameworkBundle\Client; |
| 8 | +use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; |
| 9 | +use Symfony\Component\BrowserKit\Cookie; |
| 10 | +use Symfony\Component\HttpFoundation\Session\Session; |
| 11 | +use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; |
| 12 | + |
| 13 | +class ComPassManWebTestCase extends WebTestCase |
| 14 | +{ |
| 15 | + /** @var Client $client */ |
| 16 | + protected $client = null; |
| 17 | + |
| 18 | + /** @var EntityManager $entityManager */ |
| 19 | + protected $entityManager; |
| 20 | + |
| 21 | + /** @var Session $session */ |
| 22 | + protected $session; |
| 23 | + |
| 24 | + protected $parameters = [ |
| 25 | + 'test_user_id' => null, |
| 26 | + 'firewall_name' => 'main', |
| 27 | + 'firewall_context' => 'main' |
| 28 | + ]; |
| 29 | + |
| 30 | + /** @var null|User */ |
| 31 | + protected $user = null; |
| 32 | + |
| 33 | + public function setUp() |
| 34 | + { |
| 35 | + $this->client = static::createClient(); |
| 36 | + $this->client->followRedirects(true); |
| 37 | + $this->client->setMaxRedirects(10); |
| 38 | + $this->client->disableReboot(); |
| 39 | + |
| 40 | + $this->session = $this->client->getContainer()->get('session'); |
| 41 | + |
| 42 | + $this->entityManager = $this->client->getContainer()->get('doctrine.orm.entity_manager'); |
| 43 | + //dump($this->entityManager); |
| 44 | + $this->entityManager->beginTransaction(); |
| 45 | + |
| 46 | + $this->parameters['test_user_id'] = static::$kernel->getContainer()->getParameter('test_user_id'); |
| 47 | + $user = $this->entityManager->getRepository(User::class)->find($this->parameters['test_user_id']); |
| 48 | + $this->user = $user; |
| 49 | + } |
| 50 | + |
| 51 | + protected function logIn() |
| 52 | + { |
| 53 | + $session = $this->session; |
| 54 | + |
| 55 | + $userId = $this->parameters['test_user_id']; |
| 56 | + $user = $this->entityManager->getRepository(User::class)->find($userId); |
| 57 | + |
| 58 | + $token = new UsernamePasswordToken($user, null, $this->parameters['firewall_name'], ['ROLE_SUPER_ADMIN']); |
| 59 | + $session->set('_security_' . $this->parameters['firewall_context'], serialize($token)); |
| 60 | + $session->save(); |
| 61 | + |
| 62 | + $cookie = new Cookie($session->getName(), $session->getId()); |
| 63 | + $this->client->getCookieJar()->set($cookie); |
| 64 | + |
| 65 | + $this->user = $user; |
| 66 | + } |
| 67 | + |
| 68 | + protected function tearDown() |
| 69 | + { |
| 70 | + $this->entityManager->rollback(); |
| 71 | + parent::tearDown(); |
| 72 | + |
| 73 | + $this->entityManager->close(); |
| 74 | + $this->entityManager = null; |
| 75 | + } |
| 76 | +} |
0 commit comments