FunctionalTest.php 13KB

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