]> BookStack Code Mirror - bookstack/blob - tests/SharedTestHelpers.php
Merge branch 'master' of git://github.com/Binternet/BookStack into Binternet-master
[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\Support\Env;
19 use Mockery;
20 use Throwable;
21
22 trait SharedTestHelpers
23 {
24
25     protected $admin;
26     protected $editor;
27
28     /**
29      * Set the current user context to be an admin.
30      * @return $this
31      */
32     public function asAdmin()
33     {
34         return $this->actingAs($this->getAdmin());
35     }
36
37     /**
38      * Get the current admin user.
39      * @return mixed
40      */
41     public function getAdmin() {
42         if($this->admin === null) {
43             $adminRole = Role::getSystemRole('admin');
44             $this->admin = $adminRole->users->first();
45         }
46         return $this->admin;
47     }
48
49     /**
50      * Set the current user context to be an editor.
51      * @return $this
52      */
53     public function asEditor()
54     {
55         return $this->actingAs($this->getEditor());
56     }
57
58
59     /**
60      * Get a editor user.
61      * @return mixed
62      */
63     protected function getEditor() {
64         if($this->editor === null) {
65             $editorRole = Role::getRole('editor');
66             $this->editor = $editorRole->users->first();
67         }
68         return $this->editor;
69     }
70
71     /**
72      * Get an instance of a user with 'viewer' permissions
73      * @param $attributes
74      * @return mixed
75      */
76     protected function getViewer($attributes = [])
77     {
78         $user = Role::getRole('viewer')->users()->first();
79         if (!empty($attributes)) $user->forceFill($attributes)->save();
80         return $user;
81     }
82
83     /**
84      * Regenerate the permission for an entity.
85      * @param Entity $entity
86      * @throws Throwable
87      */
88     protected function regenEntityPermissions(Entity $entity)
89     {
90         $entity->rebuildPermissions();
91         $entity->load('jointPermissions');
92     }
93
94     /**
95      * Create and return a new bookshelf.
96      * @param array $input
97      * @return Bookshelf
98      */
99     public function newShelf($input = ['name' => 'test shelf', 'description' => 'My new test shelf']) {
100         return app(BookshelfRepo::class)->create($input, []);
101     }
102
103     /**
104      * Create and return a new book.
105      * @param array $input
106      * @return Book
107      */
108     public function newBook($input = ['name' => 'test book', 'description' => 'My new test book']) {
109         return app(BookRepo::class)->create($input);
110     }
111
112     /**
113      * Create and return a new test chapter
114      * @param array $input
115      * @param Book $book
116      * @return Chapter
117      */
118     public function newChapter($input = ['name' => 'test chapter', 'description' => 'My new test chapter'], Book $book) {
119         return app(ChapterRepo::class)->create($input, $book);
120     }
121
122     /**
123      * Create and return a new test page
124      * @param array $input
125      * @return Page
126      * @throws Throwable
127      */
128     public function newPage($input = ['name' => 'test page', 'html' => 'My new test page']) {
129         $book = Book::first();
130         $pageRepo = app(PageRepo::class);
131         $draftPage = $pageRepo->getNewDraftPage($book);
132         return $pageRepo->publishDraft($draftPage, $input);
133     }
134
135     /**
136      * Quickly sets an array of settings.
137      * @param $settingsArray
138      */
139     protected function setSettings($settingsArray)
140     {
141         $settings = app(SettingService::class);
142         foreach ($settingsArray as $key => $value) {
143             $settings->put($key, $value);
144         }
145     }
146
147     /**
148      * Manually set some permissions on an entity.
149      * @param Entity $entity
150      * @param array $actions
151      * @param array $roles
152      */
153     protected function setEntityRestrictions(Entity $entity, $actions = [], $roles = [])
154     {
155         $entity->restricted = true;
156         $entity->permissions()->delete();
157
158         $permissions = [];
159         foreach ($actions as $action) {
160             foreach ($roles as $role) {
161                 $permissions[] = [
162                     'role_id' => $role->id,
163                     'action' => strtolower($action)
164                 ];
165             }
166         }
167         $entity->permissions()->createMany($permissions);
168
169         $entity->save();
170         $entity->load('permissions');
171         $this->app[PermissionService::class]->buildJointPermissionsForEntity($entity);
172         $entity->load('jointPermissions');
173     }
174
175     /**
176      * Give the given user some permissions.
177      * @param User $user
178      * @param array $permissions
179      */
180     protected function giveUserPermissions(User $user, $permissions = [])
181     {
182         $newRole = $this->createNewRole($permissions);
183         $user->attachRole($newRole);
184         $user->load('roles');
185         $user->permissions(false);
186     }
187
188     /**
189      * Create a new basic role for testing purposes.
190      * @param array $permissions
191      * @return Role
192      */
193     protected function createNewRole($permissions = [])
194     {
195         $permissionRepo = app(PermissionsRepo::class);
196         $roleData = factory(Role::class)->make()->toArray();
197         $roleData['permissions'] = array_flip($permissions);
198         return $permissionRepo->saveNewRole($roleData);
199     }
200
201     /**
202      * Mock the HttpFetcher service and return the given data on fetch.
203      * @param $returnData
204      * @param int $times
205      */
206     protected function mockHttpFetch($returnData, int $times = 1)
207     {
208         $mockHttp = Mockery::mock(HttpFetcher::class);
209         $this->app[HttpFetcher::class] = $mockHttp;
210         $mockHttp->shouldReceive('fetch')
211             ->times($times)
212             ->andReturn($returnData);
213     }
214
215     /**
216      * Run a set test with the given env variable.
217      * Remembers the original and resets the value after test.
218      * @param string $name
219      * @param $value
220      * @param callable $callback
221      */
222     protected function runWithEnv(string $name, $value, callable $callback)
223     {
224         Env::disablePutenv();
225         $originalVal = $_SERVER[$name] ?? null;
226
227         if (is_null($value)) {
228             unset($_SERVER[$name]);
229         } else {
230             $_SERVER[$name] = $value;
231         }
232
233         $this->refreshApplication();
234         $callback();
235
236         if (is_null($originalVal)) {
237             unset($_SERVER[$name]);
238         } else {
239             $_SERVER[$name] = $originalVal;
240         }
241     }
242
243     /**
244      * Check the keys and properties in the given map to include
245      * exist, albeit not exclusively, within the map to check.
246      * @param array $mapToInclude
247      * @param array $mapToCheck
248      * @param string $message
249      */
250     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = '') : void
251     {
252         $passed = true;
253
254         foreach ($mapToInclude as $key => $value) {
255             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
256                 $passed = false;
257             }
258         }
259
260         $toIncludeStr = print_r($mapToInclude, true);
261         $toCheckStr = print_r($mapToCheck, true);
262         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
263     }
264
265     /**
266      * Assert a permission error has occurred.
267      */
268     protected function assertPermissionError($response)
269     {
270         if ($response instanceof BrowserKitTest) {
271             $response = \Illuminate\Foundation\Testing\TestResponse::fromBaseResponse($response->response);
272         }
273
274         $response->assertRedirect('/');
275         $this->assertSessionHas('error');
276         $error = session()->pull('error');
277         $this->assertStringStartsWith('You do not have permission to access', $error);
278     }
279
280 }