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\Http\Response;
19 use Illuminate\Support\Env;
20 use Illuminate\Support\Facades\Log;
22 use Monolog\Handler\TestHandler;
25 use Illuminate\Foundation\Testing\Assert as PHPUnit;
27 trait SharedTestHelpers
34 * 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.
46 public function getAdmin() {
47 if($this->admin === null) {
48 $adminRole = Role::getSystemRole('admin');
49 $this->admin = $adminRole->users->first();
55 * Set the current user context to be an editor.
58 public function asEditor()
60 return $this->actingAs($this->getEditor());
68 protected function getEditor() {
69 if($this->editor === null) {
70 $editorRole = Role::getRole('editor');
71 $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();
89 * Regenerate the permission for an entity.
90 * @param Entity $entity
93 protected function regenEntityPermissions(Entity $entity)
95 $entity->rebuildPermissions();
96 $entity->load('jointPermissions');
100 * Create and return a new bookshelf.
101 * @param array $input
104 public function newShelf($input = ['name' => 'test shelf', 'description' => 'My new test shelf']) {
105 return app(BookshelfRepo::class)->create($input, []);
109 * Create and return a new book.
110 * @param array $input
113 public function newBook($input = ['name' => 'test book', 'description' => 'My new test book']) {
114 return app(BookRepo::class)->create($input);
118 * Create and return a new test chapter
119 * @param array $input
123 public function newChapter($input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book) {
124 return app(ChapterRepo::class)->create($input, $book);
128 * Create and return a new test page
129 * @param array $input
133 public function newPage($input = ['name' => 'test page', 'html' => 'My new test page']) {
134 $book = Book::first();
135 $pageRepo = app(PageRepo::class);
136 $draftPage = $pageRepo->getNewDraftPage($book);
137 return $pageRepo->publishDraft($draftPage, $input);
141 * Quickly sets an array of settings.
142 * @param $settingsArray
144 protected function setSettings($settingsArray)
146 $settings = app(SettingService::class);
147 foreach ($settingsArray as $key => $value) {
148 $settings->put($key, $value);
153 * Manually set some permissions on an entity.
154 * @param Entity $entity
155 * @param array $actions
156 * @param array $roles
158 protected function setEntityRestrictions(Entity $entity, $actions = [], $roles = [])
160 $entity->restricted = true;
161 $entity->permissions()->delete();
164 foreach ($actions as $action) {
165 foreach ($roles as $role) {
167 'role_id' => $role->id,
168 'action' => strtolower($action)
172 $entity->permissions()->createMany($permissions);
175 $entity->load('permissions');
176 $this->app[PermissionService::class]->buildJointPermissionsForEntity($entity);
177 $entity->load('jointPermissions');
181 * Give the given user some permissions.
183 * @param array $permissions
185 protected function giveUserPermissions(User $user, $permissions = [])
187 $newRole = $this->createNewRole($permissions);
188 $user->attachRole($newRole);
189 $user->load('roles');
190 $user->permissions(false);
194 * Create a new basic role for testing purposes.
195 * @param array $permissions
198 protected function createNewRole($permissions = [])
200 $permissionRepo = app(PermissionsRepo::class);
201 $roleData = factory(Role::class)->make()->toArray();
202 $roleData['permissions'] = array_flip($permissions);
203 return $permissionRepo->saveNewRole($roleData);
207 * Mock the HttpFetcher service and return the given data on fetch.
211 protected function mockHttpFetch($returnData, int $times = 1)
213 $mockHttp = Mockery::mock(HttpFetcher::class);
214 $this->app[HttpFetcher::class] = $mockHttp;
215 $mockHttp->shouldReceive('fetch')
217 ->andReturn($returnData);
221 * Run a set test with the given env variable.
222 * Remembers the original and resets the value after test.
223 * @param string $name
225 * @param callable $callback
227 protected function runWithEnv(string $name, $value, callable $callback)
229 Env::disablePutenv();
230 $originalVal = $_SERVER[$name] ?? null;
232 if (is_null($value)) {
233 unset($_SERVER[$name]);
235 $_SERVER[$name] = $value;
238 $this->refreshApplication();
241 if (is_null($originalVal)) {
242 unset($_SERVER[$name]);
244 $_SERVER[$name] = $originalVal;
249 * Check the keys and properties in the given map to include
250 * exist, albeit not exclusively, within the map to check.
251 * @param array $mapToInclude
252 * @param array $mapToCheck
253 * @param string $message
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
292 && $response->headers->get('Location') === url('/')
293 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0;
297 * Set a test handler as the logging interface for the application.
298 * Allows capture of logs for checking against during tests.
300 protected function withTestLogger(): TestHandler
302 $monolog = new Logger('testing');
303 $testHandler = new TestHandler();
304 $monolog->pushHandler($testHandler);
306 Log::extend('testing', function() use ($monolog) {
309 Log::setDefaultDriver('testing');