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;
19 use Illuminate\Support\Facades\Log;
21 use Monolog\Handler\TestHandler;
25 trait SharedTestHelpers
32 * Set the current user context to be an admin.
35 public function asAdmin()
37 return $this->actingAs($this->getAdmin());
41 * Get the current admin user.
44 public function getAdmin() {
45 if($this->admin === null) {
46 $adminRole = Role::getSystemRole('admin');
47 $this->admin = $adminRole->users->first();
53 * Set the current user context to be an editor.
56 public function asEditor()
58 return $this->actingAs($this->getEditor());
66 protected function getEditor() {
67 if($this->editor === null) {
68 $editorRole = Role::getRole('editor');
69 $this->editor = $editorRole->users->first();
75 * Get an instance of a user with 'viewer' permissions.
77 protected function getViewer(array $attributes = []): User
79 $user = Role::getRole('viewer')->users()->first();
80 if (!empty($attributes)) {
81 $user->forceFill($attributes)->save();
87 * Regenerate the permission for an entity.
88 * @param Entity $entity
91 protected function regenEntityPermissions(Entity $entity)
93 $entity->rebuildPermissions();
94 $entity->load('jointPermissions');
98 * Create and return a new bookshelf.
102 public function newShelf($input = ['name' => 'test shelf', 'description' => 'My new test shelf']) {
103 return app(BookshelfRepo::class)->create($input, []);
107 * Create and return a new book.
108 * @param array $input
111 public function newBook($input = ['name' => 'test book', 'description' => 'My new test book']) {
112 return app(BookRepo::class)->create($input);
116 * Create and return a new test chapter
117 * @param array $input
121 public function newChapter($input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book) {
122 return app(ChapterRepo::class)->create($input, $book);
126 * Create and return a new test page
127 * @param array $input
131 public function newPage($input = ['name' => 'test page', 'html' => 'My new test page']) {
132 $book = Book::first();
133 $pageRepo = app(PageRepo::class);
134 $draftPage = $pageRepo->getNewDraftPage($book);
135 return $pageRepo->publishDraft($draftPage, $input);
139 * Quickly sets an array of settings.
140 * @param $settingsArray
142 protected function setSettings($settingsArray)
144 $settings = app(SettingService::class);
145 foreach ($settingsArray as $key => $value) {
146 $settings->put($key, $value);
151 * Manually set some permissions on an entity.
152 * @param Entity $entity
153 * @param array $actions
154 * @param array $roles
156 protected function setEntityRestrictions(Entity $entity, $actions = [], $roles = [])
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 * @param array $permissions
183 protected function giveUserPermissions(User $user, $permissions = [])
185 $newRole = $this->createNewRole($permissions);
186 $user->attachRole($newRole);
187 $user->load('roles');
188 $user->permissions(false);
192 * Create a new basic role for testing purposes.
193 * @param array $permissions
196 protected function createNewRole($permissions = [])
198 $permissionRepo = app(PermissionsRepo::class);
199 $roleData = factory(Role::class)->make()->toArray();
200 $roleData['permissions'] = array_flip($permissions);
201 return $permissionRepo->saveNewRole($roleData);
205 * Mock the HttpFetcher service and return the given data on fetch.
209 protected function mockHttpFetch($returnData, int $times = 1)
211 $mockHttp = Mockery::mock(HttpFetcher::class);
212 $this->app[HttpFetcher::class] = $mockHttp;
213 $mockHttp->shouldReceive('fetch')
215 ->andReturn($returnData);
219 * Run a set test with the given env variable.
220 * Remembers the original and resets the value after test.
221 * @param string $name
223 * @param callable $callback
225 protected function runWithEnv(string $name, $value, callable $callback)
227 Env::disablePutenv();
228 $originalVal = $_SERVER[$name] ?? null;
230 if (is_null($value)) {
231 unset($_SERVER[$name]);
233 $_SERVER[$name] = $value;
236 $this->refreshApplication();
239 if (is_null($originalVal)) {
240 unset($_SERVER[$name]);
242 $_SERVER[$name] = $originalVal;
247 * Check the keys and properties in the given map to include
248 * exist, albeit not exclusively, within the map to check.
249 * @param array $mapToInclude
250 * @param array $mapToCheck
251 * @param string $message
253 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = '') : void
257 foreach ($mapToInclude as $key => $value) {
258 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
263 $toIncludeStr = print_r($mapToInclude, true);
264 $toCheckStr = print_r($mapToCheck, true);
265 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
269 * Assert a permission error has occurred.
271 protected function assertPermissionError($response)
273 if ($response instanceof BrowserKitTest) {
274 $response = \Illuminate\Foundation\Testing\TestResponse::fromBaseResponse($response->response);
277 $response->assertRedirect('/');
278 $this->assertSessionHas('error');
279 $error = session()->pull('error');
280 $this->assertStringStartsWith('You do not have permission to access', $error);
284 * Set a test handler as the logging interface for the application.
285 * Allows capture of logs for checking against during tests.
287 protected function withTestLogger(): TestHandler
289 $monolog = new Logger('testing');
290 $testHandler = new TestHandler();
291 $monolog->pushHandler($testHandler);
293 Log::extend('testing', function() use ($monolog) {
296 Log::setDefaultDriver('testing');