5 use BookStack\Auth\Permissions\JointPermissionBuilder;
6 use BookStack\Auth\Permissions\PermissionsRepo;
7 use BookStack\Auth\Permissions\RolePermission;
8 use BookStack\Auth\Role;
9 use BookStack\Auth\User;
10 use BookStack\Entities\Models\Book;
11 use BookStack\Entities\Models\Bookshelf;
12 use BookStack\Entities\Models\Chapter;
13 use BookStack\Entities\Models\Entity;
14 use BookStack\Entities\Models\Page;
15 use BookStack\Entities\Repos\BookRepo;
16 use BookStack\Entities\Repos\BookshelfRepo;
17 use BookStack\Entities\Repos\ChapterRepo;
18 use BookStack\Entities\Repos\PageRepo;
19 use BookStack\Settings\SettingService;
20 use BookStack\Uploads\HttpFetcher;
21 use GuzzleHttp\Client;
22 use GuzzleHttp\Handler\MockHandler;
23 use GuzzleHttp\HandlerStack;
24 use GuzzleHttp\Middleware;
25 use Illuminate\Foundation\Testing\DatabaseTransactions;
26 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
27 use Illuminate\Http\JsonResponse;
28 use Illuminate\Support\Env;
29 use Illuminate\Support\Facades\DB;
30 use Illuminate\Support\Facades\Log;
31 use Illuminate\Testing\Assert as PHPUnit;
32 use Monolog\Handler\TestHandler;
34 use Psr\Http\Client\ClientInterface;
35 use Ssddanbrown\AssertHtml\TestsHtml;
37 abstract class TestCase extends BaseTestCase
39 use CreatesApplication;
40 use DatabaseTransactions;
43 protected ?User $admin = null;
44 protected ?User $editor = null;
47 * The base URL to use while testing the application.
49 protected string $baseUrl = 'http://localhost';
52 * Set the current user context to be an admin.
54 public function asAdmin()
56 return $this->actingAs($this->getAdmin());
60 * Get the current admin user.
62 public function getAdmin(): User
64 if (is_null($this->admin)) {
65 $adminRole = Role::getSystemRole('admin');
66 $this->admin = $adminRole->users->first();
73 * Set the current user context to be an editor.
75 public function asEditor()
77 return $this->actingAs($this->getEditor());
83 protected function getEditor(): User
85 if ($this->editor === null) {
86 $editorRole = Role::getRole('editor');
87 $this->editor = $editorRole->users->first();
94 * Set the current user context to be a viewer.
96 public function asViewer()
98 return $this->actingAs($this->getViewer());
102 * Get an instance of a user with 'viewer' permissions.
104 protected function getViewer(array $attributes = []): User
106 $user = Role::getRole('viewer')->users()->first();
107 if (!empty($attributes)) {
108 $user->forceFill($attributes)->save();
115 * Get a user that's not a system user such as the guest user.
117 public function getNormalUser(): User
119 return User::query()->where('system_name', '=', null)->get()->last();
123 * Regenerate the permission for an entity.
125 protected function regenEntityPermissions(Entity $entity): void
127 $entity->rebuildPermissions();
128 $entity->load('jointPermissions');
132 * Create and return a new bookshelf.
134 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
136 return app(BookshelfRepo::class)->create($input, []);
140 * Create and return a new book.
142 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
144 return app(BookRepo::class)->create($input);
148 * Create and return a new test chapter.
150 public function newChapter(array $input, Book $book): Chapter
152 return app(ChapterRepo::class)->create($input, $book);
156 * Create and return a new test page.
158 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
160 $book = Book::query()->first();
161 $pageRepo = app(PageRepo::class);
162 $draftPage = $pageRepo->getNewDraftPage($book);
164 return $pageRepo->publishDraft($draftPage, $input);
168 * Quickly sets an array of settings.
170 protected function setSettings(array $settingsArray): void
172 $settings = app(SettingService::class);
173 foreach ($settingsArray as $key => $value) {
174 $settings->put($key, $value);
179 * Manually set some permissions on an entity.
181 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
183 $entity->restricted = true;
184 $entity->permissions()->delete();
187 foreach ($actions as $action) {
188 foreach ($roles as $role) {
190 'role_id' => $role->id,
191 'action' => strtolower($action),
195 $entity->permissions()->createMany($permissions);
198 $entity->load('permissions');
199 $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($entity);
200 $entity->load('jointPermissions');
204 * Give the given user some permissions.
206 protected function giveUserPermissions(User $user, array $permissions = []): void
208 $newRole = $this->createNewRole($permissions);
209 $user->attachRole($newRole);
210 $user->load('roles');
211 $user->clearPermissionCache();
215 * Completely remove the given permission name from the given user.
217 protected function removePermissionFromUser(User $user, string $permissionName)
219 $permissionBuilder = app()->make(JointPermissionBuilder::class);
221 /** @var RolePermission $permission */
222 $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
224 $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
225 $query->where('id', '=', $permission->id);
228 /** @var Role $role */
229 foreach ($roles as $role) {
230 $role->detachPermission($permission);
231 $permissionBuilder->rebuildForRole($role);
234 $user->clearPermissionCache();
238 * Create a new basic role for testing purposes.
240 protected function createNewRole(array $permissions = []): Role
242 $permissionRepo = app(PermissionsRepo::class);
243 $roleData = Role::factory()->make()->toArray();
244 $roleData['permissions'] = array_flip($permissions);
246 return $permissionRepo->saveNewRole($roleData);
250 * Create a group of entities that belong to a specific user.
252 * @return array{book: Book, chapter: Chapter, page: Page}
254 protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
256 if (empty($updaterUser)) {
257 $updaterUser = $creatorUser;
260 $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
261 $book = Book::factory()->create($userAttrs);
262 $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
263 $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
265 $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($book);
267 return compact('book', 'chapter', 'page');
271 * Mock the HttpFetcher service and return the given data on fetch.
273 protected function mockHttpFetch($returnData, int $times = 1)
275 $mockHttp = Mockery::mock(HttpFetcher::class);
276 $this->app[HttpFetcher::class] = $mockHttp;
277 $mockHttp->shouldReceive('fetch')
279 ->andReturn($returnData);
283 * Mock the http client used in BookStack.
284 * Returns a reference to the container which holds all history of http transactions.
286 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
288 protected function &mockHttpClient(array $responses = []): array
291 $history = Middleware::history($container);
292 $mock = new MockHandler($responses);
293 $handlerStack = new HandlerStack($mock);
294 $handlerStack->push($history);
295 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
301 * Run a set test with the given env variable.
302 * Remembers the original and resets the value after test.
303 * Database config is juggled so the value can be restored when
304 * parallel testing are used, where multiple databases exist.
306 protected function runWithEnv(string $name, $value, callable $callback)
308 Env::disablePutenv();
309 $originalVal = $_SERVER[$name] ?? null;
311 if (is_null($value)) {
312 unset($_SERVER[$name]);
314 $_SERVER[$name] = $value;
317 $database = config('database.connections.mysql_testing.database');
318 $this->refreshApplication();
321 config()->set('database.connections.mysql_testing.database', $database);
325 if (is_null($originalVal)) {
326 unset($_SERVER[$name]);
328 $_SERVER[$name] = $originalVal;
333 * Check the keys and properties in the given map to include
334 * exist, albeit not exclusively, within the map to check.
336 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
340 foreach ($mapToInclude as $key => $value) {
341 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
346 $toIncludeStr = print_r($mapToInclude, true);
347 $toCheckStr = print_r($mapToCheck, true);
348 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
352 * Assert a permission error has occurred.
354 protected function assertPermissionError($response)
356 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
360 * Assert a permission error has occurred.
362 protected function assertNotPermissionError($response)
364 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
368 * Check if the given response is a permission error.
370 private function isPermissionError($response): bool
372 return $response->status() === 302
375 $response->headers->get('Location') === url('/')
376 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
380 $response instanceof JsonResponse &&
381 $response->json(['error' => 'You do not have permission to perform the requested action.'])
387 * Assert that the session has a particular error notification message set.
389 protected function assertSessionError(string $message)
391 $error = session()->get('error');
392 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
396 * Assert the session contains a specific entry.
398 protected function assertSessionHas(string $key): self
400 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
405 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
407 return $this->withHtml($resp)->assertElementContains('[notification]', $text);
411 * Set a test handler as the logging interface for the application.
412 * Allows capture of logs for checking against during tests.
414 protected function withTestLogger(): TestHandler
416 $monolog = new Logger('testing');
417 $testHandler = new TestHandler();
418 $monolog->pushHandler($testHandler);
420 Log::extend('testing', function () use ($monolog) {
423 Log::setDefaultDriver('testing');
429 * Assert that an activity entry exists of the given key.
430 * Checks the activity belongs to the given entity if provided.
432 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
434 $detailsToCheck = ['type' => $type];
437 $detailsToCheck['entity_type'] = $entity->getMorphClass();
438 $detailsToCheck['entity_id'] = $entity->id;
442 $detailsToCheck['detail'] = $detail;
445 $this->assertDatabaseHas('activities', $detailsToCheck);
449 * @return array{page: Page, chapter: Chapter, book: Book, bookshelf: Bookshelf}
451 protected function getEachEntityType(): array
454 'page' => Page::query()->first(),
455 'chapter' => Chapter::query()->first(),
456 'book' => Book::query()->first(),
457 'bookshelf' => Bookshelf::query()->first(),