]> BookStack Code Mirror - bookstack/blob - tests/SharedTestHelpers.php
Fix Crowdin name in the language_request issue template
[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 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[PermissionService::class]->buildJointPermissionsForEntity($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 $permission)
198     {
199         $permission = RolePermission::query()->where('name', '=', $permission)->first();
200         /** @var Role $role */
201         foreach ($user->roles as $role) {
202             $role->detachPermission($permission);
203         }
204         $user->clearPermissionCache();
205     }
206
207     /**
208      * Create a new basic role for testing purposes.
209      */
210     protected function createNewRole(array $permissions = []): Role
211     {
212         $permissionRepo = app(PermissionsRepo::class);
213         $roleData = Role::factory()->make()->toArray();
214         $roleData['permissions'] = array_flip($permissions);
215
216         return $permissionRepo->saveNewRole($roleData);
217     }
218
219     /**
220      * Create a group of entities that belong to a specific user.
221      *
222      * @return array{book: Book, chapter: Chapter, page: Page}
223      */
224     protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
225     {
226         if (empty($updaterUser)) {
227             $updaterUser = $creatorUser;
228         }
229
230         $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
231         $book = Book::factory()->create($userAttrs);
232         $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
233         $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
234         $restrictionService = $this->app[PermissionService::class];
235         $restrictionService->buildJointPermissionsForEntity($book);
236
237         return compact('book', 'chapter', 'page');
238     }
239
240     /**
241      * Mock the HttpFetcher service and return the given data on fetch.
242      */
243     protected function mockHttpFetch($returnData, int $times = 1)
244     {
245         $mockHttp = Mockery::mock(HttpFetcher::class);
246         $this->app[HttpFetcher::class] = $mockHttp;
247         $mockHttp->shouldReceive('fetch')
248             ->times($times)
249             ->andReturn($returnData);
250     }
251
252     /**
253      * Mock the http client used in BookStack.
254      * Returns a reference to the container which holds all history of http transactions.
255      *
256      * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
257      */
258     protected function &mockHttpClient(array $responses = []): array
259     {
260         $container = [];
261         $history = Middleware::history($container);
262         $mock = new MockHandler($responses);
263         $handlerStack = new HandlerStack($mock);
264         $handlerStack->push($history);
265         $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
266
267         return $container;
268     }
269
270     /**
271      * Run a set test with the given env variable.
272      * Remembers the original and resets the value after test.
273      */
274     protected function runWithEnv(string $name, $value, callable $callback)
275     {
276         Env::disablePutenv();
277         $originalVal = $_SERVER[$name] ?? null;
278
279         if (is_null($value)) {
280             unset($_SERVER[$name]);
281         } else {
282             $_SERVER[$name] = $value;
283         }
284
285         $this->refreshApplication();
286         $callback();
287
288         if (is_null($originalVal)) {
289             unset($_SERVER[$name]);
290         } else {
291             $_SERVER[$name] = $originalVal;
292         }
293     }
294
295     /**
296      * Check the keys and properties in the given map to include
297      * exist, albeit not exclusively, within the map to check.
298      */
299     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
300     {
301         $passed = true;
302
303         foreach ($mapToInclude as $key => $value) {
304             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
305                 $passed = false;
306             }
307         }
308
309         $toIncludeStr = print_r($mapToInclude, true);
310         $toCheckStr = print_r($mapToCheck, true);
311         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
312     }
313
314     /**
315      * Assert a permission error has occurred.
316      */
317     protected function assertPermissionError($response)
318     {
319         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
320     }
321
322     /**
323      * Assert a permission error has occurred.
324      */
325     protected function assertNotPermissionError($response)
326     {
327         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
328     }
329
330     /**
331      * Check if the given response is a permission error.
332      */
333     private function isPermissionError($response): bool
334     {
335         return $response->status() === 302
336             && (
337                 (
338                     $response->headers->get('Location') === url('/')
339                     && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
340                 )
341                 ||
342                 (
343                     $response instanceof JsonResponse &&
344                     $response->json(['error' => 'You do not have permission to perform the requested action.'])
345                 )
346             );
347     }
348
349     /**
350      * Assert that the session has a particular error notification message set.
351      */
352     protected function assertSessionError(string $message)
353     {
354         $error = session()->get('error');
355         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
356     }
357
358     /**
359      * Set a test handler as the logging interface for the application.
360      * Allows capture of logs for checking against during tests.
361      */
362     protected function withTestLogger(): TestHandler
363     {
364         $monolog = new Logger('testing');
365         $testHandler = new TestHandler();
366         $monolog->pushHandler($testHandler);
367
368         Log::extend('testing', function () use ($monolog) {
369             return $monolog;
370         });
371         Log::setDefaultDriver('testing');
372
373         return $testHandler;
374     }
375 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.