5 use BookStack\Entities\Models\Entity;
6 use BookStack\Http\HttpClientHistory;
7 use BookStack\Http\HttpRequestService;
8 use BookStack\Settings\SettingService;
9 use BookStack\Users\Models\User;
10 use Illuminate\Contracts\Console\Kernel;
11 use Illuminate\Foundation\Testing\DatabaseTransactions;
12 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
13 use Illuminate\Http\JsonResponse;
14 use Illuminate\Support\Env;
15 use Illuminate\Support\Facades\DB;
16 use Illuminate\Support\Facades\Log;
17 use Illuminate\Testing\Assert as PHPUnit;
18 use Monolog\Handler\TestHandler;
20 use Ssddanbrown\AssertHtml\TestsHtml;
21 use Tests\Helpers\EntityProvider;
22 use Tests\Helpers\FileProvider;
23 use Tests\Helpers\PermissionsProvider;
24 use Tests\Helpers\TestServiceProvider;
25 use Tests\Helpers\UserRoleProvider;
27 abstract class TestCase extends BaseTestCase
29 use CreatesApplication;
30 use DatabaseTransactions;
33 protected EntityProvider $entities;
34 protected UserRoleProvider $users;
35 protected PermissionsProvider $permissions;
36 protected FileProvider $files;
38 protected function setUp(): void
40 $this->entities = new EntityProvider();
41 $this->users = new UserRoleProvider();
42 $this->permissions = new PermissionsProvider($this->users);
43 $this->files = new FileProvider();
47 // We can uncomment the below to run tests with failings upon deprecations.
48 // Can't leave on since some deprecations can only be fixed upstream.
49 // $this->withoutDeprecationHandling();
53 * The base URL to use while testing the application.
55 protected string $baseUrl = 'http://localhost';
58 * Creates the application.
60 * @return \Illuminate\Foundation\Application
62 public function createApplication()
64 /** @var \Illuminate\Foundation\Application $app */
65 $app = require __DIR__ . '/../bootstrap/app.php';
66 $app->register(TestServiceProvider::class);
67 $app->make(Kernel::class)->bootstrap();
73 * Set the current user context to be an admin.
75 public function asAdmin()
77 return $this->actingAs($this->users->admin());
81 * Set the current user context to be an editor.
83 public function asEditor()
85 return $this->actingAs($this->users->editor());
89 * Set the current user context to be a viewer.
91 public function asViewer()
93 return $this->actingAs($this->users->viewer());
97 * Quickly sets an array of settings.
99 protected function setSettings(array $settingsArray): void
101 $settings = app(SettingService::class);
102 foreach ($settingsArray as $key => $value) {
103 $settings->put($key, $value);
108 * Mock the http client used in BookStack http calls.
110 protected function mockHttpClient(array $responses = []): HttpClientHistory
112 return $this->app->make(HttpRequestService::class)->mockClient($responses);
116 * Run a set test with the given env variable.
117 * Remembers the original and resets the value after test.
118 * Database config is juggled so the value can be restored when
119 * parallel testing are used, where multiple databases exist.
121 protected function runWithEnv(array $valuesByKey, callable $callback, bool $handleDatabase = true): void
123 Env::disablePutenv();
125 foreach ($valuesByKey as $key => $value) {
126 $originals[$key] = $_SERVER[$key] ?? null;
128 if (is_null($value)) {
129 unset($_SERVER[$key]);
131 $_SERVER[$key] = $value;
135 $database = config('database.connections.mysql_testing.database');
136 $this->refreshApplication();
138 if ($handleDatabase) {
140 config()->set('database.connections.mysql_testing.database', $database);
141 DB::beginTransaction();
146 if ($handleDatabase) {
150 foreach ($originals as $key => $value) {
151 if (is_null($value)) {
152 unset($_SERVER[$key]);
154 $_SERVER[$key] = $value;
160 * Check the keys and properties in the given map to include
161 * exist, albeit not exclusively, within the map to check.
163 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
167 foreach ($mapToInclude as $key => $value) {
168 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
173 $toIncludeStr = print_r($mapToInclude, true);
174 $toCheckStr = print_r($mapToCheck, true);
175 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
179 * Assert a permission error has occurred.
181 protected function assertPermissionError($response)
183 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
187 * Assert a permission error has occurred.
189 protected function assertNotPermissionError($response)
191 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
195 * Check if the given response is a permission error.
197 private function isPermissionError($response): bool
199 if ($response->status() === 403 && $response instanceof JsonResponse) {
200 $errMessage = $response->getData(true)['error']['message'] ?? '';
201 return $errMessage === 'You do not have permission to perform the requested action.';
204 return $response->status() === 302
205 && $response->headers->get('Location') === url('/')
206 && str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
210 * Assert that the session has a particular error notification message set.
212 protected function assertSessionError(string $message)
214 $error = session()->get('error');
215 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
219 * Assert the session contains a specific entry.
221 protected function assertSessionHas(string $key): self
223 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
228 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
230 return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
234 * Set a test handler as the logging interface for the application.
235 * Allows capture of logs for checking against during tests.
237 protected function withTestLogger(): TestHandler
239 $monolog = new Logger('testing');
240 $testHandler = new TestHandler();
241 $monolog->pushHandler($testHandler);
243 Log::extend('testing', function () use ($monolog) {
246 Log::setDefaultDriver('testing');
252 * Assert that an activity entry exists of the given key.
253 * Checks the activity belongs to the given entity if provided.
255 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
257 $detailsToCheck = ['type' => $type];
260 $detailsToCheck['loggable_type'] = $entity->getMorphClass();
261 $detailsToCheck['loggable_id'] = $entity->id;
265 $detailsToCheck['detail'] = $detail;
268 $this->assertDatabaseHas('activities', $detailsToCheck);