FunctionalTest.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. <?php
  2. namespace Muzich\CoreBundle\lib;
  3. use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
  4. use Symfony\Bundle\FrameworkBundle\Client;
  5. use Symfony\Component\DomCrawler\Crawler;
  6. use Symfony\Bundle\FrameworkBundle\Console\Application;
  7. use Symfony\Component\Console\Input\StringInput;
  8. use Symfony\Component\Console\Output\StreamOutput;
  9. class FunctionalTest extends WebTestCase
  10. {
  11. /**
  12. *
  13. * @var Client
  14. */
  15. protected $client;
  16. /**
  17. *
  18. * @var Crawler
  19. */
  20. protected $crawler;
  21. protected function outputDebug($content = null)
  22. {
  23. $time = time();
  24. //unlink('.debug/out'.$time.'.html');
  25. if(@mkdir("./debug",0777,true))
  26. {
  27. }
  28. $monfichier = fopen('.debug/out'.$time.'.html', 'a+');
  29. if (!$content)
  30. {
  31. fwrite($monfichier, $this->client->getResponse()->getContent());
  32. }
  33. else
  34. {
  35. fwrite($monfichier, $content);
  36. }
  37. }
  38. /**
  39. * Retourne l'objet User
  40. *
  41. * @return \Muzich\CoreBundle\Entity\User
  42. */
  43. protected function getUser($username = null)
  44. {
  45. if (!$username)
  46. {
  47. return $this->client->getContainer()->get('security.context')->getToken()->getUser();
  48. }
  49. else
  50. {
  51. return $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
  52. ->findOneByUsername($username)
  53. ;
  54. }
  55. }
  56. /**
  57. * @return \Muzich\CoreBundle\Entity\Group
  58. */
  59. protected function getGroup($slug)
  60. {
  61. return $this->getDoctrine()->getRepository('MuzichCoreBundle:Group')
  62. ->findOneBySlug($slug)->getSingleResult()
  63. ;
  64. }
  65. protected function connectUser($login, $password, $client = null)
  66. {
  67. if (!$client)
  68. {
  69. $client = $this->client;
  70. }
  71. $this->crawler = $client->request('GET', $this->generateUrl('index'));
  72. $this->isResponseSuccess();
  73. $this->assertEquals('anon.', $this->getUser());
  74. $this->exist('div.login');
  75. $this->exist('form[action="'.($url = $this->generateUrl('fos_user_security_check')).'"]');
  76. $this->exist('form[action="'.$url.'"] input[id="username"]');
  77. $this->exist('form[action="'.$url.'"] input[id="password"]');
  78. $this->exist('form[action="'.$url.'"] input[id="remember_me"]');
  79. $this->exist('form[action="'.$url.'"] input[type="submit"]');
  80. $form = $this->selectForm('form[action="'.$url.'"] input[type="submit"]');
  81. $form['_username'] = $login;
  82. $form['_password'] = $password;
  83. $form['_remember_me'] = true;
  84. $this->submit($form);
  85. $this->isResponseRedirection();
  86. $this->followRedirection();
  87. $this->isResponseSuccess();
  88. $user = $this->getUser();
  89. if ('anon.' != $user)
  90. {
  91. $this->assertEquals($login, $user->getUsername());
  92. }
  93. else
  94. {
  95. $this->assertTrue(false);
  96. }
  97. }
  98. protected function disconnectUser()
  99. {
  100. $this->crawler = $this->client->request('GET', $this->generateUrl('fos_user_security_logout'));
  101. }
  102. protected function validate_registrate_user_form($form, $username, $email, $pass1, $pass2, $token)
  103. {
  104. $form['fos_user_registration_form[username]'] = $username;
  105. $form['fos_user_registration_form[email]'] = $email;
  106. $form['fos_user_registration_form[plainPassword][first]'] = $pass1;
  107. // Un des mots de passe est incorrect
  108. $form['fos_user_registration_form[plainPassword][second]'] = $pass2;
  109. $form['fos_user_registration_form[token]'] = $token;
  110. $form['fos_user_registration_form[cgu_accepted]']->tick();
  111. $this->submit($form);
  112. }
  113. protected function procedure_registration_success($username, $email, $pass1, $pass2, $token)
  114. {
  115. $this->crawler = $this->client->request('GET', $this->generateUrl('index'));
  116. $this->isResponseSuccess();
  117. $this->assertEquals('anon.', $this->getUser());
  118. $url = $this->generateUrl('register');
  119. // Les mots de passes sont différents
  120. $this->validate_registrate_user_form(
  121. $this->selectForm('form[action="'.$url.'"] input[type="submit"]'),
  122. $username,
  123. $email,
  124. $pass1,
  125. $pass2,
  126. $token
  127. );
  128. $this->outputDebug();
  129. $this->isResponseRedirection();
  130. $this->followRedirection();
  131. $this->isResponseSuccess();
  132. if ('anon.' != ($user = $this->getUser()))
  133. {
  134. // Nous ne sommes pas identifiés
  135. $this->assertEquals($username, $user->getUsername());
  136. // L'utilisateur n'est pas enregistré, il ne doit donc pas être en base
  137. $db_user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
  138. ->findOneByUsername($username)
  139. ;
  140. $this->assertTrue(!is_null($db_user));
  141. }
  142. else
  143. {
  144. $this->assertTrue(false);
  145. }
  146. }
  147. protected function procedure_registration_failure($username, $email, $pass1, $pass2, $token)
  148. {
  149. $this->crawler = $this->client->request('GET', $this->generateUrl('index'));
  150. $this->isResponseSuccess();
  151. $this->assertEquals('anon.', $this->getUser());
  152. $url = $this->generateUrl('register');
  153. // Les mots de passes sont différents
  154. $this->validate_registrate_user_form(
  155. $this->selectForm('form[action="'.$url.'"] input[type="submit"]'),
  156. $username,
  157. $email,
  158. $pass1,
  159. $pass2,
  160. $token
  161. );
  162. $this->isResponseSuccess();
  163. if ('anon.' === ($user = $this->getUser()))
  164. {
  165. // Nous ne sommes pas identifiés
  166. $this->assertEquals('anon.', $user);
  167. // L'utilisateur n'est pas enregistré, il ne doit donc pas être en base
  168. $db_user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
  169. ->findOneByUsername($username)
  170. ;
  171. $this->assertTrue(is_null($db_user));
  172. }
  173. else
  174. {
  175. $this->assertTrue(false);
  176. }
  177. }
  178. /**
  179. * Procédure d'ajout d'un élément
  180. *
  181. * @param string $name
  182. * @param string $url
  183. * @param array $tags
  184. * @param string $group_slug
  185. * @param boolean $need_tags
  186. */
  187. protected function procedure_add_element($name, $url, $tags, $group_slug = null, $need_tags = false)
  188. {
  189. if (!$group_slug)
  190. {
  191. $this->crawler = $this->client->request('GET', $this->generateUrl('home'));
  192. $form_url = $this->generateUrl('element_add');
  193. }
  194. else
  195. {
  196. $this->crawler = $this->client->request('GET', $this->generateUrl('show_group', array('slug' => $group_slug)));
  197. $form_url = $this->generateUrl('element_add', array('group_slug' => $group_slug));
  198. }
  199. $this->isResponseSuccess();
  200. $form = $this->selectForm('form[action="'.$form_url.'"] input[type="submit"]');
  201. $form['element_add[name]'] = $name;
  202. $form['element_add[url]'] = $url;
  203. if (count($tags))
  204. {
  205. $form['element_add[tags]'] = json_encode($tags);
  206. }
  207. if ($need_tags)
  208. {
  209. $form['element_add[need_tags]'] = true;
  210. }
  211. $this->submit($form);
  212. }
  213. /**
  214. * Retourne un utilisateur en allant le chercher en base.
  215. *
  216. * @param string $username
  217. * @return \Muzich\CoreBundle\Entity\User
  218. */
  219. protected function findUserByUsername($username)
  220. {
  221. return $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:User')
  222. ->findOneByUsername($username)
  223. ;
  224. }
  225. /**
  226. * Generates a URL from the given parameters.
  227. *
  228. * @param string $route
  229. * @param array $parameters
  230. * @param boolean $absolute
  231. *
  232. * @return string (url generated)
  233. */
  234. protected function generateUrl($route, $parameters = array(), $absolute = false)
  235. {
  236. /**
  237. * Petit hack pour que les locales ne manque pas
  238. */
  239. if ($route == 'index')
  240. {
  241. if (!array_key_exists('_locale', $parameters))
  242. {
  243. $parameters['_locale'] = 'fr';
  244. }
  245. }
  246. if ($route == 'home')
  247. {
  248. if (!array_key_exists('_locale', $parameters))
  249. {
  250. $parameters['_locale'] = 'fr';
  251. }
  252. }
  253. return $this->client->getContainer()->get('router')->generate($route, $parameters, $absolute);
  254. }
  255. protected function getContainer()
  256. {
  257. return $this->client->getContainer();
  258. }
  259. protected function getSession()
  260. {
  261. return $this->getContainer()->get('session');
  262. }
  263. protected function getCollector($name)
  264. {
  265. return$this->client->getProfile()->getCollector($name);
  266. }
  267. /**
  268. * Retourne le MessageDataCollector en cours
  269. *
  270. * @return Symfony\Bundle\SwiftmailerBundle\DataCollector\MessageDataCollector
  271. */
  272. protected function getMailerMessageDataCollector()
  273. {
  274. return $this->getCollector('swiftmailer');
  275. }
  276. protected function clickOnLink($link)
  277. {
  278. $this->crawler = $this->client->click($link);
  279. }
  280. /**
  281. *
  282. * @return \Symfony\Bundle\DoctrineBundle\Registry
  283. */
  284. protected function getDoctrine()
  285. {
  286. return $this->client->getContainer()->get('doctrine');
  287. }
  288. /**
  289. * Test l'existance d'un element
  290. *
  291. * @param string $filter
  292. */
  293. protected function exist($filter)
  294. {
  295. $this->assertTrue($this->crawler->filter($filter)->count() > 0);
  296. }
  297. /**
  298. * Test l'inexistance d'un element
  299. *
  300. * @param string $filter
  301. */
  302. protected function notExist($filter)
  303. {
  304. $this->assertFalse($this->crawler->filter($filter)->count() > 0);
  305. }
  306. /**
  307. * Retourne un objet lien
  308. *
  309. * @param string $filter
  310. * @return \Symfony\Component\DomCrawler\Link
  311. */
  312. protected function selectLink($filter)
  313. {
  314. return $this->crawler->filter($filter)->link();
  315. }
  316. // /**
  317. // * Clique sur un link
  318. // *
  319. // * @param type $link
  320. // */
  321. // protected function click($link)
  322. // {
  323. // $this->crawler = $this->client->click($link);
  324. // }
  325. /**
  326. * Retourne un formulaire, en filtrant le BOUTON SUBMIT !!
  327. *
  328. * @param string $filter
  329. * @return \Symfony\Component\DomCrawler\Form
  330. */
  331. protected function selectForm($filter)
  332. {
  333. return $this->crawler->filter($filter)->form();
  334. }
  335. /**
  336. * Soumet un formulaire
  337. *
  338. * @param type $form
  339. */
  340. protected function submit($form, $params = array())
  341. {
  342. $this->crawler = $this->client->submit($form, $params);
  343. }
  344. /**
  345. * Ordonne au client de suivre la redirection
  346. */
  347. protected function followRedirection()
  348. {
  349. $this->crawler = $this->client->followRedirect();
  350. }
  351. /**
  352. * Contrôle le Codestatus de la réponse
  353. *
  354. * @param int $code
  355. */
  356. protected function isStatusCode($code)
  357. {
  358. $this->assertEquals($code, $this->client->getResponse()->getStatusCode());
  359. }
  360. /**
  361. * Contrôle que le CodeStatus de la Response correspond bien a celle d'une
  362. * redirection
  363. */
  364. protected function isResponseRedirection()
  365. {
  366. $this->assertTrue($this->client->getResponse()->isRedirection());
  367. }
  368. /**
  369. * Contrôle que le CodeStatus de la Response correspond bien a celle d'un Ok
  370. */
  371. protected function isResponseSuccess()
  372. {
  373. $this->assertTrue($this->client->getResponse()->isSuccessful());
  374. }
  375. /**
  376. * Contrôle que le CodeStatus de la Response correspond bien a celle d'un Ok
  377. */
  378. protected function isResponseNotFound()
  379. {
  380. $this->assertTrue($this->client->getResponse()->isNotFound());
  381. }
  382. protected function addElementAjax($name, $url, $tags = '', $group_slug = null)
  383. {
  384. $this->crawler = $this->client->request('GET', $this->generateUrl('home'));
  385. $extract = $this->crawler->filter('input[name="element_add[_token]"]')
  386. ->extract(array('value'));
  387. $csrf = $extract[0];
  388. $url_ajax = $this->generateUrl('element_add');
  389. if ($group_slug)
  390. {
  391. $url_ajax = $this->generateUrl('element_add', array('group_slug' => $group_slug));
  392. }
  393. $this->crawler = $this->client->request(
  394. 'POST',
  395. $url_ajax,
  396. array(
  397. 'element_add' => array(
  398. '_token' => $csrf,
  399. 'name' => $name,
  400. 'url' => $url,
  401. 'tags' => $tags
  402. )
  403. ),
  404. array(),
  405. array('HTTP_X-Requested-With' => 'XMLHttpRequest')
  406. );
  407. $this->isResponseSuccess();
  408. $response = json_decode($this->client->getResponse()->getContent(), true);
  409. $this->assertEquals($response['status'], 'success');
  410. $element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  411. ->findOneByName($name)
  412. ;
  413. $this->assertTrue(!is_null($element));
  414. }
  415. /**
  416. * Runs a command and returns it output
  417. *
  418. * @author Alexandre Salomé <alexandre.salome@gmail.com>
  419. */
  420. public function runCommand(Client $client, $command)
  421. {
  422. $application = new Application($client->getKernel());
  423. $application->setAutoExit(false);
  424. $fp = tmpfile();
  425. $input = new StringInput($command);
  426. $output = new StreamOutput($fp);
  427. $application->run($input, $output);
  428. fseek($fp, 0);
  429. $output = '';
  430. while (!feof($fp)) {
  431. $output = fread($fp, 4096);
  432. }
  433. fclose($fp);
  434. return $output;
  435. }
  436. /**
  437. *
  438. * @return \Doctrine\ORM\EntityManager
  439. */
  440. protected function getEntityManager()
  441. {
  442. return $this->getDoctrine()->getEntityManager();
  443. }
  444. /**
  445. * Raccourcis de findOneBy
  446. *
  447. * @param string $entityName
  448. * @param array $params
  449. * @return object
  450. */
  451. protected function findOneBy($entityName, $params)
  452. {
  453. if (!is_array($params))
  454. {
  455. $params = array('name' => $params);
  456. }
  457. return $this->getEntityManager()->getRepository('MuzichCoreBundle:'.$entityName)
  458. ->findOneBy($params);
  459. }
  460. protected function goToPage($url)
  461. {
  462. $this->crawler = $this->client->request('GET', $url);
  463. }
  464. }