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\Log;
30 use Illuminate\Testing\Assert as PHPUnit;
31 use Monolog\Handler\TestHandler;
33 use Psr\Http\Client\ClientInterface;
34 use Ssddanbrown\AssertHtml\TestsHtml;
36 abstract class TestCase extends BaseTestCase
38 use CreatesApplication;
39 use DatabaseTransactions;
42 protected ?User $admin = null;
43 protected ?User $editor = null;
46 * The base URL to use while testing the application.
48 protected string $baseUrl = 'http://localhost';
51 * Set the current user context to be an admin.
53 public function asAdmin()
55 return $this->actingAs($this->getAdmin());
59 * Get the current admin user.
61 public function getAdmin(): User
63 if (is_null($this->admin)) {
64 $adminRole = Role::getSystemRole('admin');
65 $this->admin = $adminRole->users->first();
72 * Set the current user context to be an editor.
74 public function asEditor()
76 return $this->actingAs($this->getEditor());
82 protected function getEditor(): User
84 if ($this->editor === null) {
85 $editorRole = Role::getRole('editor');
86 $this->editor = $editorRole->users->first();
93 * Set the current user context to be a viewer.
95 public function asViewer()
97 return $this->actingAs($this->getViewer());
101 * Get an instance of a user with 'viewer' permissions.
103 protected function getViewer(array $attributes = []): User
105 $user = Role::getRole('viewer')->users()->first();
106 if (!empty($attributes)) {
107 $user->forceFill($attributes)->save();
114 * Get a user that's not a system user such as the guest user.
116 public function getNormalUser(): User
118 return User::query()->where('system_name', '=', null)->get()->last();
122 * Regenerate the permission for an entity.
124 protected function regenEntityPermissions(Entity $entity): void
126 $entity->rebuildPermissions();
127 $entity->load('jointPermissions');
131 * Create and return a new bookshelf.
133 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
135 return app(BookshelfRepo::class)->create($input, []);
139 * Create and return a new book.
141 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
143 return app(BookRepo::class)->create($input);
147 * Create and return a new test chapter.
149 public function newChapter(array $input, Book $book): Chapter
151 return app(ChapterRepo::class)->create($input, $book);
155 * Create and return a new test page.
157 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
159 $book = Book::query()->first();
160 $pageRepo = app(PageRepo::class);
161 $draftPage = $pageRepo->getNewDraftPage($book);
163 return $pageRepo->publishDraft($draftPage, $input);
167 * Quickly sets an array of settings.
169 protected function setSettings(array $settingsArray): void
171 $settings = app(SettingService::class);
172 foreach ($settingsArray as $key => $value) {
173 $settings->put($key, $value);
178 * Manually set some permissions on an entity.
180 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
182 $entity->restricted = true;
183 $entity->permissions()->delete();
186 foreach ($actions as $action) {
187 foreach ($roles as $role) {
189 'role_id' => $role->id,
190 'action' => strtolower($action),
194 $entity->permissions()->createMany($permissions);
197 $entity->load('permissions');
198 $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($entity);
199 $entity->load('jointPermissions');
203 * Give the given user some permissions.
205 protected function giveUserPermissions(User $user, array $permissions = []): void
207 $newRole = $this->createNewRole($permissions);
208 $user->attachRole($newRole);
209 $user->load('roles');
210 $user->clearPermissionCache();
214 * Completely remove the given permission name from the given user.
216 protected function removePermissionFromUser(User $user, string $permissionName)
218 $permissionBuilder = app()->make(JointPermissionBuilder::class);
220 /** @var RolePermission $permission */
221 $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
223 $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
224 $query->where('id', '=', $permission->id);
227 /** @var Role $role */
228 foreach ($roles as $role) {
229 $role->detachPermission($permission);
230 $permissionBuilder->rebuildForRole($role);
233 $user->clearPermissionCache();
237 * Create a new basic role for testing purposes.
239 protected function createNewRole(array $permissions = []): Role
241 $permissionRepo = app(PermissionsRepo::class);
242 $roleData = Role::factory()->make()->toArray();
243 $roleData['permissions'] = array_flip($permissions);
245 return $permissionRepo->saveNewRole($roleData);
249 * Create a group of entities that belong to a specific user.
251 * @return array{book: Book, chapter: Chapter, page: Page}
253 protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
255 if (empty($updaterUser)) {
256 $updaterUser = $creatorUser;
259 $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
260 $book = Book::factory()->create($userAttrs);
261 $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
262 $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
264 $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($book);
266 return compact('book', 'chapter', 'page');
270 * Mock the HttpFetcher service and return the given data on fetch.
272 protected function mockHttpFetch($returnData, int $times = 1)
274 $mockHttp = Mockery::mock(HttpFetcher::class);
275 $this->app[HttpFetcher::class] = $mockHttp;
276 $mockHttp->shouldReceive('fetch')
278 ->andReturn($returnData);
282 * Mock the http client used in BookStack.
283 * Returns a reference to the container which holds all history of http transactions.
285 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
287 protected function &mockHttpClient(array $responses = []): array
290 $history = Middleware::history($container);
291 $mock = new MockHandler($responses);
292 $handlerStack = new HandlerStack($mock);
293 $handlerStack->push($history);
294 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
300 * Run a set test with the given env variable.
301 * Remembers the original and resets the value after test.
303 protected function runWithEnv(string $name, $value, callable $callback)
305 Env::disablePutenv();
306 $originalVal = $_SERVER[$name] ?? null;
308 if (is_null($value)) {
309 unset($_SERVER[$name]);
311 $_SERVER[$name] = $value;
314 $this->refreshApplication();
317 if (is_null($originalVal)) {
318 unset($_SERVER[$name]);
320 $_SERVER[$name] = $originalVal;
325 * Check the keys and properties in the given map to include
326 * exist, albeit not exclusively, within the map to check.
328 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
332 foreach ($mapToInclude as $key => $value) {
333 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
338 $toIncludeStr = print_r($mapToInclude, true);
339 $toCheckStr = print_r($mapToCheck, true);
340 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
344 * Assert a permission error has occurred.
346 protected function assertPermissionError($response)
348 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
352 * Assert a permission error has occurred.
354 protected function assertNotPermissionError($response)
356 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
360 * Check if the given response is a permission error.
362 private function isPermissionError($response): bool
364 return $response->status() === 302
367 $response->headers->get('Location') === url('/')
368 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
372 $response instanceof JsonResponse &&
373 $response->json(['error' => 'You do not have permission to perform the requested action.'])
379 * Assert that the session has a particular error notification message set.
381 protected function assertSessionError(string $message)
383 $error = session()->get('error');
384 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
388 * Assert the session contains a specific entry.
390 protected function assertSessionHas(string $key): self
392 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
397 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
399 return $this->withHtml($resp)->assertElementContains('[notification]', $text);
403 * Set a test handler as the logging interface for the application.
404 * Allows capture of logs for checking against during tests.
406 protected function withTestLogger(): TestHandler
408 $monolog = new Logger('testing');
409 $testHandler = new TestHandler();
410 $monolog->pushHandler($testHandler);
412 Log::extend('testing', function () use ($monolog) {
415 Log::setDefaultDriver('testing');
421 * Assert that an activity entry exists of the given key.
422 * Checks the activity belongs to the given entity if provided.
424 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
426 $detailsToCheck = ['type' => $type];
429 $detailsToCheck['entity_type'] = $entity->getMorphClass();
430 $detailsToCheck['entity_id'] = $entity->id;
434 $detailsToCheck['detail'] = $detail;
437 $this->assertDatabaseHas('activities', $detailsToCheck);
441 * @return array{page: Page, chapter: Chapter, book: Book, bookshelf: Bookshelf}
443 protected function getEachEntityType(): array
446 'page' => Page::query()->first(),
447 'chapter' => Chapter::query()->first(),
448 'book' => Book::query()->first(),
449 'bookshelf' => Bookshelf::query()->first(),