]> BookStack Code Mirror - bookstack/blob - tests/SharedTestHelpers.php
Added role permissions for exporting content
[bookstack] / tests / SharedTestHelpers.php
1 <?php
2
3 namespace Tests;
4
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;
25 use Mockery;
26 use Monolog\Handler\TestHandler;
27 use Monolog\Logger;
28
29 trait SharedTestHelpers
30 {
31     protected $admin;
32     protected $editor;
33
34     /**
35      * Set the current user context to be an admin.
36      */
37     public function asAdmin()
38     {
39         return $this->actingAs($this->getAdmin());
40     }
41
42     /**
43      * Get the current admin user.
44      */
45     public function getAdmin(): User
46     {
47         if (is_null($this->admin)) {
48             $adminRole = Role::getSystemRole('admin');
49             $this->admin = $adminRole->users->first();
50         }
51
52         return $this->admin;
53     }
54
55     /**
56      * Set the current user context to be an editor.
57      */
58     public function asEditor()
59     {
60         return $this->actingAs($this->getEditor());
61     }
62
63     /**
64      * Get a editor user.
65      */
66     protected function getEditor(): User
67     {
68         if ($this->editor === null) {
69             $editorRole = Role::getRole('editor');
70             $this->editor = $editorRole->users->first();
71         }
72
73         return $this->editor;
74     }
75
76     /**
77      * Get an instance of a user with 'viewer' permissions.
78      */
79     protected function getViewer(array $attributes = []): User
80     {
81         $user = Role::getRole('viewer')->users()->first();
82         if (!empty($attributes)) {
83             $user->forceFill($attributes)->save();
84         }
85
86         return $user;
87     }
88
89     /**
90      * Get a user that's not a system user such as the guest user.
91      */
92     public function getNormalUser()
93     {
94         return User::query()->where('system_name', '=', null)->get()->last();
95     }
96
97     /**
98      * Regenerate the permission for an entity.
99      */
100     protected function regenEntityPermissions(Entity $entity): void
101     {
102         $entity->rebuildPermissions();
103         $entity->load('jointPermissions');
104     }
105
106     /**
107      * Create and return a new bookshelf.
108      */
109     public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
110     {
111         return app(BookshelfRepo::class)->create($input, []);
112     }
113
114     /**
115      * Create and return a new book.
116      */
117     public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
118     {
119         return app(BookRepo::class)->create($input);
120     }
121
122     /**
123      * Create and return a new test chapter.
124      */
125     public function newChapter(array $input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book): Chapter
126     {
127         return app(ChapterRepo::class)->create($input, $book);
128     }
129
130     /**
131      * Create and return a new test page.
132      */
133     public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
134     {
135         $book = Book::query()->first();
136         $pageRepo = app(PageRepo::class);
137         $draftPage = $pageRepo->getNewDraftPage($book);
138
139         return $pageRepo->publishDraft($draftPage, $input);
140     }
141
142     /**
143      * Quickly sets an array of settings.
144      */
145     protected function setSettings(array $settingsArray): void
146     {
147         $settings = app(SettingService::class);
148         foreach ($settingsArray as $key => $value) {
149             $settings->put($key, $value);
150         }
151     }
152
153     /**
154      * Manually set some permissions on an entity.
155      */
156     protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
157     {
158         $entity->restricted = true;
159         $entity->permissions()->delete();
160
161         $permissions = [];
162         foreach ($actions as $action) {
163             foreach ($roles as $role) {
164                 $permissions[] = [
165                     'role_id' => $role->id,
166                     'action'  => strtolower($action),
167                 ];
168             }
169         }
170         $entity->permissions()->createMany($permissions);
171
172         $entity->save();
173         $entity->load('permissions');
174         $this->app[PermissionService::class]->buildJointPermissionsForEntity($entity);
175         $entity->load('jointPermissions');
176     }
177
178     /**
179      * Give the given user some permissions.
180      */
181     protected function giveUserPermissions(User $user, array $permissions = []): void
182     {
183         $newRole = $this->createNewRole($permissions);
184         $user->attachRole($newRole);
185         $user->load('roles');
186         $user->clearPermissionCache();
187     }
188
189     /**
190      * Completely remove the given permission name from the given user.
191      */
192     protected function removePermissionFromUser(User $user, string $permission)
193     {
194         $permission = RolePermission::query()->where('name', '=', $permission)->first();
195         /** @var Role $role */
196         foreach ($user->roles as $role) {
197             $role->detachPermission($permission);
198         }
199         $user->clearPermissionCache();
200     }
201
202     /**
203      * Create a new basic role for testing purposes.
204      */
205     protected function createNewRole(array $permissions = []): Role
206     {
207         $permissionRepo = app(PermissionsRepo::class);
208         $roleData = factory(Role::class)->make()->toArray();
209         $roleData['permissions'] = array_flip($permissions);
210
211         return $permissionRepo->saveNewRole($roleData);
212     }
213
214     /**
215      * Mock the HttpFetcher service and return the given data on fetch.
216      */
217     protected function mockHttpFetch($returnData, int $times = 1)
218     {
219         $mockHttp = Mockery::mock(HttpFetcher::class);
220         $this->app[HttpFetcher::class] = $mockHttp;
221         $mockHttp->shouldReceive('fetch')
222             ->times($times)
223             ->andReturn($returnData);
224     }
225
226     /**
227      * Run a set test with the given env variable.
228      * Remembers the original and resets the value after test.
229      */
230     protected function runWithEnv(string $name, $value, callable $callback)
231     {
232         Env::disablePutenv();
233         $originalVal = $_SERVER[$name] ?? null;
234
235         if (is_null($value)) {
236             unset($_SERVER[$name]);
237         } else {
238             $_SERVER[$name] = $value;
239         }
240
241         $this->refreshApplication();
242         $callback();
243
244         if (is_null($originalVal)) {
245             unset($_SERVER[$name]);
246         } else {
247             $_SERVER[$name] = $originalVal;
248         }
249     }
250
251     /**
252      * Check the keys and properties in the given map to include
253      * exist, albeit not exclusively, within the map to check.
254      */
255     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
256     {
257         $passed = true;
258
259         foreach ($mapToInclude as $key => $value) {
260             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
261                 $passed = false;
262             }
263         }
264
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}");
268     }
269
270     /**
271      * Assert a permission error has occurred.
272      */
273     protected function assertPermissionError($response)
274     {
275         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
276     }
277
278     /**
279      * Assert a permission error has occurred.
280      */
281     protected function assertNotPermissionError($response)
282     {
283         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
284     }
285
286     /**
287      * Check if the given response is a permission error.
288      */
289     private function isPermissionError($response): bool
290     {
291         return $response->status() === 302
292             && (
293                 (
294                     $response->headers->get('Location') === url('/')
295                     && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
296                 )
297                 ||
298                 (
299                     $response instanceof JsonResponse &&
300                     $response->json(['error' => 'You do not have permission to perform the requested action.'])
301                 )
302             );
303     }
304
305     /**
306      * Set a test handler as the logging interface for the application.
307      * Allows capture of logs for checking against during tests.
308      */
309     protected function withTestLogger(): TestHandler
310     {
311         $monolog = new Logger('testing');
312         $testHandler = new TestHandler();
313         $monolog->pushHandler($testHandler);
314
315         Log::extend('testing', function () use ($monolog) {
316             return $monolog;
317         });
318         Log::setDefaultDriver('testing');
319
320         return $testHandler;
321     }
322 }