5 use BookStack\Auth\Permissions\PermissionService;
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 Illuminate\Foundation\Testing\Assert as PHPUnit;
22 use Illuminate\Http\JsonResponse;
23 use Illuminate\Support\Env;
24 use Illuminate\Support\Facades\Log;
26 use Monolog\Handler\TestHandler;
29 trait SharedTestHelpers
35 * Set the current user context to be an admin.
37 public function asAdmin()
39 return $this->actingAs($this->getAdmin());
43 * Get the current admin user.
45 public function getAdmin(): User
47 if (is_null($this->admin)) {
48 $adminRole = Role::getSystemRole('admin');
49 $this->admin = $adminRole->users->first();
56 * Set the current user context to be an editor.
58 public function asEditor()
60 return $this->actingAs($this->getEditor());
66 protected function getEditor(): User
68 if ($this->editor === null) {
69 $editorRole = Role::getRole('editor');
70 $this->editor = $editorRole->users->first();
77 * Get an instance of a user with 'viewer' permissions.
79 protected function getViewer(array $attributes = []): User
81 $user = Role::getRole('viewer')->users()->first();
82 if (!empty($attributes)) {
83 $user->forceFill($attributes)->save();
90 * Get a user that's not a system user such as the guest user.
92 public function getNormalUser()
94 return User::query()->where('system_name', '=', null)->get()->last();
98 * Regenerate the permission for an entity.
100 protected function regenEntityPermissions(Entity $entity): void
102 $entity->rebuildPermissions();
103 $entity->load('jointPermissions');
107 * Create and return a new bookshelf.
109 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
111 return app(BookshelfRepo::class)->create($input, []);
115 * Create and return a new book.
117 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
119 return app(BookRepo::class)->create($input);
123 * Create and return a new test chapter.
125 public function newChapter(array $input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book): Chapter
127 return app(ChapterRepo::class)->create($input, $book);
131 * Create and return a new test page.
133 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
135 $book = Book::query()->first();
136 $pageRepo = app(PageRepo::class);
137 $draftPage = $pageRepo->getNewDraftPage($book);
139 return $pageRepo->publishDraft($draftPage, $input);
143 * Quickly sets an array of settings.
145 protected function setSettings(array $settingsArray): void
147 $settings = app(SettingService::class);
148 foreach ($settingsArray as $key => $value) {
149 $settings->put($key, $value);
154 * Manually set some permissions on an entity.
156 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
158 $entity->restricted = true;
159 $entity->permissions()->delete();
162 foreach ($actions as $action) {
163 foreach ($roles as $role) {
165 'role_id' => $role->id,
166 'action' => strtolower($action),
170 $entity->permissions()->createMany($permissions);
173 $entity->load('permissions');
174 $this->app[PermissionService::class]->buildJointPermissionsForEntity($entity);
175 $entity->load('jointPermissions');
179 * Give the given user some permissions.
181 protected function giveUserPermissions(User $user, array $permissions = []): void
183 $newRole = $this->createNewRole($permissions);
184 $user->attachRole($newRole);
185 $user->load('roles');
186 $user->clearPermissionCache();
190 * Completely remove the given permission name from the given user.
192 protected function removePermissionFromUser(User $user, string $permission)
194 $permission = RolePermission::query()->where('name', '=', $permission)->first();
195 /** @var Role $role */
196 foreach ($user->roles as $role) {
197 $role->detachPermission($permission);
199 $user->clearPermissionCache();
203 * Create a new basic role for testing purposes.
205 protected function createNewRole(array $permissions = []): Role
207 $permissionRepo = app(PermissionsRepo::class);
208 $roleData = factory(Role::class)->make()->toArray();
209 $roleData['permissions'] = array_flip($permissions);
211 return $permissionRepo->saveNewRole($roleData);
215 * Mock the HttpFetcher service and return the given data on fetch.
217 protected function mockHttpFetch($returnData, int $times = 1)
219 $mockHttp = Mockery::mock(HttpFetcher::class);
220 $this->app[HttpFetcher::class] = $mockHttp;
221 $mockHttp->shouldReceive('fetch')
223 ->andReturn($returnData);
227 * Run a set test with the given env variable.
228 * Remembers the original and resets the value after test.
230 protected function runWithEnv(string $name, $value, callable $callback)
232 Env::disablePutenv();
233 $originalVal = $_SERVER[$name] ?? null;
235 if (is_null($value)) {
236 unset($_SERVER[$name]);
238 $_SERVER[$name] = $value;
241 $this->refreshApplication();
244 if (is_null($originalVal)) {
245 unset($_SERVER[$name]);
247 $_SERVER[$name] = $originalVal;
252 * Check the keys and properties in the given map to include
253 * exist, albeit not exclusively, within the map to check.
255 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
259 foreach ($mapToInclude as $key => $value) {
260 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
265 $toIncludeStr = print_r($mapToInclude, true);
266 $toCheckStr = print_r($mapToCheck, true);
267 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
271 * Assert a permission error has occurred.
273 protected function assertPermissionError($response)
275 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
279 * Assert a permission error has occurred.
281 protected function assertNotPermissionError($response)
283 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
287 * Check if the given response is a permission error.
289 private function isPermissionError($response): bool
291 return $response->status() === 302
294 $response->headers->get('Location') === url('/')
295 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
299 $response instanceof JsonResponse &&
300 $response->json(['error' => 'You do not have permission to perform the requested action.'])
306 * Set a test handler as the logging interface for the application.
307 * Allows capture of logs for checking against during tests.
309 protected function withTestLogger(): TestHandler
311 $monolog = new Logger('testing');
312 $testHandler = new TestHandler();
313 $monolog->pushHandler($testHandler);
315 Log::extend('testing', function () use ($monolog) {
318 Log::setDefaultDriver('testing');