OtWebTestCase.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. <?php
  2. namespace App\Tests\Application;
  3. use App\Entity\Access\Access;
  4. use App\Entity\Person\Person;
  5. use App\Entity\Public\FederationStructure;
  6. use App\Enum\Organization\LegalEnum;
  7. use App\Enum\Organization\PrincipalTypeEnum;
  8. use App\Enum\Organization\SettingsProductEnum;
  9. use App\Tests\Fixture\Factory\Access\AccessFactory;
  10. use App\Tests\Fixture\Factory\Organization\OrganizationFactory;
  11. use App\Tests\Fixture\Factory\Organization\SettingsFactory;
  12. use App\Tests\Fixture\Factory\Person\PersonFactory;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Doctrine\Common\DataFixtures\Purger\ORMPurger;
  15. use Symfony\Bundle\SecurityBundle\Security;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\DomCrawler\Crawler;
  18. use ApiPlatform\Symfony\Bundle\Test\Client;
  19. use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
  20. use Symfony\Contracts\HttpClient\ResponseInterface;
  21. use Zenstruck\Foundry\Proxy;
  22. /**
  23. * Base class for applicative tests
  24. */
  25. abstract class OtWebTestCase extends ApiTestCase
  26. {
  27. protected EntityManagerInterface $em;
  28. protected Client $client;
  29. protected Access | Proxy | null $user = null;
  30. protected ?string $securityToken = null;
  31. /**
  32. * Executed before each test
  33. *
  34. * @return void
  35. * @throws \Exception
  36. */
  37. public function setup(): void {
  38. // Boot le kernel symfony et récupère l'entity manager
  39. // @see https://symfony.com/doc/current/testing.html#retrieving-services-in-the-test
  40. self::bootKernel();
  41. $this->em = static::getContainer()->get(EntityManagerInterface::class);
  42. // Purge DB before populating new fixtures
  43. $this->purgeDb();
  44. // Définit les fixtures et flush
  45. $this->loadFixture();
  46. $this->em->flush();
  47. // Instancie le client qui exécutera les requêtes à l'api
  48. // @see https://symfony.com/doc/current/testing.html#making-requests
  49. $this->client = static::createClient();
  50. }
  51. /**
  52. * Delete all DB records before populating fixtures.
  53. *
  54. * @return void
  55. * @throws \Doctrine\DBAL\Exception
  56. */
  57. private function purgeDb() {
  58. if (!preg_match('/.*test.*/', $this->em->getConnection()->getDatabase())) {
  59. throw new \RuntimeException("The DB name shall contain 'test' in its name to be purge");
  60. }
  61. $this->em->getConnection()->exec('SET FOREIGN_KEY_CHECKS = 0;');
  62. $purger = new ORMPurger($this->em);
  63. $purger->setPurgeMode(ORMPurger::PURGE_MODE_DELETE);
  64. $purger->purge();
  65. $this->em->getConnection()->exec('SET FOREIGN_KEY_CHECKS = 1;');
  66. }
  67. /**
  68. * Create and persist the fixtures (do not flush)
  69. *
  70. * @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#same-entities-used-in-these-docs
  71. *
  72. * @return void
  73. */
  74. protected function loadFixture(): void {
  75. $person = PersonFactory::createOne(
  76. [
  77. 'username' => 'username',
  78. 'password' => 'password'
  79. ]
  80. );
  81. $organization = OrganizationFactory::createOne([
  82. 'legalStatus' => LegalEnum::ASSOCIATION_LAW_1901()->getValue(),
  83. 'principalType' => PrincipalTypeEnum::ARTISTIC_EDUCATION_ONLY()->getValue(),
  84. 'name' => 'My Organization'
  85. ]);
  86. SettingsFactory::createOne([
  87. 'product' => SettingsProductEnum::ARTIST(),
  88. 'organization' => $organization
  89. ]);
  90. $this->user = AccessFactory::createOne([
  91. 'person' => $person,
  92. 'organization' => $organization,
  93. 'roles' => ['ROLE_USERS_VIEW']
  94. ]);
  95. }
  96. /**
  97. * Send a requests, parse the hydra response and return an object or a Collection
  98. *
  99. * @param string $method
  100. * @param string $route
  101. * @param array<mixed> $data
  102. * @param array<mixed> $headers
  103. * @return ResponseInterface
  104. */
  105. protected function request(string $method, string $route, array | null $data = null, array $headers = []): ResponseInterface {
  106. if ($this->user) {
  107. $headers = array_merge(
  108. ['x-accessid' => $this->user->getId(), 'authorization' => 'BEARER ' . $this->securityToken],
  109. $headers
  110. );
  111. }
  112. $parameters = ['headers' => $headers];
  113. if ($data) {
  114. $parameters['json'] = $data;
  115. }
  116. return $this->client->request(
  117. $method,
  118. $route,
  119. $parameters
  120. );
  121. }
  122. /**
  123. * Send a GET request and return the response parsed content
  124. *
  125. * @param string $route
  126. * @param array<mixed> $headers
  127. * @return ResponseInterface
  128. */
  129. protected function get(string $route, array $headers = []): ResponseInterface {
  130. return $this->request(
  131. Request::METHOD_GET,
  132. $route,
  133. null,
  134. $headers
  135. );
  136. }
  137. /**
  138. * Send a PUT request and return the response parsed content
  139. *
  140. * @param string $route
  141. * @param array<mixed> $data
  142. * @param array<mixed> $headers
  143. * @return ResponseInterface
  144. */
  145. protected function put(string $route, array $data, array $headers = []): ResponseInterface {
  146. return $this->request(
  147. Request::METHOD_PUT,
  148. $route,
  149. $data,
  150. $headers
  151. );
  152. }
  153. /**
  154. * Send a POST request and return the response parsed content
  155. *
  156. * @param string $route
  157. * @param array<mixed> $data
  158. * @param array<mixed> $headers
  159. * @return ResponseInterface
  160. */
  161. protected function post(string $route, array $data, array $headers = []): ResponseInterface {
  162. return $this->request(
  163. Request::METHOD_POST,
  164. $route,
  165. $data,
  166. $headers
  167. );
  168. }
  169. /**
  170. * Send a DELETE request and return the response parsed content
  171. *
  172. * @param string $route
  173. * @param array<mixed> $headers
  174. * @return ResponseInterface
  175. */
  176. protected function delete(string $route, array $headers = []): ResponseInterface {
  177. return $this->request(
  178. Request::METHOD_DELETE,
  179. $route,
  180. null,
  181. $headers
  182. );
  183. }
  184. /**
  185. * Login as the given Access user
  186. *
  187. * @param Proxy|Access $access
  188. * @return void
  189. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  190. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  191. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  192. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  193. */
  194. protected function loginAs(Proxy | Access $access): void {
  195. $person = $access->getPerson();
  196. $response = $this->post(
  197. '/login_check',
  198. ['username' => $person->getUsername(), 'password' => $person->getPassword()]
  199. );
  200. $content = $response->getContent();
  201. $this->securityToken = json_decode($content)->token;
  202. $this->user = $access;
  203. }
  204. /**
  205. * Assert that the response has the expected status code and is well formated
  206. *
  207. * @param string $resourceClass
  208. * @param int $expectedStatus
  209. * @return void
  210. */
  211. protected function validateCollectionSchema(string $resourceClass, int $expectedStatus = 200): void {
  212. $this->assertResponseStatusCodeSame($expectedStatus);
  213. if ($expectedStatus == 200) {
  214. $this->assertResponseIsSuccessful();
  215. }
  216. // Asserts that the returned content type is JSON-LD (the default)
  217. $this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
  218. // Asserts that the returned JSON is validated by the JSON Schema generated for this resource by API Platform
  219. // >>> Issue with the json typed PublicStructure::addresses properties
  220. // $this->assertMatchesResourceCollectionJsonSchema($resourceClass);
  221. }
  222. }