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->isResponseRedirection();
  129. $this->followRedirection();
  130. $this->isResponseSuccess();
  131. if ('anon.' != ($user = $this->getUser()))
  132. {
  133. // Nous ne sommes pas identifiés
  134. $this->assertEquals($username, $user->getUsername());
  135. // L'utilisateur n'est pas enregistré, il ne doit donc pas être en base
  136. $db_user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
  137. ->findOneByUsername($username)
  138. ;
  139. $this->assertTrue(!is_null($db_user));
  140. }
  141. else
  142. {
  143. $this->assertTrue(false);
  144. }
  145. }
  146. protected function procedure_registration_failure($username, $email, $pass1, $pass2, $token)
  147. {
  148. $this->crawler = $this->client->request('GET', $this->generateUrl('index'));
  149. $this->isResponseSuccess();
  150. $this->assertEquals('anon.', $this->getUser());
  151. $url = $this->generateUrl('register');
  152. // Les mots de passes sont différents
  153. $this->validate_registrate_user_form(
  154. $this->selectForm('form[action="'.$url.'"] input[type="submit"]'),
  155. $username,
  156. $email,
  157. $pass1,
  158. $pass2,
  159. $token
  160. );
  161. $this->isResponseSuccess();
  162. if ('anon.' === ($user = $this->getUser()))
  163. {
  164. // Nous ne sommes pas identifiés
  165. $this->assertEquals('anon.', $user);
  166. // L'utilisateur n'est pas enregistré, il ne doit donc pas être en base
  167. $db_user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
  168. ->findOneByUsername($username)
  169. ;
  170. $this->assertTrue(is_null($db_user));
  171. }
  172. else
  173. {
  174. $this->assertTrue(false);
  175. }
  176. }
  177. /**
  178. * Procédure d'ajout d'un élément
  179. *
  180. * @param string $name
  181. * @param string $url
  182. * @param array $tags
  183. * @param string $group_slug
  184. * @param boolean $need_tags
  185. */
  186. protected function procedure_add_element($name, $url, $tags, $group_slug = null, $need_tags = false)
  187. {
  188. if (!$group_slug)
  189. {
  190. $this->crawler = $this->client->request('GET', $this->generateUrl('home'));
  191. $form_url = $this->generateUrl('element_add');
  192. }
  193. else
  194. {
  195. $this->crawler = $this->client->request('GET', $this->generateUrl('show_group', array('slug' => $group_slug)));
  196. $form_url = $this->generateUrl('element_add', array('group_slug' => $group_slug));
  197. }
  198. $this->isResponseSuccess();
  199. $form = $this->selectForm('form[action="'.$form_url.'"] input[type="submit"]');
  200. $form['element_add[name]'] = $name;
  201. $form['element_add[url]'] = $url;
  202. if (count($tags))
  203. {
  204. $form['element_add[tags]'] = json_encode($tags);
  205. }
  206. if ($need_tags)
  207. {
  208. $form['element_add[need_tags]'] = true;
  209. }
  210. $this->submit($form);
  211. }
  212. /**
  213. * Retourne un utilisateur en allant le chercher en base.
  214. *
  215. * @param string $username
  216. * @return \Muzich\CoreBundle\Entity\User
  217. */
  218. protected function findUserByUsername($username)
  219. {
  220. return $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:User')
  221. ->findOneByUsername($username)
  222. ;
  223. }
  224. /**
  225. * Generates a URL from the given parameters.
  226. *
  227. * @param string $route
  228. * @param array $parameters
  229. * @param boolean $absolute
  230. *
  231. * @return string (url generated)
  232. */
  233. protected function generateUrl($route, $parameters = array(), $absolute = false)
  234. {
  235. /**
  236. * Petit hack pour que les locales ne manque pas
  237. */
  238. if ($route == 'index')
  239. {
  240. if (!array_key_exists('_locale', $parameters))
  241. {
  242. $parameters['_locale'] = 'fr';
  243. }
  244. }
  245. if ($route == 'home')
  246. {
  247. if (!array_key_exists('_locale', $parameters))
  248. {
  249. $parameters['_locale'] = 'fr';
  250. }
  251. }
  252. return $this->client->getContainer()->get('router')->generate($route, $parameters, $absolute);
  253. }
  254. protected function getContainer()
  255. {
  256. return $this->client->getContainer();
  257. }
  258. protected function getSession()
  259. {
  260. return $this->getContainer()->get('session');
  261. }
  262. protected function getCollector($name)
  263. {
  264. return$this->client->getProfile()->getCollector($name);
  265. }
  266. /**
  267. * Retourne le MessageDataCollector en cours
  268. *
  269. * @return Symfony\Bundle\SwiftmailerBundle\DataCollector\MessageDataCollector
  270. */
  271. protected function getMailerMessageDataCollector()
  272. {
  273. return $this->getCollector('swiftmailer');
  274. }
  275. protected function clickOnLink($link)
  276. {
  277. $this->crawler = $this->client->click($link);
  278. }
  279. /**
  280. *
  281. * @return \Doctrine\Bundle\DoctrineBundle\Registry
  282. */
  283. protected function getDoctrine()
  284. {
  285. return $this->client->getContainer()->get('doctrine');
  286. }
  287. /**
  288. * Test l'existance d'un element
  289. *
  290. * @param string $filter
  291. */
  292. protected function exist($filter)
  293. {
  294. $this->assertTrue($this->crawler->filter($filter)->count() > 0);
  295. }
  296. /**
  297. * Test l'inexistance d'un element
  298. *
  299. * @param string $filter
  300. */
  301. protected function notExist($filter)
  302. {
  303. $this->assertFalse($this->crawler->filter($filter)->count() > 0);
  304. }
  305. /**
  306. * Retourne un objet lien
  307. *
  308. * @param string $filter
  309. * @return \Symfony\Component\DomCrawler\Link
  310. */
  311. protected function selectLink($filter)
  312. {
  313. return $this->crawler->filter($filter)->link();
  314. }
  315. // /**
  316. // * Clique sur un link
  317. // *
  318. // * @param type $link
  319. // */
  320. // protected function click($link)
  321. // {
  322. // $this->crawler = $this->client->click($link);
  323. // }
  324. /**
  325. * Retourne un formulaire, en filtrant le BOUTON SUBMIT !!
  326. *
  327. * @param string $filter
  328. * @return \Symfony\Component\DomCrawler\Form
  329. */
  330. protected function selectForm($filter)
  331. {
  332. return $this->crawler->filter($filter)->form();
  333. }
  334. /**
  335. * Soumet un formulaire
  336. *
  337. * @param type $form
  338. */
  339. protected function submit($form, $params = array())
  340. {
  341. $this->crawler = $this->client->submit($form, $params);
  342. }
  343. /**
  344. * Ordonne au client de suivre la redirection
  345. */
  346. protected function followRedirection()
  347. {
  348. $this->crawler = $this->client->followRedirect();
  349. }
  350. /**
  351. * Contrôle le Codestatus de la réponse
  352. *
  353. * @param int $code
  354. */
  355. protected function isStatusCode($code)
  356. {
  357. $this->assertEquals($code, $this->client->getResponse()->getStatusCode());
  358. }
  359. /**
  360. * Contrôle que le CodeStatus de la Response correspond bien a celle d'une
  361. * redirection
  362. */
  363. protected function isResponseRedirection()
  364. {
  365. $this->assertTrue($this->client->getResponse()->isRedirection());
  366. }
  367. /**
  368. * Contrôle que le CodeStatus de la Response correspond bien a celle d'un Ok
  369. */
  370. protected function isResponseSuccess()
  371. {
  372. $this->assertTrue($this->client->getResponse()->isSuccessful());
  373. }
  374. /**
  375. * Contrôle que le CodeStatus de la Response correspond bien a celle d'un Ok
  376. */
  377. protected function isResponseNotFound()
  378. {
  379. $this->assertTrue($this->client->getResponse()->isNotFound());
  380. }
  381. protected function addElementAjax($name, $url, $tags = '', $group_slug = null)
  382. {
  383. $this->crawler = $this->client->request('GET', $this->generateUrl('home'));
  384. $extract = $this->crawler->filter('input[name="element_add[_token]"]')
  385. ->extract(array('value'));
  386. $csrf = $extract[0];
  387. $url_ajax = $this->generateUrl('element_add');
  388. if ($group_slug)
  389. {
  390. $url_ajax = $this->generateUrl('element_add', array('group_slug' => $group_slug));
  391. }
  392. $this->crawler = $this->client->request(
  393. 'POST',
  394. $url_ajax,
  395. array(
  396. 'element_add' => array(
  397. '_token' => $csrf,
  398. 'name' => $name,
  399. 'url' => $url,
  400. 'tags' => $tags
  401. )
  402. ),
  403. array(),
  404. array('HTTP_X-Requested-With' => 'XMLHttpRequest')
  405. );
  406. $this->isResponseSuccess();
  407. $response = json_decode($this->client->getResponse()->getContent(), true);
  408. $this->assertEquals($response['status'], 'success');
  409. $element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  410. ->findOneByName($name)
  411. ;
  412. $this->assertTrue(!is_null($element));
  413. }
  414. /**
  415. * Runs a command and returns it output
  416. *
  417. * @author Alexandre Salomé <alexandre.salome@gmail.com>
  418. */
  419. public function runCommand(Client $client, $command)
  420. {
  421. $application = new Application($client->getKernel());
  422. $application->setAutoExit(false);
  423. $fp = tmpfile();
  424. $input = new StringInput($command);
  425. $output = new StreamOutput($fp);
  426. $application->run($input, $output);
  427. fseek($fp, 0);
  428. $output = '';
  429. while (!feof($fp)) {
  430. $output = fread($fp, 4096);
  431. }
  432. fclose($fp);
  433. return $output;
  434. }
  435. /**
  436. *
  437. * @return \Doctrine\ORM\EntityManager
  438. */
  439. protected function getEntityManager()
  440. {
  441. return $this->getDoctrine()->getEntityManager();
  442. }
  443. /**
  444. * Raccourcis de findOneBy
  445. *
  446. * @param string $entityName
  447. * @param array $params
  448. * @return object
  449. */
  450. protected function findOneBy($entityName, $params)
  451. {
  452. if (!is_array($params))
  453. {
  454. $params = array('name' => $params);
  455. }
  456. return $this->getEntityManager()->getRepository('MuzichCoreBundle:'.$entityName)
  457. ->findOneBy($params);
  458. }
  459. protected function goToPage($url)
  460. {
  461. $this->crawler = $this->client->request('GET', $url);
  462. }
  463. }