5 use BookStack\Entities\Models\Entity;
6 use BookStack\Http\HttpClientHistory;
7 use BookStack\Http\HttpRequestService;
8 use BookStack\Settings\SettingService;
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 Illuminate\Testing\Constraints\HasInDatabase;
19 use Monolog\Handler\TestHandler;
21 use Ssddanbrown\AssertHtml\TestsHtml;
22 use Tests\Helpers\EntityProvider;
23 use Tests\Helpers\FileProvider;
24 use Tests\Helpers\PermissionsProvider;
25 use Tests\Helpers\TestServiceProvider;
26 use Tests\Helpers\UserRoleProvider;
28 abstract class TestCase extends BaseTestCase
30 use CreatesApplication;
31 use DatabaseTransactions;
34 protected EntityProvider $entities;
35 protected UserRoleProvider $users;
36 protected PermissionsProvider $permissions;
37 protected FileProvider $files;
39 protected function setUp(): void
41 $this->entities = new EntityProvider();
42 $this->users = new UserRoleProvider();
43 $this->permissions = new PermissionsProvider($this->users);
44 $this->files = new FileProvider();
48 // We can uncomment the below to run tests with failings upon deprecations.
49 // Can't leave on since some deprecations can only be fixed upstream.
50 // $this->withoutDeprecationHandling();
54 * The base URL to use while testing the application.
56 protected string $baseUrl = 'http://localhost';
59 * Creates the application.
61 * @return \Illuminate\Foundation\Application
63 public function createApplication()
65 /** @var \Illuminate\Foundation\Application $app */
66 $app = require __DIR__ . '/../bootstrap/app.php';
67 $app->register(TestServiceProvider::class);
68 $app->make(Kernel::class)->bootstrap();
74 * Set the current user context to be an admin.
76 public function asAdmin()
78 return $this->actingAs($this->users->admin());
82 * Set the current user context to be an editor.
84 public function asEditor()
86 return $this->actingAs($this->users->editor());
90 * Set the current user context to be a viewer.
92 public function asViewer()
94 return $this->actingAs($this->users->viewer());
98 * Quickly sets an array of settings.
100 protected function setSettings(array $settingsArray): void
102 $settings = app(SettingService::class);
103 foreach ($settingsArray as $key => $value) {
104 $settings->put($key, $value);
109 * Mock the http client used in BookStack http calls.
111 protected function mockHttpClient(array $responses = []): HttpClientHistory
113 return $this->app->make(HttpRequestService::class)->mockClient($responses);
117 * Run a set test with the given env variable.
118 * Remembers the original and resets the value after test.
119 * Database config is juggled so the value can be restored when
120 * parallel testing are used, where multiple databases exist.
122 protected function runWithEnv(array $valuesByKey, callable $callback, bool $handleDatabase = true): void
124 Env::disablePutenv();
126 foreach ($valuesByKey as $key => $value) {
127 $originals[$key] = $_SERVER[$key] ?? null;
129 if (is_null($value)) {
130 unset($_SERVER[$key]);
132 $_SERVER[$key] = $value;
136 $database = config('database.connections.mysql_testing.database');
137 $this->refreshApplication();
139 if ($handleDatabase) {
141 config()->set('database.connections.mysql_testing.database', $database);
142 DB::beginTransaction();
147 if ($handleDatabase) {
151 foreach ($originals as $key => $value) {
152 if (is_null($value)) {
153 unset($_SERVER[$key]);
155 $_SERVER[$key] = $value;
161 * Check the keys and properties in the given map to include
162 * exist, albeit not exclusively, within the map to check.
164 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
168 foreach ($mapToInclude as $key => $value) {
169 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
174 $toIncludeStr = print_r($mapToInclude, true);
175 $toCheckStr = print_r($mapToCheck, true);
176 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
180 * Assert a permission error has occurred.
182 protected function assertPermissionError($response)
184 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
188 * Assert a permission error has occurred.
190 protected function assertNotPermissionError($response)
192 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
196 * Check if the given response is a permission error.
198 private function isPermissionError($response): bool
200 if ($response->status() === 403 && $response instanceof JsonResponse) {
201 $errMessage = $response->getData(true)['error']['message'] ?? '';
202 return str_contains($errMessage, 'do not have permission');
205 return $response->status() === 302
206 && $response->headers->get('Location') === url('/')
207 && str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
211 * Assert that the session has a particular error notification message set.
213 protected function assertSessionError(string $message)
215 $error = session()->get('error');
216 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
220 * Assert the session contains a specific entry.
222 protected function assertSessionHas(string $key): self
224 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
229 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
231 return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
235 * Set a test handler as the logging interface for the application.
236 * Allows capture of logs for checking against during tests.
238 protected function withTestLogger(): TestHandler
240 $monolog = new Logger('testing');
241 $testHandler = new TestHandler();
242 $monolog->pushHandler($testHandler);
244 Log::extend('testing', function () use ($monolog) {
247 Log::setDefaultDriver('testing');
253 * Assert that an activity entry exists of the given key.
254 * Checks the activity belongs to the given entity if provided.
256 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
258 $detailsToCheck = ['type' => $type];
261 $detailsToCheck['loggable_type'] = $entity->getMorphClass();
262 $detailsToCheck['loggable_id'] = $entity->id;
266 $detailsToCheck['detail'] = $detail;
269 $this->assertDatabaseHas('activities', $detailsToCheck);
273 * Assert the database has the given data for an entity type.
275 protected function assertDatabaseHasEntityData(string $type, array $data = []): self
277 $entityFields = array_intersect_key($data, array_flip(Entity::$commonFields));
278 $extraFields = array_diff_key($data, $entityFields);
279 $extraTable = $type === 'page' ? 'entity_page_data' : 'entity_container_data';
280 $entityFields['type'] = $type;
283 $this->getTable('entities'),
284 new HasInDatabase($this->getConnection(null, 'entities'), $entityFields)
287 if (!empty($extraFields)) {
288 $id = $entityFields['id'] ?? DB::table($this->getTable('entities'))
289 ->where($entityFields)->orderByDesc('id')->first()->id ?? null;
291 throw new Exception('Failed to find entity id for asserting database data');
294 if ($type !== 'page') {
295 $extraFields['entity_id'] = $id;
296 $extraFields['entity_type'] = $type;
298 $extraFields['page_id'] = $id;
302 $this->getTable($extraTable),
303 new HasInDatabase($this->getConnection(null, $extraTable), $extraFields)