]> BookStack Code Mirror - bookstack/blob - tests/TestCase.php
OIDC: Added testing coverage for picture fetching
[bookstack] / tests / TestCase.php
1 <?php
2
3 namespace Tests;
4
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Http\HttpClientHistory;
7 use BookStack\Http\HttpRequestService;
8 use BookStack\Settings\SettingService;
9 use BookStack\Users\Models\User;
10 use Illuminate\Contracts\Console\Kernel;
11 use Illuminate\Foundation\Testing\DatabaseTransactions;
12 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
13 use Illuminate\Http\JsonResponse;
14 use Illuminate\Support\Env;
15 use Illuminate\Support\Facades\DB;
16 use Illuminate\Support\Facades\Log;
17 use Illuminate\Testing\Assert as PHPUnit;
18 use Monolog\Handler\TestHandler;
19 use Monolog\Logger;
20 use Ssddanbrown\AssertHtml\TestsHtml;
21 use Tests\Helpers\EntityProvider;
22 use Tests\Helpers\FileProvider;
23 use Tests\Helpers\PermissionsProvider;
24 use Tests\Helpers\TestServiceProvider;
25 use Tests\Helpers\UserRoleProvider;
26
27 abstract class TestCase extends BaseTestCase
28 {
29     use CreatesApplication;
30     use DatabaseTransactions;
31     use TestsHtml;
32
33     protected EntityProvider $entities;
34     protected UserRoleProvider $users;
35     protected PermissionsProvider $permissions;
36     protected FileProvider $files;
37
38     protected function setUp(): void
39     {
40         $this->entities = new EntityProvider();
41         $this->users = new UserRoleProvider();
42         $this->permissions = new PermissionsProvider($this->users);
43         $this->files = new FileProvider();
44
45         parent::setUp();
46
47         // We can uncomment the below to run tests with failings upon deprecations.
48         // Can't leave on since some deprecations can only be fixed upstream.
49          // $this->withoutDeprecationHandling();
50     }
51
52     /**
53      * The base URL to use while testing the application.
54      */
55     protected string $baseUrl = 'http://localhost';
56
57     /**
58      * Creates the application.
59      *
60      * @return \Illuminate\Foundation\Application
61      */
62     public function createApplication()
63     {
64         /** @var \Illuminate\Foundation\Application  $app */
65         $app = require __DIR__ . '/../bootstrap/app.php';
66         $app->register(TestServiceProvider::class);
67         $app->make(Kernel::class)->bootstrap();
68
69         return $app;
70     }
71
72     /**
73      * Set the current user context to be an admin.
74      */
75     public function asAdmin()
76     {
77         return $this->actingAs($this->users->admin());
78     }
79
80     /**
81      * Set the current user context to be an editor.
82      */
83     public function asEditor()
84     {
85         return $this->actingAs($this->users->editor());
86     }
87
88     /**
89      * Set the current user context to be a viewer.
90      */
91     public function asViewer()
92     {
93         return $this->actingAs($this->users->viewer());
94     }
95
96     /**
97      * Quickly sets an array of settings.
98      */
99     protected function setSettings(array $settingsArray): void
100     {
101         $settings = app(SettingService::class);
102         foreach ($settingsArray as $key => $value) {
103             $settings->put($key, $value);
104         }
105     }
106
107     /**
108      * Mock the http client used in BookStack http calls.
109      */
110     protected function mockHttpClient(array $responses = []): HttpClientHistory
111     {
112         return $this->app->make(HttpRequestService::class)->mockClient($responses);
113     }
114
115     /**
116      * Run a set test with the given env variable.
117      * Remembers the original and resets the value after test.
118      * Database config is juggled so the value can be restored when
119      * parallel testing are used, where multiple databases exist.
120      */
121     protected function runWithEnv(string $name, $value, callable $callback, bool $handleDatabase = true)
122     {
123         Env::disablePutenv();
124         $originalVal = $_SERVER[$name] ?? null;
125
126         if (is_null($value)) {
127             unset($_SERVER[$name]);
128         } else {
129             $_SERVER[$name] = $value;
130         }
131
132         $database = config('database.connections.mysql_testing.database');
133         $this->refreshApplication();
134
135         if ($handleDatabase) {
136             DB::purge();
137             config()->set('database.connections.mysql_testing.database', $database);
138             DB::beginTransaction();
139         }
140
141         $callback();
142
143         if ($handleDatabase) {
144             DB::rollBack();
145         }
146
147         if (is_null($originalVal)) {
148             unset($_SERVER[$name]);
149         } else {
150             $_SERVER[$name] = $originalVal;
151         }
152     }
153
154     /**
155      * Check the keys and properties in the given map to include
156      * exist, albeit not exclusively, within the map to check.
157      */
158     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
159     {
160         $passed = true;
161
162         foreach ($mapToInclude as $key => $value) {
163             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
164                 $passed = false;
165             }
166         }
167
168         $toIncludeStr = print_r($mapToInclude, true);
169         $toCheckStr = print_r($mapToCheck, true);
170         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
171     }
172
173     /**
174      * Assert a permission error has occurred.
175      */
176     protected function assertPermissionError($response)
177     {
178         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
179     }
180
181     /**
182      * Assert a permission error has occurred.
183      */
184     protected function assertNotPermissionError($response)
185     {
186         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
187     }
188
189     /**
190      * Check if the given response is a permission error.
191      */
192     private function isPermissionError($response): bool
193     {
194         if ($response->status() === 403 && $response instanceof JsonResponse) {
195             $errMessage = $response->getData(true)['error']['message'] ?? '';
196             return $errMessage === 'You do not have permission to perform the requested action.';
197         }
198
199         return $response->status() === 302
200             && $response->headers->get('Location') === url('/')
201             && str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
202     }
203
204     /**
205      * Assert that the session has a particular error notification message set.
206      */
207     protected function assertSessionError(string $message)
208     {
209         $error = session()->get('error');
210         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
211     }
212
213     /**
214      * Assert the session contains a specific entry.
215      */
216     protected function assertSessionHas(string $key): self
217     {
218         $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
219
220         return $this;
221     }
222
223     protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
224     {
225         return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
226     }
227
228     /**
229      * Set a test handler as the logging interface for the application.
230      * Allows capture of logs for checking against during tests.
231      */
232     protected function withTestLogger(): TestHandler
233     {
234         $monolog = new Logger('testing');
235         $testHandler = new TestHandler();
236         $monolog->pushHandler($testHandler);
237
238         Log::extend('testing', function () use ($monolog) {
239             return $monolog;
240         });
241         Log::setDefaultDriver('testing');
242
243         return $testHandler;
244     }
245
246     /**
247      * Assert that an activity entry exists of the given key.
248      * Checks the activity belongs to the given entity if provided.
249      */
250     protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
251     {
252         $detailsToCheck = ['type' => $type];
253
254         if ($entity) {
255             $detailsToCheck['loggable_type'] = $entity->getMorphClass();
256             $detailsToCheck['loggable_id'] = $entity->id;
257         }
258
259         if ($detail) {
260             $detailsToCheck['detail'] = $detail;
261         }
262
263         $this->assertDatabaseHas('activities', $detailsToCheck);
264     }
265 }