3 use BookStack\Auth\User;
4 use BookStack\Entities\Models\Book;
5 use BookStack\Entities\Models\Bookshelf;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\Page;
9 use BookStack\Entities\Repos\BookRepo;
10 use BookStack\Entities\Repos\BookshelfRepo;
11 use BookStack\Entities\Repos\ChapterRepo;
12 use BookStack\Auth\Permissions\PermissionsRepo;
13 use BookStack\Auth\Role;
14 use BookStack\Auth\Permissions\PermissionService;
15 use BookStack\Entities\Repos\PageRepo;
16 use BookStack\Settings\SettingService;
17 use BookStack\Uploads\HttpFetcher;
18 use Illuminate\Support\Env;
19 use Illuminate\Support\Facades\Log;
21 use Monolog\Handler\TestHandler;
23 use Illuminate\Foundation\Testing\Assert as PHPUnit;
25 trait SharedTestHelpers
32 * Set the current user context to be an admin.
34 public function asAdmin()
36 return $this->actingAs($this->getAdmin());
40 * Get the current admin user.
42 public function getAdmin(): User
44 if (is_null($this->admin)) {
45 $adminRole = Role::getSystemRole('admin');
46 $this->admin = $adminRole->users->first();
53 * Set the current user context to be an editor.
55 public function asEditor()
57 return $this->actingAs($this->getEditor());
64 protected function getEditor(): User
66 if ($this->editor === null) {
67 $editorRole = Role::getRole('editor');
68 $this->editor = $editorRole->users->first();
74 * Get an instance of a user with 'viewer' permissions.
76 protected function getViewer(array $attributes = []): User
78 $user = Role::getRole('viewer')->users()->first();
79 if (!empty($attributes)) {
80 $user->forceFill($attributes)->save();
86 * Get a user that's not a system user such as the guest user.
88 public function getNormalUser()
90 return User::query()->where('system_name', '=', null)->get()->last();
94 * Regenerate the permission for an entity.
96 protected function regenEntityPermissions(Entity $entity): void
98 $entity->rebuildPermissions();
99 $entity->load('jointPermissions');
103 * Create and return a new bookshelf.
105 public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
107 return app(BookshelfRepo::class)->create($input, []);
111 * Create and return a new book.
113 public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
115 return app(BookRepo::class)->create($input);
119 * Create and return a new test chapter
121 public function newChapter(array $input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book): Chapter
123 return app(ChapterRepo::class)->create($input, $book);
127 * Create and return a new test page
129 public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
131 $book = Book::query()->first();
132 $pageRepo = app(PageRepo::class);
133 $draftPage = $pageRepo->getNewDraftPage($book);
134 return $pageRepo->publishDraft($draftPage, $input);
138 * Quickly sets an array of settings.
140 protected function setSettings(array $settingsArray): void
142 $settings = app(SettingService::class);
143 foreach ($settingsArray as $key => $value) {
144 $settings->put($key, $value);
149 * Manually set some permissions on an entity.
151 protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
153 $entity->restricted = true;
154 $entity->permissions()->delete();
157 foreach ($actions as $action) {
158 foreach ($roles as $role) {
160 'role_id' => $role->id,
161 'action' => strtolower($action)
165 $entity->permissions()->createMany($permissions);
168 $entity->load('permissions');
169 $this->app[PermissionService::class]->buildJointPermissionsForEntity($entity);
170 $entity->load('jointPermissions');
174 * Give the given user some permissions.
176 protected function giveUserPermissions(User $user, array $permissions = []): void
178 $newRole = $this->createNewRole($permissions);
179 $user->attachRole($newRole);
180 $user->load('roles');
181 $user->clearPermissionCache();
185 * Create a new basic role for testing purposes.
187 protected function createNewRole(array $permissions = []): Role
189 $permissionRepo = app(PermissionsRepo::class);
190 $roleData = factory(Role::class)->make()->toArray();
191 $roleData['permissions'] = array_flip($permissions);
192 return $permissionRepo->saveNewRole($roleData);
196 * Mock the HttpFetcher service and return the given data on fetch.
198 protected function mockHttpFetch($returnData, int $times = 1)
200 $mockHttp = Mockery::mock(HttpFetcher::class);
201 $this->app[HttpFetcher::class] = $mockHttp;
202 $mockHttp->shouldReceive('fetch')
204 ->andReturn($returnData);
208 * Run a set test with the given env variable.
209 * Remembers the original and resets the value after test.
211 protected function runWithEnv(string $name, $value, callable $callback)
213 Env::disablePutenv();
214 $originalVal = $_SERVER[$name] ?? null;
216 if (is_null($value)) {
217 unset($_SERVER[$name]);
219 $_SERVER[$name] = $value;
222 $this->refreshApplication();
225 if (is_null($originalVal)) {
226 unset($_SERVER[$name]);
228 $_SERVER[$name] = $originalVal;
233 * Check the keys and properties in the given map to include
234 * exist, albeit not exclusively, within the map to check.
236 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
240 foreach ($mapToInclude as $key => $value) {
241 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
246 $toIncludeStr = print_r($mapToInclude, true);
247 $toCheckStr = print_r($mapToCheck, true);
248 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
252 * Assert a permission error has occurred.
254 protected function assertPermissionError($response)
256 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), "Failed asserting the response contains a permission error.");
260 * Assert a permission error has occurred.
262 protected function assertNotPermissionError($response)
264 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), "Failed asserting the response does not contain a permission error.");
268 * Check if the given response is a permission error.
270 private function isPermissionError($response): bool
272 return $response->status() === 302
273 && $response->headers->get('Location') === url('/')
274 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0;
278 * Set a test handler as the logging interface for the application.
279 * Allows capture of logs for checking against during tests.
281 protected function withTestLogger(): TestHandler
283 $monolog = new Logger('testing');
284 $testHandler = new TestHandler();
285 $monolog->pushHandler($testHandler);
287 Log::extend('testing', function () use ($monolog) {
290 Log::setDefaultDriver('testing');