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