1
0

AppTestCase.php 5.4 KB

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