FunctionalTest.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. */
  184. protected function procedure_add_element($name, $url, $tags, $group_slug = null)
  185. {
  186. if (!$group_slug)
  187. {
  188. $this->crawler = $this->client->request('GET', $this->generateUrl('home'));
  189. $form_url = $this->generateUrl('element_add');
  190. }
  191. else
  192. {
  193. $this->crawler = $this->client->request('GET', $this->generateUrl('show_group', array('slug' => $group_slug)));
  194. $form_url = $this->generateUrl('element_add', array('group_slug' => $group_slug));
  195. }
  196. $this->isResponseSuccess();
  197. $form = $this->selectForm('form[action="'.$form_url.'"] input[type="submit"]');
  198. $form['element_add[name]'] = $name;
  199. $form['element_add[url]'] = $url;
  200. $form['element_add[tags]'] = json_encode($tags);
  201. $this->submit($form);
  202. }
  203. /**
  204. * Retourne un utilisateur en allant le chercher en base.
  205. *
  206. * @param string $username
  207. * @return \Muzich\CoreBundle\Entity\User
  208. */
  209. protected function findUserByUsername($username)
  210. {
  211. return $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:User')
  212. ->findOneByUsername($username)
  213. ;
  214. }
  215. /**
  216. * Generates a URL from the given parameters.
  217. *
  218. * @param string $route
  219. * @param array $parameters
  220. * @param boolean $absolute
  221. *
  222. * @return string (url generated)
  223. */
  224. protected function generateUrl($route, $parameters = array(), $absolute = false)
  225. {
  226. /**
  227. * Petit hack pour que les locales ne manque pas
  228. */
  229. if ($route == 'index')
  230. {
  231. if (!array_key_exists('_locale', $parameters))
  232. {
  233. $parameters['_locale'] = 'fr';
  234. }
  235. }
  236. if ($route == 'home')
  237. {
  238. if (!array_key_exists('_locale', $parameters))
  239. {
  240. $parameters['_locale'] = 'fr';
  241. }
  242. }
  243. return $this->client->getContainer()->get('router')->generate($route, $parameters, $absolute);
  244. }
  245. protected function getContainer()
  246. {
  247. return $this->client->getContainer();
  248. }
  249. protected function getSession()
  250. {
  251. return $this->getContainer()->get('session');
  252. }
  253. protected function getCollector($name)
  254. {
  255. return$this->client->getProfile()->getCollector($name);
  256. }
  257. /**
  258. * Retourne le MessageDataCollector en cours
  259. *
  260. * @return Symfony\Bundle\SwiftmailerBundle\DataCollector\MessageDataCollector
  261. */
  262. protected function getMailerMessageDataCollector()
  263. {
  264. return $this->getCollector('swiftmailer');
  265. }
  266. protected function clickOnLink($link)
  267. {
  268. $this->crawler = $this->client->click($link);
  269. }
  270. /**
  271. *
  272. * @return \Symfony\Bundle\DoctrineBundle\Registry
  273. */
  274. protected function getDoctrine()
  275. {
  276. return $this->client->getContainer()->get('doctrine');
  277. }
  278. /**
  279. * Test l'existance d'un element
  280. *
  281. * @param string $filter
  282. */
  283. protected function exist($filter)
  284. {
  285. $this->assertTrue($this->crawler->filter($filter)->count() > 0);
  286. }
  287. /**
  288. * Test l'inexistance d'un element
  289. *
  290. * @param string $filter
  291. */
  292. protected function notExist($filter)
  293. {
  294. $this->assertFalse($this->crawler->filter($filter)->count() > 0);
  295. }
  296. /**
  297. * Retourne un objet lien
  298. *
  299. * @param string $filter
  300. * @return \Symfony\Component\DomCrawler\Link
  301. */
  302. protected function selectLink($filter)
  303. {
  304. return $this->crawler->filter($filter)->link();
  305. }
  306. // /**
  307. // * Clique sur un link
  308. // *
  309. // * @param type $link
  310. // */
  311. // protected function click($link)
  312. // {
  313. // $this->crawler = $this->client->click($link);
  314. // }
  315. /**
  316. * Retourne un formulaire, en filtrant le BOUTON SUBMIT !!
  317. *
  318. * @param string $filter
  319. * @return \Symfony\Component\DomCrawler\Form
  320. */
  321. protected function selectForm($filter)
  322. {
  323. return $this->crawler->filter($filter)->form();
  324. }
  325. /**
  326. * Soumet un formulaire
  327. *
  328. * @param type $form
  329. */
  330. protected function submit($form, $params = array())
  331. {
  332. $this->crawler = $this->client->submit($form, $params);
  333. }
  334. /**
  335. * Ordonne au client de suivre la redirection
  336. */
  337. protected function followRedirection()
  338. {
  339. $this->crawler = $this->client->followRedirect();
  340. }
  341. /**
  342. * Contrôle le Codestatus de la réponse
  343. *
  344. * @param int $code
  345. */
  346. protected function isStatusCode($code)
  347. {
  348. $this->assertEquals($code, $this->client->getResponse()->getStatusCode());
  349. }
  350. /**
  351. * Contrôle que le CodeStatus de la Response correspond bien a celle d'une
  352. * redirection
  353. */
  354. protected function isResponseRedirection()
  355. {
  356. $this->assertTrue($this->client->getResponse()->isRedirection());
  357. }
  358. /**
  359. * Contrôle que le CodeStatus de la Response correspond bien a celle d'un Ok
  360. */
  361. protected function isResponseSuccess()
  362. {
  363. $this->assertTrue($this->client->getResponse()->isSuccessful());
  364. }
  365. /**
  366. * Contrôle que le CodeStatus de la Response correspond bien a celle d'un Ok
  367. */
  368. protected function isResponseNotFound()
  369. {
  370. $this->assertTrue($this->client->getResponse()->isNotFound());
  371. }
  372. protected function addElementAjax($name, $url, $tags = '', $group_slug = null)
  373. {
  374. $this->crawler = $this->client->request('GET', $this->generateUrl('home'));
  375. $extract = $this->crawler->filter('input[name="element_add[_token]"]')
  376. ->extract(array('value'));
  377. $csrf = $extract[0];
  378. $url_ajax = $this->generateUrl('element_add');
  379. if ($group_slug)
  380. {
  381. $url_ajax = $this->generateUrl('element_add', array('group_slug' => $group_slug));
  382. }
  383. $this->crawler = $this->client->request(
  384. 'POST',
  385. $url_ajax,
  386. array(
  387. 'element_add' => array(
  388. '_token' => $csrf,
  389. 'name' => $name,
  390. 'url' => $url,
  391. 'tags' => $tags
  392. )
  393. ),
  394. array(),
  395. array('HTTP_X-Requested-With' => 'XMLHttpRequest')
  396. );
  397. $this->isResponseSuccess();
  398. $response = json_decode($this->client->getResponse()->getContent(), true);
  399. $this->assertEquals($response['status'], 'success');
  400. $element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  401. ->findOneByName($name)
  402. ;
  403. $this->assertTrue(!is_null($element));
  404. }
  405. /**
  406. * Runs a command and returns it output
  407. *
  408. * @author Alexandre Salomé <alexandre.salome@gmail.com>
  409. */
  410. public function runCommand(Client $client, $command)
  411. {
  412. $application = new Application($client->getKernel());
  413. $application->setAutoExit(false);
  414. $fp = tmpfile();
  415. $input = new StringInput($command);
  416. $output = new StreamOutput($fp);
  417. $application->run($input, $output);
  418. fseek($fp, 0);
  419. $output = '';
  420. while (!feof($fp)) {
  421. $output = fread($fp, 4096);
  422. }
  423. fclose($fp);
  424. return $output;
  425. }
  426. }