FunctionalTest.php 14KB

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