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