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 * Get an instance of a user with 'viewer' permissions.
95 protected function getViewer(array $attributes = []): User
97 $user = Role::getRole('viewer')->users()->first();
98 if (!empty($attributes)) {
99 $user->forceFill($attributes)->save();
106 * Get a user that's not a system user such as the guest user.
108 public function getNormalUser(): User
110 return User::query()->where('system_name', '=', null)->get()->last();
114 * Regenerate the permission for an entity.
116 protected function regenEntityPermissions(Entity $entity): void
118 $entity->rebuildPermissions();
119 $entity->load('jointPermissions');
123 * Create and return a new bookshelf.
125 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
127 return app(BookshelfRepo::class)->create($input, []);
131 * Create and return a new book.
133 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
135 return app(BookRepo::class)->create($input);
139 * Create and return a new test chapter.
141 public function newChapter(array $input, Book $book): Chapter
143 return app(ChapterRepo::class)->create($input, $book);
147 * Create and return a new test page.
149 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
151 $book = Book::query()->first();
152 $pageRepo = app(PageRepo::class);
153 $draftPage = $pageRepo->getNewDraftPage($book);
155 return $pageRepo->publishDraft($draftPage, $input);
159 * Quickly sets an array of settings.
161 protected function setSettings(array $settingsArray): void
163 $settings = app(SettingService::class);
164 foreach ($settingsArray as $key => $value) {
165 $settings->put($key, $value);
170 * Manually set some permissions on an entity.
172 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
174 $entity->restricted = true;
175 $entity->permissions()->delete();
178 foreach ($actions as $action) {
179 foreach ($roles as $role) {
181 'role_id' => $role->id,
182 'action' => strtolower($action),
186 $entity->permissions()->createMany($permissions);
189 $entity->load('permissions');
190 $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($entity);
191 $entity->load('jointPermissions');
195 * Give the given user some permissions.
197 protected function giveUserPermissions(User $user, array $permissions = []): void
199 $newRole = $this->createNewRole($permissions);
200 $user->attachRole($newRole);
201 $user->load('roles');
202 $user->clearPermissionCache();
206 * Completely remove the given permission name from the given user.
208 protected function removePermissionFromUser(User $user, string $permissionName)
210 $permissionBuilder = app()->make(JointPermissionBuilder::class);
212 /** @var RolePermission $permission */
213 $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
215 $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
216 $query->where('id', '=', $permission->id);
219 /** @var Role $role */
220 foreach ($roles as $role) {
221 $role->detachPermission($permission);
222 $permissionBuilder->rebuildForRole($role);
225 $user->clearPermissionCache();
229 * Create a new basic role for testing purposes.
231 protected function createNewRole(array $permissions = []): Role
233 $permissionRepo = app(PermissionsRepo::class);
234 $roleData = Role::factory()->make()->toArray();
235 $roleData['permissions'] = array_flip($permissions);
237 return $permissionRepo->saveNewRole($roleData);
241 * Create a group of entities that belong to a specific user.
243 * @return array{book: Book, chapter: Chapter, page: Page}
245 protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
247 if (empty($updaterUser)) {
248 $updaterUser = $creatorUser;
251 $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
252 $book = Book::factory()->create($userAttrs);
253 $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
254 $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
256 $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($book);
258 return compact('book', 'chapter', 'page');
262 * Mock the HttpFetcher service and return the given data on fetch.
264 protected function mockHttpFetch($returnData, int $times = 1)
266 $mockHttp = Mockery::mock(HttpFetcher::class);
267 $this->app[HttpFetcher::class] = $mockHttp;
268 $mockHttp->shouldReceive('fetch')
270 ->andReturn($returnData);
274 * Mock the http client used in BookStack.
275 * Returns a reference to the container which holds all history of http transactions.
277 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
279 protected function &mockHttpClient(array $responses = []): array
282 $history = Middleware::history($container);
283 $mock = new MockHandler($responses);
284 $handlerStack = new HandlerStack($mock);
285 $handlerStack->push($history);
286 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
292 * Run a set test with the given env variable.
293 * Remembers the original and resets the value after test.
295 protected function runWithEnv(string $name, $value, callable $callback)
297 Env::disablePutenv();
298 $originalVal = $_SERVER[$name] ?? null;
300 if (is_null($value)) {
301 unset($_SERVER[$name]);
303 $_SERVER[$name] = $value;
306 $this->refreshApplication();
309 if (is_null($originalVal)) {
310 unset($_SERVER[$name]);
312 $_SERVER[$name] = $originalVal;
317 * Check the keys and properties in the given map to include
318 * exist, albeit not exclusively, within the map to check.
320 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
324 foreach ($mapToInclude as $key => $value) {
325 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
330 $toIncludeStr = print_r($mapToInclude, true);
331 $toCheckStr = print_r($mapToCheck, true);
332 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
336 * Assert a permission error has occurred.
338 protected function assertPermissionError($response)
340 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
344 * Assert a permission error has occurred.
346 protected function assertNotPermissionError($response)
348 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
352 * Check if the given response is a permission error.
354 private function isPermissionError($response): bool
356 return $response->status() === 302
359 $response->headers->get('Location') === url('/')
360 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
364 $response instanceof JsonResponse &&
365 $response->json(['error' => 'You do not have permission to perform the requested action.'])
371 * Assert that the session has a particular error notification message set.
373 protected function assertSessionError(string $message)
375 $error = session()->get('error');
376 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
380 * Assert the session contains a specific entry.
382 protected function assertSessionHas(string $key): self
384 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
389 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
391 return $this->withHtml($resp)->assertElementContains('[notification]', $text);
395 * Set a test handler as the logging interface for the application.
396 * Allows capture of logs for checking against during tests.
398 protected function withTestLogger(): TestHandler
400 $monolog = new Logger('testing');
401 $testHandler = new TestHandler();
402 $monolog->pushHandler($testHandler);
404 Log::extend('testing', function () use ($monolog) {
407 Log::setDefaultDriver('testing');
413 * Assert that an activity entry exists of the given key.
414 * Checks the activity belongs to the given entity if provided.
416 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
418 $detailsToCheck = ['type' => $type];
421 $detailsToCheck['entity_type'] = $entity->getMorphClass();
422 $detailsToCheck['entity_id'] = $entity->id;
426 $detailsToCheck['detail'] = $detail;
429 $this->assertDatabaseHas('activities', $detailsToCheck);
435 protected function getEachEntityType(): array
438 'page' => Page::query()->first(),
439 'chapter' => Chapter::query()->first(),
440 'book' => Book::query()->first(),
441 'bookshelf' => Bookshelf::query()->first(),