]> BookStack Code Mirror - bookstack/blob - tests/SharedTestHelpers.php
Applied StyleCI changes
[bookstack] / tests / SharedTestHelpers.php
1 <?php
2
3 namespace Tests;
4
5 use BookStack\Auth\Permissions\JointPermissionBuilder;
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 GuzzleHttp\Client;
22 use GuzzleHttp\Handler\MockHandler;
23 use GuzzleHttp\HandlerStack;
24 use GuzzleHttp\Middleware;
25 use Illuminate\Http\JsonResponse;
26 use Illuminate\Support\Env;
27 use Illuminate\Support\Facades\Log;
28 use Illuminate\Testing\Assert as PHPUnit;
29 use Mockery;
30 use Monolog\Handler\TestHandler;
31 use Monolog\Logger;
32 use Psr\Http\Client\ClientInterface;
33
34 trait SharedTestHelpers
35 {
36     protected $admin;
37     protected $editor;
38
39     /**
40      * Set the current user context to be an admin.
41      */
42     public function asAdmin()
43     {
44         return $this->actingAs($this->getAdmin());
45     }
46
47     /**
48      * Get the current admin user.
49      */
50     public function getAdmin(): User
51     {
52         if (is_null($this->admin)) {
53             $adminRole = Role::getSystemRole('admin');
54             $this->admin = $adminRole->users->first();
55         }
56
57         return $this->admin;
58     }
59
60     /**
61      * Set the current user context to be an editor.
62      */
63     public function asEditor()
64     {
65         return $this->actingAs($this->getEditor());
66     }
67
68     /**
69      * Get a editor user.
70      */
71     protected function getEditor(): User
72     {
73         if ($this->editor === null) {
74             $editorRole = Role::getRole('editor');
75             $this->editor = $editorRole->users->first();
76         }
77
78         return $this->editor;
79     }
80
81     /**
82      * Get an instance of a user with 'viewer' permissions.
83      */
84     protected function getViewer(array $attributes = []): User
85     {
86         $user = Role::getRole('viewer')->users()->first();
87         if (!empty($attributes)) {
88             $user->forceFill($attributes)->save();
89         }
90
91         return $user;
92     }
93
94     /**
95      * Get a user that's not a system user such as the guest user.
96      */
97     public function getNormalUser(): User
98     {
99         return User::query()->where('system_name', '=', null)->get()->last();
100     }
101
102     /**
103      * Regenerate the permission for an entity.
104      */
105     protected function regenEntityPermissions(Entity $entity): void
106     {
107         $entity->rebuildPermissions();
108         $entity->load('jointPermissions');
109     }
110
111     /**
112      * Create and return a new bookshelf.
113      */
114     public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
115     {
116         return app(BookshelfRepo::class)->create($input, []);
117     }
118
119     /**
120      * Create and return a new book.
121      */
122     public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
123     {
124         return app(BookRepo::class)->create($input);
125     }
126
127     /**
128      * Create and return a new test chapter.
129      */
130     public function newChapter(array $input, Book $book): Chapter
131     {
132         return app(ChapterRepo::class)->create($input, $book);
133     }
134
135     /**
136      * Create and return a new test page.
137      */
138     public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
139     {
140         $book = Book::query()->first();
141         $pageRepo = app(PageRepo::class);
142         $draftPage = $pageRepo->getNewDraftPage($book);
143
144         return $pageRepo->publishDraft($draftPage, $input);
145     }
146
147     /**
148      * Quickly sets an array of settings.
149      */
150     protected function setSettings(array $settingsArray): void
151     {
152         $settings = app(SettingService::class);
153         foreach ($settingsArray as $key => $value) {
154             $settings->put($key, $value);
155         }
156     }
157
158     /**
159      * Manually set some permissions on an entity.
160      */
161     protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
162     {
163         $entity->restricted = true;
164         $entity->permissions()->delete();
165
166         $permissions = [];
167         foreach ($actions as $action) {
168             foreach ($roles as $role) {
169                 $permissions[] = [
170                     'role_id' => $role->id,
171                     'action'  => strtolower($action),
172                 ];
173             }
174         }
175         $entity->permissions()->createMany($permissions);
176
177         $entity->save();
178         $entity->load('permissions');
179         $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($entity);
180         $entity->load('jointPermissions');
181     }
182
183     /**
184      * Give the given user some permissions.
185      */
186     protected function giveUserPermissions(User $user, array $permissions = []): void
187     {
188         $newRole = $this->createNewRole($permissions);
189         $user->attachRole($newRole);
190         $user->load('roles');
191         $user->clearPermissionCache();
192     }
193
194     /**
195      * Completely remove the given permission name from the given user.
196      */
197     protected function removePermissionFromUser(User $user, string $permissionName)
198     {
199         $permissionBuilder = app()->make(JointPermissionBuilder::class);
200
201         /** @var RolePermission $permission */
202         $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
203
204         $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
205             $query->where('id', '=', $permission->id);
206         })->get();
207
208         /** @var Role $role */
209         foreach ($roles as $role) {
210             $role->detachPermission($permission);
211             $permissionBuilder->rebuildForRole($role);
212         }
213
214         $user->clearPermissionCache();
215     }
216
217     /**
218      * Create a new basic role for testing purposes.
219      */
220     protected function createNewRole(array $permissions = []): Role
221     {
222         $permissionRepo = app(PermissionsRepo::class);
223         $roleData = Role::factory()->make()->toArray();
224         $roleData['permissions'] = array_flip($permissions);
225
226         return $permissionRepo->saveNewRole($roleData);
227     }
228
229     /**
230      * Create a group of entities that belong to a specific user.
231      *
232      * @return array{book: Book, chapter: Chapter, page: Page}
233      */
234     protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
235     {
236         if (empty($updaterUser)) {
237             $updaterUser = $creatorUser;
238         }
239
240         $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
241         $book = Book::factory()->create($userAttrs);
242         $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
243         $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
244
245         $this->app->make(JointPermissionBuilder::class)->rebuildForEntity($book);
246
247         return compact('book', 'chapter', 'page');
248     }
249
250     /**
251      * Mock the HttpFetcher service and return the given data on fetch.
252      */
253     protected function mockHttpFetch($returnData, int $times = 1)
254     {
255         $mockHttp = Mockery::mock(HttpFetcher::class);
256         $this->app[HttpFetcher::class] = $mockHttp;
257         $mockHttp->shouldReceive('fetch')
258             ->times($times)
259             ->andReturn($returnData);
260     }
261
262     /**
263      * Mock the http client used in BookStack.
264      * Returns a reference to the container which holds all history of http transactions.
265      *
266      * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
267      */
268     protected function &mockHttpClient(array $responses = []): array
269     {
270         $container = [];
271         $history = Middleware::history($container);
272         $mock = new MockHandler($responses);
273         $handlerStack = new HandlerStack($mock);
274         $handlerStack->push($history);
275         $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
276
277         return $container;
278     }
279
280     /**
281      * Run a set test with the given env variable.
282      * Remembers the original and resets the value after test.
283      */
284     protected function runWithEnv(string $name, $value, callable $callback)
285     {
286         Env::disablePutenv();
287         $originalVal = $_SERVER[$name] ?? null;
288
289         if (is_null($value)) {
290             unset($_SERVER[$name]);
291         } else {
292             $_SERVER[$name] = $value;
293         }
294
295         $this->refreshApplication();
296         $callback();
297
298         if (is_null($originalVal)) {
299             unset($_SERVER[$name]);
300         } else {
301             $_SERVER[$name] = $originalVal;
302         }
303     }
304
305     /**
306      * Check the keys and properties in the given map to include
307      * exist, albeit not exclusively, within the map to check.
308      */
309     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
310     {
311         $passed = true;
312
313         foreach ($mapToInclude as $key => $value) {
314             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
315                 $passed = false;
316             }
317         }
318
319         $toIncludeStr = print_r($mapToInclude, true);
320         $toCheckStr = print_r($mapToCheck, true);
321         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
322     }
323
324     /**
325      * Assert a permission error has occurred.
326      */
327     protected function assertPermissionError($response)
328     {
329         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
330     }
331
332     /**
333      * Assert a permission error has occurred.
334      */
335     protected function assertNotPermissionError($response)
336     {
337         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
338     }
339
340     /**
341      * Check if the given response is a permission error.
342      */
343     private function isPermissionError($response): bool
344     {
345         return $response->status() === 302
346             && (
347                 (
348                     $response->headers->get('Location') === url('/')
349                     && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
350                 )
351                 ||
352                 (
353                     $response instanceof JsonResponse &&
354                     $response->json(['error' => 'You do not have permission to perform the requested action.'])
355                 )
356             );
357     }
358
359     /**
360      * Assert that the session has a particular error notification message set.
361      */
362     protected function assertSessionError(string $message)
363     {
364         $error = session()->get('error');
365         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
366     }
367
368     /**
369      * Set a test handler as the logging interface for the application.
370      * Allows capture of logs for checking against during tests.
371      */
372     protected function withTestLogger(): TestHandler
373     {
374         $monolog = new Logger('testing');
375         $testHandler = new TestHandler();
376         $monolog->pushHandler($testHandler);
377
378         Log::extend('testing', function () use ($monolog) {
379             return $monolog;
380         });
381         Log::setDefaultDriver('testing');
382
383         return $testHandler;
384     }
385 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.