5 use BookStack\Auth\Permissions\JointPermissionBuilder;
6 use BookStack\Auth\Permissions\PermissionService;
7 use BookStack\Auth\Permissions\PermissionsRepo;
8 use BookStack\Auth\Permissions\RolePermission;
9 use BookStack\Auth\Role;
10 use BookStack\Auth\User;
11 use BookStack\Entities\Models\Book;
12 use BookStack\Entities\Models\Bookshelf;
13 use BookStack\Entities\Models\Chapter;
14 use BookStack\Entities\Models\Entity;
15 use BookStack\Entities\Models\Page;
16 use BookStack\Entities\Repos\BookRepo;
17 use BookStack\Entities\Repos\BookshelfRepo;
18 use BookStack\Entities\Repos\ChapterRepo;
19 use BookStack\Entities\Repos\PageRepo;
20 use BookStack\Settings\SettingService;
21 use BookStack\Uploads\HttpFetcher;
22 use GuzzleHttp\Client;
23 use GuzzleHttp\Handler\MockHandler;
24 use GuzzleHttp\HandlerStack;
25 use GuzzleHttp\Middleware;
26 use Illuminate\Http\JsonResponse;
27 use Illuminate\Support\Env;
28 use Illuminate\Support\Facades\Log;
29 use Illuminate\Testing\Assert as PHPUnit;
31 use Monolog\Handler\TestHandler;
33 use Psr\Http\Client\ClientInterface;
35 trait SharedTestHelpers
41 * Set the current user context to be an admin.
43 public function asAdmin()
45 return $this->actingAs($this->getAdmin());
49 * Get the current admin user.
51 public function getAdmin(): User
53 if (is_null($this->admin)) {
54 $adminRole = Role::getSystemRole('admin');
55 $this->admin = $adminRole->users->first();
62 * Set the current user context to be an editor.
64 public function asEditor()
66 return $this->actingAs($this->getEditor());
72 protected function getEditor(): User
74 if ($this->editor === null) {
75 $editorRole = Role::getRole('editor');
76 $this->editor = $editorRole->users->first();
83 * Get an instance of a user with 'viewer' permissions.
85 protected function getViewer(array $attributes = []): User
87 $user = Role::getRole('viewer')->users()->first();
88 if (!empty($attributes)) {
89 $user->forceFill($attributes)->save();
96 * Get a user that's not a system user such as the guest user.
98 public function getNormalUser(): User
100 return User::query()->where('system_name', '=', null)->get()->last();
104 * Regenerate the permission for an entity.
106 protected function regenEntityPermissions(Entity $entity): void
108 $entity->rebuildPermissions();
109 $entity->load('jointPermissions');
113 * Create and return a new bookshelf.
115 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
117 return app(BookshelfRepo::class)->create($input, []);
121 * Create and return a new book.
123 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
125 return app(BookRepo::class)->create($input);
129 * Create and return a new test chapter.
131 public function newChapter(array $input, Book $book): Chapter
133 return app(ChapterRepo::class)->create($input, $book);
137 * Create and return a new test page.
139 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
141 $book = Book::query()->first();
142 $pageRepo = app(PageRepo::class);
143 $draftPage = $pageRepo->getNewDraftPage($book);
145 return $pageRepo->publishDraft($draftPage, $input);
149 * Quickly sets an array of settings.
151 protected function setSettings(array $settingsArray): void
153 $settings = app(SettingService::class);
154 foreach ($settingsArray as $key => $value) {
155 $settings->put($key, $value);
160 * Manually set some permissions on an entity.
162 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
164 $entity->restricted = true;
165 $entity->permissions()->delete();
168 foreach ($actions as $action) {
169 foreach ($roles as $role) {
171 'role_id' => $role->id,
172 'action' => strtolower($action),
176 $entity->permissions()->createMany($permissions);
179 $entity->load('permissions');
180 $this->app->make(JointPermissionBuilder::class)->buildJointPermissionsForEntity($entity);
181 $entity->load('jointPermissions');
185 * Give the given user some permissions.
187 protected function giveUserPermissions(User $user, array $permissions = []): void
189 $newRole = $this->createNewRole($permissions);
190 $user->attachRole($newRole);
191 $user->load('roles');
192 $user->clearPermissionCache();
196 * Completely remove the given permission name from the given user.
198 protected function removePermissionFromUser(User $user, string $permissionName)
200 $permissionBuilder = app()->make(JointPermissionBuilder::class);
202 /** @var RolePermission $permission */
203 $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
205 $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
206 $query->where('id', '=', $permission->id);
209 /** @var Role $role */
210 foreach ($roles as $role) {
211 $role->detachPermission($permission);
212 $permissionBuilder->buildJointPermissionForRole($role);
215 $user->clearPermissionCache();
219 * Create a new basic role for testing purposes.
221 protected function createNewRole(array $permissions = []): Role
223 $permissionRepo = app(PermissionsRepo::class);
224 $roleData = Role::factory()->make()->toArray();
225 $roleData['permissions'] = array_flip($permissions);
227 return $permissionRepo->saveNewRole($roleData);
231 * Create a group of entities that belong to a specific user.
233 * @return array{book: Book, chapter: Chapter, page: Page}
235 protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
237 if (empty($updaterUser)) {
238 $updaterUser = $creatorUser;
241 $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
242 $book = Book::factory()->create($userAttrs);
243 $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
244 $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
246 $this->app->make(JointPermissionBuilder::class)->buildJointPermissionsForEntity($book);
248 return compact('book', 'chapter', 'page');
252 * Mock the HttpFetcher service and return the given data on fetch.
254 protected function mockHttpFetch($returnData, int $times = 1)
256 $mockHttp = Mockery::mock(HttpFetcher::class);
257 $this->app[HttpFetcher::class] = $mockHttp;
258 $mockHttp->shouldReceive('fetch')
260 ->andReturn($returnData);
264 * Mock the http client used in BookStack.
265 * Returns a reference to the container which holds all history of http transactions.
267 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
269 protected function &mockHttpClient(array $responses = []): array
272 $history = Middleware::history($container);
273 $mock = new MockHandler($responses);
274 $handlerStack = new HandlerStack($mock);
275 $handlerStack->push($history);
276 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
282 * Run a set test with the given env variable.
283 * Remembers the original and resets the value after test.
285 protected function runWithEnv(string $name, $value, callable $callback)
287 Env::disablePutenv();
288 $originalVal = $_SERVER[$name] ?? null;
290 if (is_null($value)) {
291 unset($_SERVER[$name]);
293 $_SERVER[$name] = $value;
296 $this->refreshApplication();
299 if (is_null($originalVal)) {
300 unset($_SERVER[$name]);
302 $_SERVER[$name] = $originalVal;
307 * Check the keys and properties in the given map to include
308 * exist, albeit not exclusively, within the map to check.
310 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
314 foreach ($mapToInclude as $key => $value) {
315 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
320 $toIncludeStr = print_r($mapToInclude, true);
321 $toCheckStr = print_r($mapToCheck, true);
322 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
326 * Assert a permission error has occurred.
328 protected function assertPermissionError($response)
330 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
334 * Assert a permission error has occurred.
336 protected function assertNotPermissionError($response)
338 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
342 * Check if the given response is a permission error.
344 private function isPermissionError($response): bool
346 return $response->status() === 302
349 $response->headers->get('Location') === url('/')
350 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
354 $response instanceof JsonResponse &&
355 $response->json(['error' => 'You do not have permission to perform the requested action.'])
361 * Assert that the session has a particular error notification message set.
363 protected function assertSessionError(string $message)
365 $error = session()->get('error');
366 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
370 * Set a test handler as the logging interface for the application.
371 * Allows capture of logs for checking against during tests.
373 protected function withTestLogger(): TestHandler
375 $monolog = new Logger('testing');
376 $testHandler = new TestHandler();
377 $monolog->pushHandler($testHandler);
379 Log::extend('testing', function () use ($monolog) {
382 Log::setDefaultDriver('testing');