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\Contracts\Console\Kernel;
26 use Illuminate\Foundation\Testing\DatabaseTransactions;
27 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
28 use Illuminate\Http\JsonResponse;
29 use Illuminate\Support\Env;
30 use Illuminate\Support\Facades\DB;
31 use Illuminate\Support\Facades\Log;
32 use Illuminate\Testing\Assert as PHPUnit;
33 use Monolog\Handler\TestHandler;
35 use Psr\Http\Client\ClientInterface;
36 use Ssddanbrown\AssertHtml\TestsHtml;
38 abstract class TestCase extends BaseTestCase
40 use CreatesApplication;
41 use DatabaseTransactions;
44 protected ?User $admin = null;
45 protected ?User $editor = null;
48 * The base URL to use while testing the application.
50 protected string $baseUrl = 'http://localhost';
53 * Creates the application.
55 * @return \Illuminate\Foundation\Application
57 public function createApplication()
59 /** @var \Illuminate\Foundation\Application $app */
60 $app = require __DIR__ . '/../bootstrap/app.php';
61 $app->register(TestServiceProvider::class);
62 $app->make(Kernel::class)->bootstrap();
68 * Set the current user context to be an admin.
70 public function asAdmin()
72 return $this->actingAs($this->getAdmin());
76 * Get the current admin user.
78 public function getAdmin(): User
80 if (is_null($this->admin)) {
81 $adminRole = Role::getSystemRole('admin');
82 $this->admin = $adminRole->users->first();
89 * Set the current user context to be an editor.
91 public function asEditor()
93 return $this->actingAs($this->getEditor());
99 protected function getEditor(): User
101 if ($this->editor === null) {
102 $editorRole = Role::getRole('editor');
103 $this->editor = $editorRole->users->first();
106 return $this->editor;
110 * Set the current user context to be a viewer.
112 public function asViewer()
114 return $this->actingAs($this->getViewer());
118 * Get an instance of a user with 'viewer' permissions.
120 protected function getViewer(array $attributes = []): User
122 $user = Role::getRole('viewer')->users()->first();
123 if (!empty($attributes)) {
124 $user->forceFill($attributes)->save();
131 * Get a user that's not a system user such as the guest user.
133 public function getNormalUser(): User
135 return User::query()->where('system_name', '=', null)->get()->last();
139 * Regenerate the permission for an entity.
141 protected function regenEntityPermissions(Entity $entity): void
143 $entity->rebuildPermissions();
144 $entity->load('jointPermissions');
148 * Create and return a new bookshelf.
150 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
152 return app(BookshelfRepo::class)->create($input, []);
156 * Create and return a new book.
158 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
160 return app(BookRepo::class)->create($input);
164 * Create and return a new test chapter.
166 public function newChapter(array $input, Book $book): Chapter
168 return app(ChapterRepo::class)->create($input, $book);
172 * Create and return a new test page.
174 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
176 $book = Book::query()->first();
177 $pageRepo = app(PageRepo::class);
178 $draftPage = $pageRepo->getNewDraftPage($book);
180 return $pageRepo->publishDraft($draftPage, $input);
184 * Quickly sets an array of settings.
186 protected function setSettings(array $settingsArray): void
188 $settings = app(SettingService::class);
189 foreach ($settingsArray as $key => $value) {
190 $settings->put($key, $value);
195 * Manually set some permissions on an entity.
197 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
199 $entity->restricted = true;
200 $entity->permissions()->delete();
203 foreach ($actions as $action) {
204 foreach ($roles as $role) {
206 'role_id' => $role->id,
207 'action' => strtolower($action),
211 $entity->permissions()->createMany($permissions);
214 $entity->load('permissions');
215 $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($entity);
216 $entity->load('jointPermissions');
220 * Give the given user some permissions.
222 protected function giveUserPermissions(User $user, array $permissions = []): void
224 $newRole = $this->createNewRole($permissions);
225 $user->attachRole($newRole);
226 $user->load('roles');
227 $user->clearPermissionCache();
231 * Completely remove the given permission name from the given user.
233 protected function removePermissionFromUser(User $user, string $permissionName)
235 $permissionBuilder = app()->make(JointPermissionBuilder::class);
237 /** @var RolePermission $permission */
238 $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
240 $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
241 $query->where('id', '=', $permission->id);
244 /** @var Role $role */
245 foreach ($roles as $role) {
246 $role->detachPermission($permission);
247 $permissionBuilder->rebuildForRole($role);
250 $user->clearPermissionCache();
254 * Create a new basic role for testing purposes.
256 protected function createNewRole(array $permissions = []): Role
258 $permissionRepo = app(PermissionsRepo::class);
259 $roleData = Role::factory()->make()->toArray();
260 $roleData['permissions'] = array_flip($permissions);
262 return $permissionRepo->saveNewRole($roleData);
266 * Create a group of entities that belong to a specific user.
268 * @return array{book: Book, chapter: Chapter, page: Page}
270 protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
272 if (empty($updaterUser)) {
273 $updaterUser = $creatorUser;
276 $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
277 $book = Book::factory()->create($userAttrs);
278 $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
279 $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
281 $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($book);
283 return compact('book', 'chapter', 'page');
287 * Mock the HttpFetcher service and return the given data on fetch.
289 protected function mockHttpFetch($returnData, int $times = 1)
291 $mockHttp = Mockery::mock(HttpFetcher::class);
292 $this->app[HttpFetcher::class] = $mockHttp;
293 $mockHttp->shouldReceive('fetch')
295 ->andReturn($returnData);
299 * Mock the http client used in BookStack.
300 * Returns a reference to the container which holds all history of http transactions.
302 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
304 protected function &mockHttpClient(array $responses = []): array
307 $history = Middleware::history($container);
308 $mock = new MockHandler($responses);
309 $handlerStack = new HandlerStack($mock);
310 $handlerStack->push($history);
311 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
317 * Run a set test with the given env variable.
318 * Remembers the original and resets the value after test.
319 * Database config is juggled so the value can be restored when
320 * parallel testing are used, where multiple databases exist.
322 protected function runWithEnv(string $name, $value, callable $callback)
324 Env::disablePutenv();
325 $originalVal = $_SERVER[$name] ?? null;
327 if (is_null($value)) {
328 unset($_SERVER[$name]);
330 $_SERVER[$name] = $value;
333 $database = config('database.connections.mysql_testing.database');
334 $this->refreshApplication();
337 config()->set('database.connections.mysql_testing.database', $database);
341 if (is_null($originalVal)) {
342 unset($_SERVER[$name]);
344 $_SERVER[$name] = $originalVal;
349 * Check the keys and properties in the given map to include
350 * exist, albeit not exclusively, within the map to check.
352 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
356 foreach ($mapToInclude as $key => $value) {
357 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
362 $toIncludeStr = print_r($mapToInclude, true);
363 $toCheckStr = print_r($mapToCheck, true);
364 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
368 * Assert a permission error has occurred.
370 protected function assertPermissionError($response)
372 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
376 * Assert a permission error has occurred.
378 protected function assertNotPermissionError($response)
380 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
384 * Check if the given response is a permission error.
386 private function isPermissionError($response): bool
388 return $response->status() === 302
391 $response->headers->get('Location') === url('/')
392 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
396 $response instanceof JsonResponse &&
397 $response->json(['error' => 'You do not have permission to perform the requested action.'])
403 * Assert that the session has a particular error notification message set.
405 protected function assertSessionError(string $message)
407 $error = session()->get('error');
408 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
412 * Assert the session contains a specific entry.
414 protected function assertSessionHas(string $key): self
416 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
421 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
423 return $this->withHtml($resp)->assertElementContains('[notification]', $text);
427 * Set a test handler as the logging interface for the application.
428 * Allows capture of logs for checking against during tests.
430 protected function withTestLogger(): TestHandler
432 $monolog = new Logger('testing');
433 $testHandler = new TestHandler();
434 $monolog->pushHandler($testHandler);
436 Log::extend('testing', function () use ($monolog) {
439 Log::setDefaultDriver('testing');
445 * Assert that an activity entry exists of the given key.
446 * Checks the activity belongs to the given entity if provided.
448 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
450 $detailsToCheck = ['type' => $type];
453 $detailsToCheck['entity_type'] = $entity->getMorphClass();
454 $detailsToCheck['entity_id'] = $entity->id;
458 $detailsToCheck['detail'] = $detail;
461 $this->assertDatabaseHas('activities', $detailsToCheck);
465 * @return array{page: Page, chapter: Chapter, book: Book, bookshelf: Bookshelf}
467 protected function getEachEntityType(): array
470 'page' => Page::query()->first(),
471 'chapter' => Chapter::query()->first(),
472 'book' => Book::query()->first(),
473 'bookshelf' => Bookshelf::query()->first(),