]> BookStack Code Mirror - bookstack/blob - tests/TestCase.php
Extracted entity testcase methods to own class
[bookstack] / tests / TestCase.php
1 <?php
2
3 namespace Tests;
4
5 use BookStack\Auth\Permissions\JointPermissionBuilder;
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\Entity;
11 use BookStack\Settings\SettingService;
12 use BookStack\Uploads\HttpFetcher;
13 use GuzzleHttp\Client;
14 use GuzzleHttp\Handler\MockHandler;
15 use GuzzleHttp\HandlerStack;
16 use GuzzleHttp\Middleware;
17 use Illuminate\Contracts\Console\Kernel;
18 use Illuminate\Foundation\Testing\DatabaseTransactions;
19 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
20 use Illuminate\Http\JsonResponse;
21 use Illuminate\Support\Env;
22 use Illuminate\Support\Facades\DB;
23 use Illuminate\Support\Facades\Log;
24 use Illuminate\Testing\Assert as PHPUnit;
25 use Monolog\Handler\TestHandler;
26 use Monolog\Logger;
27 use Psr\Http\Client\ClientInterface;
28 use Ssddanbrown\AssertHtml\TestsHtml;
29 use Tests\Helpers\EntityProvider;
30
31 abstract class TestCase extends BaseTestCase
32 {
33     use CreatesApplication;
34     use DatabaseTransactions;
35     use TestsHtml;
36
37     protected ?User $admin = null;
38     protected ?User $editor = null;
39     protected EntityProvider $entities;
40
41     protected function setUp(): void
42     {
43         $this->entities = new EntityProvider();
44         parent::setUp();
45     }
46
47     /**
48      * The base URL to use while testing the application.
49      */
50     protected string $baseUrl = 'http://localhost';
51
52     /**
53      * Creates the application.
54      *
55      * @return \Illuminate\Foundation\Application
56      */
57     public function createApplication()
58     {
59         /** @var \Illuminate\Foundation\Application  $app */
60         $app = require __DIR__ . '/../bootstrap/app.php';
61         $app->register(TestServiceProvider::class);
62         $app->make(Kernel::class)->bootstrap();
63
64         return $app;
65     }
66
67     /**
68      * Set the current user context to be an admin.
69      */
70     public function asAdmin()
71     {
72         return $this->actingAs($this->getAdmin());
73     }
74
75     /**
76      * Get the current admin user.
77      */
78     public function getAdmin(): User
79     {
80         if (is_null($this->admin)) {
81             $adminRole = Role::getSystemRole('admin');
82             $this->admin = $adminRole->users->first();
83         }
84
85         return $this->admin;
86     }
87
88     /**
89      * Set the current user context to be an editor.
90      */
91     public function asEditor()
92     {
93         return $this->actingAs($this->getEditor());
94     }
95
96     /**
97      * Get a editor user.
98      */
99     protected function getEditor(): User
100     {
101         if ($this->editor === null) {
102             $editorRole = Role::getRole('editor');
103             $this->editor = $editorRole->users->first();
104         }
105
106         return $this->editor;
107     }
108
109     /**
110      * Set the current user context to be a viewer.
111      */
112     public function asViewer()
113     {
114         return $this->actingAs($this->getViewer());
115     }
116
117     /**
118      * Get an instance of a user with 'viewer' permissions.
119      */
120     protected function getViewer(array $attributes = []): User
121     {
122         $user = Role::getRole('viewer')->users()->first();
123         if (!empty($attributes)) {
124             $user->forceFill($attributes)->save();
125         }
126
127         return $user;
128     }
129
130     /**
131      * Get a user that's not a system user such as the guest user.
132      */
133     public function getNormalUser(): User
134     {
135         return User::query()->where('system_name', '=', null)->get()->last();
136     }
137
138     /**
139      * Quickly sets an array of settings.
140      */
141     protected function setSettings(array $settingsArray): void
142     {
143         $settings = app(SettingService::class);
144         foreach ($settingsArray as $key => $value) {
145             $settings->put($key, $value);
146         }
147     }
148
149     /**
150      * Give the given user some permissions.
151      */
152     protected function giveUserPermissions(User $user, array $permissions = []): void
153     {
154         $newRole = $this->createNewRole($permissions);
155         $user->attachRole($newRole);
156         $user->load('roles');
157         $user->clearPermissionCache();
158     }
159
160     /**
161      * Completely remove the given permission name from the given user.
162      */
163     protected function removePermissionFromUser(User $user, string $permissionName)
164     {
165         $permissionBuilder = app()->make(JointPermissionBuilder::class);
166
167         /** @var RolePermission $permission */
168         $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
169
170         $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
171             $query->where('id', '=', $permission->id);
172         })->get();
173
174         /** @var Role $role */
175         foreach ($roles as $role) {
176             $role->detachPermission($permission);
177             $permissionBuilder->rebuildForRole($role);
178         }
179
180         $user->clearPermissionCache();
181     }
182
183     /**
184      * Create a new basic role for testing purposes.
185      */
186     protected function createNewRole(array $permissions = []): Role
187     {
188         $permissionRepo = app(PermissionsRepo::class);
189         $roleData = Role::factory()->make()->toArray();
190         $roleData['permissions'] = array_flip($permissions);
191
192         return $permissionRepo->saveNewRole($roleData);
193     }
194
195     /**
196      * Mock the HttpFetcher service and return the given data on fetch.
197      */
198     protected function mockHttpFetch($returnData, int $times = 1)
199     {
200         $mockHttp = Mockery::mock(HttpFetcher::class);
201         $this->app[HttpFetcher::class] = $mockHttp;
202         $mockHttp->shouldReceive('fetch')
203             ->times($times)
204             ->andReturn($returnData);
205     }
206
207     /**
208      * Mock the http client used in BookStack.
209      * Returns a reference to the container which holds all history of http transactions.
210      *
211      * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
212      */
213     protected function &mockHttpClient(array $responses = []): array
214     {
215         $container = [];
216         $history = Middleware::history($container);
217         $mock = new MockHandler($responses);
218         $handlerStack = new HandlerStack($mock);
219         $handlerStack->push($history);
220         $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
221
222         return $container;
223     }
224
225     /**
226      * Run a set test with the given env variable.
227      * Remembers the original and resets the value after test.
228      * Database config is juggled so the value can be restored when
229      * parallel testing are used, where multiple databases exist.
230      */
231     protected function runWithEnv(string $name, $value, callable $callback)
232     {
233         Env::disablePutenv();
234         $originalVal = $_SERVER[$name] ?? null;
235
236         if (is_null($value)) {
237             unset($_SERVER[$name]);
238         } else {
239             $_SERVER[$name] = $value;
240         }
241
242         $database = config('database.connections.mysql_testing.database');
243         $this->refreshApplication();
244
245         DB::purge();
246         config()->set('database.connections.mysql_testing.database', $database);
247
248         $callback();
249
250         if (is_null($originalVal)) {
251             unset($_SERVER[$name]);
252         } else {
253             $_SERVER[$name] = $originalVal;
254         }
255     }
256
257     /**
258      * Check the keys and properties in the given map to include
259      * exist, albeit not exclusively, within the map to check.
260      */
261     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
262     {
263         $passed = true;
264
265         foreach ($mapToInclude as $key => $value) {
266             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
267                 $passed = false;
268             }
269         }
270
271         $toIncludeStr = print_r($mapToInclude, true);
272         $toCheckStr = print_r($mapToCheck, true);
273         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
274     }
275
276     /**
277      * Assert a permission error has occurred.
278      */
279     protected function assertPermissionError($response)
280     {
281         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
282     }
283
284     /**
285      * Assert a permission error has occurred.
286      */
287     protected function assertNotPermissionError($response)
288     {
289         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
290     }
291
292     /**
293      * Check if the given response is a permission error.
294      */
295     private function isPermissionError($response): bool
296     {
297         return $response->status() === 302
298             && (
299                 (
300                     $response->headers->get('Location') === url('/')
301                     && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
302                 )
303                 ||
304                 (
305                     $response instanceof JsonResponse &&
306                     $response->json(['error' => 'You do not have permission to perform the requested action.'])
307                 )
308             );
309     }
310
311     /**
312      * Assert that the session has a particular error notification message set.
313      */
314     protected function assertSessionError(string $message)
315     {
316         $error = session()->get('error');
317         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
318     }
319
320     /**
321      * Assert the session contains a specific entry.
322      */
323     protected function assertSessionHas(string $key): self
324     {
325         $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
326
327         return $this;
328     }
329
330     protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
331     {
332         return $this->withHtml($resp)->assertElementContains('[notification]', $text);
333     }
334
335     /**
336      * Set a test handler as the logging interface for the application.
337      * Allows capture of logs for checking against during tests.
338      */
339     protected function withTestLogger(): TestHandler
340     {
341         $monolog = new Logger('testing');
342         $testHandler = new TestHandler();
343         $monolog->pushHandler($testHandler);
344
345         Log::extend('testing', function () use ($monolog) {
346             return $monolog;
347         });
348         Log::setDefaultDriver('testing');
349
350         return $testHandler;
351     }
352
353     /**
354      * Assert that an activity entry exists of the given key.
355      * Checks the activity belongs to the given entity if provided.
356      */
357     protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
358     {
359         $detailsToCheck = ['type' => $type];
360
361         if ($entity) {
362             $detailsToCheck['entity_type'] = $entity->getMorphClass();
363             $detailsToCheck['entity_id'] = $entity->id;
364         }
365
366         if ($detail) {
367             $detailsToCheck['detail'] = $detail;
368         }
369
370         $this->assertDatabaseHas('activities', $detailsToCheck);
371     }
372 }