1
0

AppTestCase.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests\Integration\Support;
  4. use App\App\AppFactory;
  5. use App\App\Container;
  6. use App\Auth\OidcAuthenticator;
  7. use GuzzleHttp\ClientInterface as GuzzleClientInterface;
  8. use GuzzleHttp\Handler\MockHandler;
  9. use GuzzleHttp\HandlerStack;
  10. use GuzzleHttp\Middleware;
  11. use Monolog\Handler\NullHandler;
  12. use Monolog\Handler\TestHandler;
  13. use Monolog\Logger;
  14. use PHPUnit\Framework\TestCase;
  15. use Psr\Container\ContainerInterface;
  16. use Psr\Log\LoggerInterface;
  17. use Slim\App;
  18. use Slim\Psr7\Factory\ServerRequestFactory;
  19. use Slim\Psr7\Factory\StreamFactory;
  20. /**
  21. * Boots the UI Slim app with a Guzzle MockHandler swapped in for the
  22. * api-side calls. Sessions run in CLI-fallback mode (no headers); each
  23. * test gets a fresh `$_SESSION` superglobal.
  24. *
  25. * The mocked responses are queued via `enqueueApiResponse(...)` before
  26. * the request under test fires.
  27. */
  28. abstract class AppTestCase extends TestCase
  29. {
  30. protected ContainerInterface $container;
  31. protected App $app;
  32. protected MockHandler $mock;
  33. /** @var list<array{request: \Psr\Http\Message\RequestInterface, response: \Psr\Http\Message\ResponseInterface, error: mixed, options: array<string, mixed>}> */
  34. protected array $apiHistory = [];
  35. private ?string $throttlePath = null;
  36. protected function tearDown(): void
  37. {
  38. parent::tearDown();
  39. if ($this->throttlePath !== null) {
  40. @unlink($this->throttlePath);
  41. @unlink($this->throttlePath . '.lock');
  42. $this->throttlePath = null;
  43. }
  44. }
  45. /**
  46. * @param array<string, mixed> $overrides
  47. */
  48. protected function bootApp(array $overrides = []): void
  49. {
  50. // Reset the global session bag between tests.
  51. $_SESSION = [];
  52. $this->throttlePath = sys_get_temp_dir() . '/irdb_login_throttle_test_'
  53. . bin2hex(random_bytes(8)) . '.json';
  54. $defaults = [
  55. 'app_env' => 'development',
  56. 'log_level' => \Monolog\Level::Warning,
  57. 'public_url' => 'http://localhost:8080',
  58. 'ui_secret' => 'test',
  59. 'api_base_url' => 'http://api:8081',
  60. 'ui_service_token' => 'irdb_svc_TESTTOKEN',
  61. 'api_timeout_seconds' => 1.0,
  62. 'oidc_enabled' => false,
  63. 'oidc_issuer' => '',
  64. 'oidc_client_id' => '',
  65. 'oidc_client_secret' => '',
  66. 'oidc_redirect_uri' => '',
  67. 'local_admin_enabled' => true,
  68. 'local_admin_username' => 'admin',
  69. 'local_admin_password_hash' => password_hash('test1234', PASSWORD_ARGON2ID),
  70. 'session_idle_seconds' => 28800,
  71. 'session_absolute_seconds' => 86400,
  72. 'login_throttle_path' => $this->throttlePath,
  73. ];
  74. $settings = array_replace($defaults, $overrides);
  75. $this->container = Container::build($settings);
  76. $this->mock = new MockHandler();
  77. $this->apiHistory = [];
  78. if (method_exists($this->container, 'set')) {
  79. /** @var \DI\Container $c */
  80. $c = $this->container;
  81. $handler = HandlerStack::create($this->mock);
  82. $handler->push(Middleware::history($this->apiHistory));
  83. $c->set(GuzzleClientInterface::class, new \GuzzleHttp\Client(['handler' => $handler]));
  84. // ApiClient closure-builds from the container; refresh the
  85. // bound instance with our mocked Guzzle client.
  86. $c->set(\App\ApiClient\ApiClient::class, new \App\ApiClient\ApiClient(
  87. http: $c->get(GuzzleClientInterface::class),
  88. serviceToken: (string) $c->get('settings.ui_service_token'),
  89. health: $c->get(\App\ApiClient\ApiHealth::class),
  90. ));
  91. // Quiet the logger so test output stays clean.
  92. $nullLogger = new Logger('test');
  93. $nullLogger->pushHandler(new NullHandler());
  94. $c->set(LoggerInterface::class, $nullLogger);
  95. }
  96. $this->app = AppFactory::build($this->container);
  97. }
  98. /**
  99. * @param array<string, mixed> $body
  100. */
  101. protected function enqueueApiResponse(int $status, array $body, string $contentType = 'application/json'): void
  102. {
  103. $this->mock->append(new \GuzzleHttp\Psr7\Response(
  104. $status,
  105. ['Content-Type' => $contentType],
  106. (string) json_encode($body),
  107. ));
  108. }
  109. protected function enqueueApiException(\Throwable $e): void
  110. {
  111. $this->mock->append($e);
  112. }
  113. /**
  114. * @param array<string, string> $headers
  115. * @param array<string, mixed> $serverParams
  116. */
  117. protected function request(
  118. string $method,
  119. string $path,
  120. array $headers = [],
  121. ?string $body = null,
  122. ?string $contentType = null,
  123. array $serverParams = [],
  124. ): \Psr\Http\Message\ResponseInterface {
  125. $factory = new ServerRequestFactory();
  126. $request = $factory->createServerRequest($method, $path, $serverParams);
  127. foreach ($headers as $name => $value) {
  128. $request = $request->withHeader($name, $value);
  129. }
  130. if ($contentType !== null) {
  131. $request = $request->withHeader('Content-Type', $contentType);
  132. }
  133. if ($body !== null) {
  134. $stream = (new StreamFactory())->createStream($body);
  135. $request = $request->withBody($stream);
  136. }
  137. return $this->app->handle($request);
  138. }
  139. /**
  140. * Swap in a Monolog `TestHandler` so a test can assert what reached
  141. * the logger. Re-builds controllers that captured the old logger
  142. * (currently just `OidcController`) so they pick up the new binding.
  143. */
  144. protected function captureLogs(): TestHandler
  145. {
  146. $handler = new TestHandler();
  147. $logger = new Logger('test');
  148. $logger->pushHandler($handler);
  149. if (method_exists($this->container, 'set')) {
  150. /** @var \DI\Container $c */
  151. $c = $this->container;
  152. $c->set(LoggerInterface::class, $logger);
  153. $c->set(\App\Auth\OidcController::class, new \App\Auth\OidcController(
  154. authenticator: $c->get(OidcAuthenticator::class),
  155. auth: $c->get(\App\ApiClient\AuthClient::class),
  156. sessions: $c->get(\App\Auth\SessionManager::class),
  157. logger: $logger,
  158. enabled: (bool) $c->get('settings.oidc_enabled'),
  159. ));
  160. $this->app = AppFactory::build($c);
  161. }
  162. return $handler;
  163. }
  164. /**
  165. * Replace the `OidcAuthenticator` binding with a fake callback that
  166. * the test controls. Lets us drive the OIDC controller's success +
  167. * failure paths without a real IdP.
  168. */
  169. protected function bindOidcAuthenticator(OidcAuthenticator $stub): void
  170. {
  171. if (method_exists($this->container, 'set')) {
  172. /** @var \DI\Container $c */
  173. $c = $this->container;
  174. $c->set(OidcAuthenticator::class, $stub);
  175. // Re-build the OidcController so it picks up the new binding.
  176. $c->set(\App\Auth\OidcController::class, new \App\Auth\OidcController(
  177. authenticator: $stub,
  178. auth: $c->get(\App\ApiClient\AuthClient::class),
  179. sessions: $c->get(\App\Auth\SessionManager::class),
  180. logger: $c->get(LoggerInterface::class),
  181. enabled: (bool) $c->get('settings.oidc_enabled'),
  182. ));
  183. $this->app = AppFactory::build($c);
  184. }
  185. }
  186. }