FunctionalTest.php 13KB

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