AppTestCase.php 5.8 KB

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