]> BookStack Code Mirror - bookstack/blob - tests/SharedTestHelpers.php
LDAP: Added TLS support
[bookstack] / tests / SharedTestHelpers.php
1 <?php namespace Tests;
2
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;
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      * @param User $user
183      * @param array $permissions
184      */
185     protected function giveUserPermissions(User $user, $permissions = [])
186     {
187         $newRole = $this->createNewRole($permissions);
188         $user->attachRole($newRole);
189         $user->load('roles');
190         $user->permissions(false);
191     }
192
193     /**
194      * Create a new basic role for testing purposes.
195      * @param array $permissions
196      * @return Role
197      */
198     protected function createNewRole($permissions = [])
199     {
200         $permissionRepo = app(PermissionsRepo::class);
201         $roleData = factory(Role::class)->make()->toArray();
202         $roleData['permissions'] = array_flip($permissions);
203         return $permissionRepo->saveNewRole($roleData);
204     }
205
206     /**
207      * Mock the HttpFetcher service and return the given data on fetch.
208      * @param $returnData
209      * @param int $times
210      */
211     protected function mockHttpFetch($returnData, int $times = 1)
212     {
213         $mockHttp = Mockery::mock(HttpFetcher::class);
214         $this->app[HttpFetcher::class] = $mockHttp;
215         $mockHttp->shouldReceive('fetch')
216             ->times($times)
217             ->andReturn($returnData);
218     }
219
220     /**
221      * Run a set test with the given env variable.
222      * Remembers the original and resets the value after test.
223      * @param string $name
224      * @param $value
225      * @param callable $callback
226      */
227     protected function runWithEnv(string $name, $value, callable $callback)
228     {
229         Env::disablePutenv();
230         $originalVal = $_SERVER[$name] ?? null;
231
232         if (is_null($value)) {
233             unset($_SERVER[$name]);
234         } else {
235             $_SERVER[$name] = $value;
236         }
237
238         $this->refreshApplication();
239         $callback();
240
241         if (is_null($originalVal)) {
242             unset($_SERVER[$name]);
243         } else {
244             $_SERVER[$name] = $originalVal;
245         }
246     }
247
248     /**
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
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             && $response->headers->get('Location') === url('/')
293             && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0;
294     }
295
296     /**
297      * Set a test handler as the logging interface for the application.
298      * Allows capture of logs for checking against during tests.
299      */
300     protected function withTestLogger(): TestHandler
301     {
302         $monolog = new Logger('testing');
303         $testHandler = new TestHandler();
304         $monolog->pushHandler($testHandler);
305
306         Log::extend('testing', function() use ($monolog) {
307             return $monolog;
308         });
309         Log::setDefaultDriver('testing');
310
311         return $testHandler;
312     }
313
314 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.