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