OtWebTestCase.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. <?php
  2. namespace App\Tests\Application;
  3. use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
  4. use ApiPlatform\Symfony\Bundle\Test\Client;
  5. use App\Entity\Access\Access;
  6. use App\Enum\Booking\VisibilityEnum;
  7. use App\Enum\Core\ContactPointTypeEnum;
  8. use App\Enum\Core\TimeZoneEnum;
  9. use App\Enum\Education\AdvancedEducationNotationTypeEnum;
  10. use App\Enum\Education\CycleEnum;
  11. use App\Enum\Education\PeriodicityEnum;
  12. use App\Enum\Organization\BulletinOutputEnum;
  13. use App\Enum\Organization\BulletinPeriodEnum;
  14. use App\Enum\Organization\LegalEnum;
  15. use App\Enum\Organization\PrincipalTypeEnum;
  16. use App\Enum\Organization\SendToBulletinEnum;
  17. use App\Enum\Organization\SettingsProductEnum;
  18. use App\Tests\Fixture\Factory\Access\AccessFactory;
  19. use App\Tests\Fixture\Factory\Billing\BillingSettingFactory;
  20. use App\Tests\Fixture\Factory\Billing\ResidenceAreaFactory;
  21. use App\Tests\Fixture\Factory\Booking\EventFactory;
  22. use App\Tests\Fixture\Factory\Core\ContactPointFactory;
  23. use App\Tests\Fixture\Factory\Education\CycleFactory;
  24. use App\Tests\Fixture\Factory\Education\EducationTimingFactory;
  25. use App\Tests\Fixture\Factory\Mobyt\MobytUserStatusFactory;
  26. use App\Tests\Fixture\Factory\Network\NetworkFactory;
  27. use App\Tests\Fixture\Factory\Network\NetworkOrganizationFactory;
  28. use App\Tests\Fixture\Factory\Organization\OrganizationFactory;
  29. use App\Tests\Fixture\Factory\Organization\ParametersFactory;
  30. use App\Tests\Fixture\Factory\Organization\SettingsFactory;
  31. use App\Tests\Fixture\Factory\Organization\SubdomainFactory;
  32. use App\Tests\Fixture\Factory\Person\PersonFactory;
  33. use Doctrine\Common\DataFixtures\Purger\ORMPurger;
  34. use Doctrine\ORM\EntityManagerInterface;
  35. use Monolog\Formatter\LineFormatter;
  36. use Monolog\Handler\StreamHandler;
  37. use Monolog\Logger;
  38. use Symfony\Component\HttpFoundation\Request;
  39. use Symfony\Contracts\HttpClient\ResponseInterface;
  40. use Zenstruck\Foundry\Proxy;
  41. /**
  42. * Base class for applicative tests.
  43. */
  44. abstract class OtWebTestCase extends ApiTestCase
  45. {
  46. protected EntityManagerInterface $em;
  47. protected Client $client;
  48. protected Access|Proxy|null $user = null;
  49. protected ?string $securityToken = null;
  50. protected Logger $logger;
  51. /**
  52. * Executed before each test.
  53. *
  54. * @throws \Exception
  55. */
  56. protected function setUp(): void
  57. {
  58. // Initialisation du logger
  59. $this->logger = new Logger('Test applicatif');
  60. $handler = new StreamHandler('php://stdout', Logger::DEBUG);
  61. $formatter = new LineFormatter(
  62. "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n",
  63. 'Y-m-d H:i:s'
  64. );
  65. $handler->setFormatter($formatter);
  66. $this->logger->pushHandler($handler);
  67. // Boot le kernel symfony et récupère l'entity manager
  68. // @see https://symfony.com/doc/current/testing.html#retrieving-services-in-the-test
  69. self::bootKernel();
  70. $this->em = static::getContainer()->get(EntityManagerInterface::class);
  71. // Purge DB before populating new fixtures
  72. $this->purgeDb();
  73. $this->logger->info('Database purged');
  74. // Définit les fixtures et flush
  75. $this->loadFixtures();
  76. $this->em->flush();
  77. // Instancie le client qui exécutera les requêtes à l'api
  78. // @see https://symfony.com/doc/current/testing.html#making-requests
  79. $this->client = static::createClient();
  80. }
  81. protected function purgeDb()
  82. {
  83. if (!preg_match('/.*test.*/', $this->em->getConnection()->getDatabase())) {
  84. throw new \RuntimeException("The DB name shall contain 'test' in its name to be purge");
  85. }
  86. $this->em->getConnection()->exec('SET FOREIGN_KEY_CHECKS = 0;');
  87. $purger = new ORMPurger($this->em);
  88. $purger->setPurgeMode(ORMPurger::PURGE_MODE_DELETE);
  89. $purger->purge();
  90. $this->resetAutoIncrement();
  91. $this->em->getConnection()->exec('SET FOREIGN_KEY_CHECKS = 1;');
  92. }
  93. protected function resetAutoIncrement()
  94. {
  95. $connection = $this->em->getConnection();
  96. $schemaManager = $connection->getSchemaManager();
  97. foreach ($schemaManager->listTableNames() as $tableName) {
  98. $connection->executeStatement("ALTER TABLE $tableName AUTO_INCREMENT = 1;");
  99. }
  100. }
  101. /**
  102. * Create and persist the fixtures (do not flush).
  103. *
  104. * @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#same-entities-used-in-these-docs
  105. */
  106. protected function loadFixtures(): void
  107. {
  108. $adminEbag = PersonFactory::createOne(
  109. [
  110. 'username' => 'ebag',
  111. 'password' => 'password',
  112. ]
  113. );
  114. $personOfOtherOrganization = PersonFactory::createOne(
  115. [
  116. 'username' => 'intruOfRoot',
  117. 'password' => 'password',
  118. ]
  119. );
  120. $student = PersonFactory::createOne([
  121. 'username' => 'studentEbag',
  122. 'password' => 'password',
  123. ]);
  124. $contactPoint = ContactPointFactory::createOne([
  125. 'contactType' => ContactPointTypeEnum::PRINCIPAL,
  126. ]);
  127. $parameters = ParametersFactory::createOne([
  128. 'educationPeriodicity' => PeriodicityEnum::MONTHLY,
  129. 'financialDate' => new \DateTime(),
  130. 'musicalDate' => new \DateTime(),
  131. 'startCourseDate' => new \DateTime(),
  132. 'endCourseDate' => new \DateTime(),
  133. 'average' => 20,
  134. 'editCriteriaNotationByAdminOnly' => true,
  135. 'smsSenderName' => 'MySender',
  136. 'logoDonorsMove' => false,
  137. 'subDomain' => 'subdomain',
  138. 'website' => 'https://www.example.com',
  139. 'otherWebsite' => 'https://www.otherwebsite.com',
  140. 'customDomain' => 'https://www.customdomain.com',
  141. 'desactivateOpentalentSiteWeb' => false,
  142. 'bulletinPeriod' => BulletinPeriodEnum::YEAR,
  143. 'bulletinWithTeacher' => false,
  144. 'bulletinPrintAddress' => false,
  145. 'bulletinSignatureDirector' => true,
  146. 'bulletinDisplayLevelAcquired' => true,
  147. 'bulletinShowEducationWithoutEvaluation' => false,
  148. 'bulletinViewTestResults' => false,
  149. 'bulletinShowAbsences' => false,
  150. 'bulletinShowAverages' => true,
  151. 'bulletinOutput' => BulletinOutputEnum::SEND_BY_EMAIL,
  152. 'bulletinEditWithoutEvaluation' => true,
  153. 'bulletinReceiver' => SendToBulletinEnum::STUDENTS_AND_THEIR_GUARDIANS,
  154. 'usernameSMS' => '2iosinterne',
  155. 'passwordSMS' => '2iosot74',
  156. 'showAdherentList' => true,
  157. 'studentsAreAdherents' => false,
  158. 'timezone' => TimeZoneEnum::EUROPE_PARIS,
  159. 'advancedEducationNotationType' => AdvancedEducationNotationTypeEnum::BY_EDUCATION,
  160. 'sendAttendanceEmail' => true,
  161. 'sendAttendanceSms' => true,
  162. 'generateAttendanceReport' => true,
  163. 'consultPedagogicResult' => true,
  164. 'consultTeacherListing' => true,
  165. 'periodValidation' => true,
  166. ]);
  167. $parameters2 = ParametersFactory::createOne([
  168. 'educationPeriodicity' => PeriodicityEnum::MONTHLY,
  169. 'financialDate' => new \DateTime(),
  170. 'musicalDate' => new \DateTime(),
  171. 'startCourseDate' => new \DateTime(),
  172. 'endCourseDate' => new \DateTime(),
  173. 'average' => 20,
  174. 'editCriteriaNotationByAdminOnly' => true,
  175. 'smsSenderName' => 'toto',
  176. 'logoDonorsMove' => false,
  177. 'subDomain' => 'subdomain',
  178. 'website' => 'https://www.toto.com',
  179. 'otherWebsite' => 'https://www.toto.com',
  180. 'customDomain' => 'https://www.toto.com',
  181. 'desactivateOpentalentSiteWeb' => false,
  182. 'bulletinPeriod' => BulletinPeriodEnum::YEAR,
  183. 'bulletinWithTeacher' => false,
  184. 'bulletinPrintAddress' => false,
  185. 'bulletinSignatureDirector' => true,
  186. 'bulletinDisplayLevelAcquired' => true,
  187. 'bulletinShowEducationWithoutEvaluation' => false,
  188. 'bulletinViewTestResults' => false,
  189. 'bulletinShowAbsences' => false,
  190. 'bulletinShowAverages' => true,
  191. 'bulletinOutput' => BulletinOutputEnum::SEND_BY_EMAIL,
  192. 'bulletinEditWithoutEvaluation' => true,
  193. 'bulletinReceiver' => SendToBulletinEnum::STUDENTS_AND_THEIR_GUARDIANS,
  194. 'usernameSMS' => 'toto',
  195. 'passwordSMS' => 'toto',
  196. 'showAdherentList' => true,
  197. 'studentsAreAdherents' => false,
  198. 'timezone' => TimeZoneEnum::EUROPE_PARIS,
  199. 'advancedEducationNotationType' => AdvancedEducationNotationTypeEnum::BY_EDUCATION,
  200. 'sendAttendanceEmail' => true,
  201. 'sendAttendanceSms' => true,
  202. 'generateAttendanceReport' => true,
  203. 'consultPedagogicResult' => true,
  204. 'consultTeacherListing' => true,
  205. 'periodValidation' => true,
  206. ]);
  207. $organization = OrganizationFactory::createOne([
  208. 'legalStatus' => LegalEnum::ASSOCIATION_LAW_1901,
  209. 'principalType' => PrincipalTypeEnum::NATIONAL_FEDERATION,
  210. 'name' => 'Root',
  211. 'parameters' => $parameters,
  212. 'siretNumber' => '34919841600035',
  213. 'identifier' => 'FR042100000050',
  214. ]);
  215. $network1 = NetworkFactory::createOne([
  216. 'name' => 'Network 1',
  217. 'logo' => 'logo',
  218. 'url' => 'https://www.network1.com',
  219. ]);
  220. $network2 = NetworkFactory::createOne([
  221. 'name' => 'Network 2',
  222. 'logo' => 'logo',
  223. 'url' => 'https://www.network2.com',
  224. ]);
  225. $cmfNetwork = NetworkFactory::createOne([
  226. 'name' => 'CMF',
  227. 'logo' => 'logo',
  228. 'url' => 'https://www.cmf.com',
  229. ]);
  230. $networkOrganization = NetworkOrganizationFactory::createOne([
  231. 'network' => $cmfNetwork,
  232. 'organization' => $organization,
  233. 'startDate' => new \DateTime('2001-01-01'),
  234. 'endDate' => new \DateTime('2031-12-31'),
  235. 'leadingCause' => 'leadingCause',
  236. ]);
  237. $billingSetting = BillingSettingFactory::createOne([
  238. 'organization' => $organization,
  239. ]);
  240. $residenceArea = ResidenceAreaFactory::createOne([
  241. 'label' => 'Résidence 1',
  242. 'billingSetting' => $billingSetting,
  243. ]);
  244. $organization2 = OrganizationFactory::createOne([
  245. 'legalStatus' => LegalEnum::ASSOCIATION_LAW_1901,
  246. 'principalType' => PrincipalTypeEnum::NATIONAL_FEDERATION,
  247. 'name' => 'Other Organization',
  248. 'parameters' => $parameters2,
  249. ]);
  250. $settings2 = SettingsFactory::createOne([
  251. 'product' => SettingsProductEnum::SCHOOL_PREMIUM,
  252. 'organization' => $organization2,
  253. 'modules' => ['BillingAdministration'],
  254. ]);
  255. $mobyteUserStatus = MobytUserStatusFactory::createOne([
  256. 'organizationId' => $organization->getId(),
  257. 'active' => true,
  258. 'amount' => 100,
  259. 'money' => 100,
  260. ]);
  261. $cycle = CycleFactory::createOne([
  262. 'organization' => $organization,
  263. 'label' => 'Cycle 1',
  264. 'cycleEnum' => CycleEnum::CYCLE_1,
  265. ]);
  266. $settings = SettingsFactory::createOne([
  267. 'product' => SettingsProductEnum::SCHOOL_PREMIUM,
  268. 'organization' => $organization,
  269. 'modules' => [
  270. 'Sms' => true,
  271. // 'BillingAdministration' => true,
  272. ],
  273. ]);
  274. $educationTimings = EducationTimingFactory::createOne([
  275. 'organization' => $organization,
  276. 'timing' => 45,
  277. ]);
  278. $educationTimings2 = EducationTimingFactory::createOne([
  279. 'organization' => $organization2,
  280. 'timing' => 60,
  281. ]);
  282. $subdomain = SubdomainFactory::createOne([
  283. 'organization' => $organization,
  284. 'subdomain' => 'subdomain',
  285. 'active' => true,
  286. ]);
  287. $event = EventFactory::createOne([
  288. 'organization' => $organization,
  289. 'name' => 'My event',
  290. 'datetimeStart' => new \DateTime(),
  291. 'datetimeEnd' => new \DateTime(),
  292. 'visibility' => VisibilityEnum::PUBLIC_VISIBILITY,
  293. ]);
  294. $this->user = AccessFactory::createOne([
  295. 'person' => $adminEbag,
  296. 'organization' => $organization,
  297. 'roles' => ['ROLE_ADMIN', 'ROLE_ADMIN_CORE', 'ROLE_SUPER_ADMIN', 'ROLE_ORGANIZATION_VIEW', 'ROLE_ORGANIZATION'],
  298. 'adminAccess' => true,
  299. 'activityYear' => 2021,
  300. ]);
  301. $accessWithNoRole = AccessFactory::createOne([
  302. 'person' => $student,
  303. 'organization' => $organization,
  304. 'roles' => ['ROLE_STUDENT'],
  305. 'adminAccess' => false,
  306. ]);
  307. $acccesFromOtherOrganization = AccessFactory::createOne([
  308. 'person' => $personOfOtherOrganization,
  309. 'organization' => $organization2,
  310. 'roles' => ['ROLE_ADMIN', 'ROLE_ADMIN_CORE', 'ROLE_SUPER_ADMIN', 'ROLE_ORGANIZATION_VIEW', 'ROLE_ORGANIZATION'],
  311. 'adminAccess' => true,
  312. ]);
  313. $this->logger->info('User created in loadFixture: ', [
  314. 'id' => $this->user->getId(),
  315. 'username' => $this->user->getPerson()->getUsername(),
  316. 'roles' => $this->user->getRoles(),
  317. 'organization' => $this->user->getOrganization()->getName(),
  318. 'billingSetting' => $this->user->getOrganization()->getBillingSetting()->getId(),
  319. ]);
  320. }
  321. /**
  322. * Send a requests, parse the hydra response and return an object or a Collection.
  323. *
  324. * @param array<mixed> $data
  325. * @param array<mixed> $headers
  326. */
  327. protected function request(string $method, string $route, ?array $data = null, array $headers = []): ResponseInterface
  328. {
  329. if ($this->user) {
  330. $headers = array_merge(
  331. ['x-accessid' => $this->user->getId(), 'authorization' => 'BEARER '.$this->securityToken],
  332. $headers
  333. );
  334. }
  335. $parameters = ['headers' => $headers];
  336. if ($data) {
  337. $parameters['json'] = $data;
  338. }
  339. return $this->client->request(
  340. $method,
  341. $route,
  342. $parameters
  343. );
  344. }
  345. /**
  346. * Send a GET request and return the response parsed content.
  347. *
  348. * @param array<mixed> $headers
  349. */
  350. protected function get(string $route, array $headers = []): ResponseInterface
  351. {
  352. return $this->request(
  353. Request::METHOD_GET,
  354. $route,
  355. null,
  356. $headers
  357. );
  358. }
  359. /**
  360. * Send a PUT request and return the response parsed content.
  361. *
  362. * @param array<mixed> $data
  363. * @param array<mixed> $headers
  364. */
  365. protected function put(string $route, array $data, array $headers = []): ResponseInterface
  366. {
  367. return $this->request(
  368. Request::METHOD_PUT,
  369. $route,
  370. $data,
  371. $headers
  372. );
  373. }
  374. /**
  375. * Send a POST request and return the response parsed content.
  376. *
  377. * @param array<mixed> $data
  378. * @param array<mixed> $headers
  379. */
  380. protected function post(string $route, array $data, array $headers = []): ResponseInterface
  381. {
  382. return $this->request(
  383. Request::METHOD_POST,
  384. $route,
  385. $data,
  386. $headers
  387. );
  388. }
  389. /**
  390. * Send a DELETE request and return the response parsed content.
  391. *
  392. * @param array<mixed> $headers
  393. */
  394. protected function delete(string $route, array $headers = []): ResponseInterface
  395. {
  396. return $this->request(
  397. Request::METHOD_DELETE,
  398. $route,
  399. null,
  400. $headers
  401. );
  402. }
  403. /**
  404. * Login as the given Access user.
  405. *
  406. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  407. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  408. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  409. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  410. */
  411. public function loginAs()
  412. {
  413. $access = $this->em->getRepository(Access::class)->find(1);
  414. $person = $access->getPerson();
  415. $response = $this->post(
  416. '/login_check',
  417. ['username' => $person->getUsername(), 'password' => $person->getPassword()]
  418. );
  419. $content = $response->getContent();
  420. $decodedContent = json_decode($content);
  421. // Vérifier que le token est présent
  422. if (!isset($decodedContent->token)) {
  423. throw new \Exception('Token not found in response');
  424. }
  425. $this->securityToken = $decodedContent->token;
  426. $this->user = $access;
  427. }
  428. /**
  429. * Login as the given Access user.
  430. *
  431. * @return void
  432. *
  433. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  434. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  435. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  436. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  437. */
  438. public function loginAsStudent()
  439. {
  440. // on récupère l'access qui a l'id 641003 dans l'entity manager
  441. $access = $this->em->getRepository(Access::class)->find(2);
  442. $person = $access->getPerson();
  443. $response = $this->post(
  444. '/login_check',
  445. ['username' => $person->getUsername(), 'password' => $person->getPassword()]
  446. );
  447. $content = $response->getContent();
  448. $this->securityToken = json_decode($content)->token;
  449. $this->user = $access;
  450. }
  451. /**
  452. * Login as the given Access user.
  453. *
  454. * @return void
  455. *
  456. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  457. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  458. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  459. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  460. */
  461. public function loginAsintruOfRoot()
  462. {
  463. $access = $this->em->getRepository(Access::class)->find(3);
  464. $person = $access->getPerson();
  465. $response = $this->post(
  466. '/login_check',
  467. ['username' => $person->getUsername(), 'password' => $person->getPassword()]
  468. );
  469. $content = $response->getContent();
  470. $this->securityToken = json_decode($content)->token;
  471. $this->user = $access;
  472. }
  473. /**
  474. * Assert that the response has the expected status code and is well formated.
  475. */
  476. protected function validateCollectionSchema(string $resourceClass, int $expectedStatus = 200): void
  477. {
  478. $this->assertResponseStatusCodeSame($expectedStatus);
  479. if ($expectedStatus == 200) {
  480. $this->assertResponseIsSuccessful();
  481. }
  482. // Asserts that the returned content type is JSON-LD (the default)
  483. $this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
  484. // Asserts that the returned JSON is validated by the JSON Schema generated for this resource by API Platform
  485. // >>> Issue with the json typed PublicStructure::addresses properties
  486. // $this->assertMatchesResourceCollectionJsonSchema($resourceClass);
  487. }
  488. }