FunctionalTest.php 13KB

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