3 use BookStack\Auth\User;
4 use BookStack\Entities\Book;
5 use BookStack\Entities\Bookshelf;
6 use BookStack\Entities\Chapter;
7 use BookStack\Entities\Entity;
8 use BookStack\Entities\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;
22 trait SharedTestHelpers
29 * Set the current user context to be an admin.
32 public function asAdmin()
34 return $this->actingAs($this->getAdmin());
38 * Get the current admin user.
41 public function getAdmin() {
42 if($this->admin === null) {
43 $adminRole = Role::getSystemRole('admin');
44 $this->admin = $adminRole->users->first();
50 * Set the current user context to be an editor.
53 public function asEditor()
55 return $this->actingAs($this->getEditor());
63 protected function getEditor() {
64 if($this->editor === null) {
65 $editorRole = Role::getRole('editor');
66 $this->editor = $editorRole->users->first();
72 * Get an instance of a user with 'viewer' permissions
76 protected function getViewer($attributes = [])
78 $user = Role::getRole('viewer')->users()->first();
79 if (!empty($attributes)) $user->forceFill($attributes)->save();
84 * Regenerate the permission for an entity.
85 * @param Entity $entity
88 protected function regenEntityPermissions(Entity $entity)
90 $entity->rebuildPermissions();
91 $entity->load('jointPermissions');
95 * Create and return a new bookshelf.
99 public function newShelf($input = ['name' => 'test shelf', 'description' => 'My new test shelf']) {
100 return app(BookshelfRepo::class)->create($input, []);
104 * Create and return a new book.
105 * @param array $input
108 public function newBook($input = ['name' => 'test book', 'description' => 'My new test book']) {
109 return app(BookRepo::class)->create($input);
113 * Create and return a new test chapter
114 * @param array $input
118 public function newChapter($input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book) {
119 return app(ChapterRepo::class)->create($input, $book);
123 * Create and return a new test page
124 * @param array $input
128 public function newPage($input = ['name' => 'test page', 'html' => 'My new test page']) {
129 $book = Book::first();
130 $pageRepo = app(PageRepo::class);
131 $draftPage = $pageRepo->getNewDraftPage($book);
132 return $pageRepo->publishDraft($draftPage, $input);
136 * Quickly sets an array of settings.
137 * @param $settingsArray
139 protected function setSettings($settingsArray)
141 $settings = app(SettingService::class);
142 foreach ($settingsArray as $key => $value) {
143 $settings->put($key, $value);
148 * Manually set some permissions on an entity.
149 * @param Entity $entity
150 * @param array $actions
151 * @param array $roles
153 protected function setEntityRestrictions(Entity $entity, $actions = [], $roles = [])
155 $entity->restricted = true;
156 $entity->permissions()->delete();
159 foreach ($actions as $action) {
160 foreach ($roles as $role) {
162 'role_id' => $role->id,
163 'action' => strtolower($action)
167 $entity->permissions()->createMany($permissions);
170 $entity->load('permissions');
171 $this->app[PermissionService::class]->buildJointPermissionsForEntity($entity);
172 $entity->load('jointPermissions');
176 * Give the given user some permissions.
178 * @param array $permissions
180 protected function giveUserPermissions(User $user, $permissions = [])
182 $newRole = $this->createNewRole($permissions);
183 $user->attachRole($newRole);
184 $user->load('roles');
185 $user->permissions(false);
189 * Create a new basic role for testing purposes.
190 * @param array $permissions
193 protected function createNewRole($permissions = [])
195 $permissionRepo = app(PermissionsRepo::class);
196 $roleData = factory(Role::class)->make()->toArray();
197 $roleData['permissions'] = array_flip($permissions);
198 return $permissionRepo->saveNewRole($roleData);
202 * Mock the HttpFetcher service and return the given data on fetch.
206 protected function mockHttpFetch($returnData, int $times = 1)
208 $mockHttp = Mockery::mock(HttpFetcher::class);
209 $this->app[HttpFetcher::class] = $mockHttp;
210 $mockHttp->shouldReceive('fetch')
212 ->andReturn($returnData);
216 * Run a set test with the given env variable.
217 * Remembers the original and resets the value after test.
218 * @param string $name
220 * @param callable $callback
222 protected function runWithEnv(string $name, $value, callable $callback)
224 Env::disablePutenv();
225 $originalVal = $_SERVER[$name] ?? null;
227 if (is_null($value)) {
228 unset($_SERVER[$name]);
230 $_SERVER[$name] = $value;
233 $this->refreshApplication();
236 if (is_null($originalVal)) {
237 unset($_SERVER[$name]);
239 $_SERVER[$name] = $originalVal;
244 * Check the keys and properties in the given map to include
245 * exist, albeit not exclusively, within the map to check.
246 * @param array $mapToInclude
247 * @param array $mapToCheck
248 * @param string $message
250 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = '') : void
254 foreach ($mapToInclude as $key => $value) {
255 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
260 $toIncludeStr = print_r($mapToInclude, true);
261 $toCheckStr = print_r($mapToCheck, true);
262 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
266 * Assert a permission error has occurred.
268 protected function assertPermissionError($response)
270 if ($response instanceof BrowserKitTest) {
271 $response = \Illuminate\Foundation\Testing\TestResponse::fromBaseResponse($response->response);
274 $response->assertRedirect('/');
275 $this->assertSessionHas('error');
276 $error = session()->pull('error');
277 $this->assertStringStartsWith('You do not have permission to access', $error);