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