]> BookStack Code Mirror - bookstack/blob - tests/TestCase.php
Create additional test helper classes
[bookstack] / tests / TestCase.php
1 <?php
2
3 namespace Tests;
4
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Settings\SettingService;
7 use BookStack\Uploads\HttpFetcher;
8 use GuzzleHttp\Client;
9 use GuzzleHttp\Handler\MockHandler;
10 use GuzzleHttp\HandlerStack;
11 use GuzzleHttp\Middleware;
12 use Illuminate\Contracts\Console\Kernel;
13 use Illuminate\Foundation\Testing\DatabaseTransactions;
14 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
15 use Illuminate\Http\JsonResponse;
16 use Illuminate\Support\Env;
17 use Illuminate\Support\Facades\DB;
18 use Illuminate\Support\Facades\Log;
19 use Illuminate\Testing\Assert as PHPUnit;
20 use Mockery;
21 use Monolog\Handler\TestHandler;
22 use Monolog\Logger;
23 use Psr\Http\Client\ClientInterface;
24 use Ssddanbrown\AssertHtml\TestsHtml;
25 use Tests\Helpers\EntityProvider;
26 use Tests\Helpers\PermissionsProvider;
27 use Tests\Helpers\TestServiceProvider;
28 use Tests\Helpers\UserRoleProvider;
29
30 abstract class TestCase extends BaseTestCase
31 {
32     use CreatesApplication;
33     use DatabaseTransactions;
34     use TestsHtml;
35
36     protected EntityProvider $entities;
37     protected UserRoleProvider $users;
38     protected PermissionsProvider $permissions;
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
46         parent::setUp();
47     }
48
49     /**
50      * The base URL to use while testing the application.
51      */
52     protected string $baseUrl = 'http://localhost';
53
54     /**
55      * Creates the application.
56      *
57      * @return \Illuminate\Foundation\Application
58      */
59     public function createApplication()
60     {
61         /** @var \Illuminate\Foundation\Application  $app */
62         $app = require __DIR__ . '/../bootstrap/app.php';
63         $app->register(TestServiceProvider::class);
64         $app->make(Kernel::class)->bootstrap();
65
66         return $app;
67     }
68
69     /**
70      * Set the current user context to be an admin.
71      */
72     public function asAdmin()
73     {
74         return $this->actingAs($this->users->admin());
75     }
76
77     /**
78      * Set the current user context to be an editor.
79      */
80     public function asEditor()
81     {
82         return $this->actingAs($this->users->editor());
83     }
84
85     /**
86      * Set the current user context to be a viewer.
87      */
88     public function asViewer()
89     {
90         return $this->actingAs($this->users->viewer());
91     }
92
93     /**
94      * Quickly sets an array of settings.
95      */
96     protected function setSettings(array $settingsArray): void
97     {
98         $settings = app(SettingService::class);
99         foreach ($settingsArray as $key => $value) {
100             $settings->put($key, $value);
101         }
102     }
103
104     /**
105      * Mock the HttpFetcher service and return the given data on fetch.
106      */
107     protected function mockHttpFetch($returnData, int $times = 1)
108     {
109         $mockHttp = Mockery::mock(HttpFetcher::class);
110         $this->app[HttpFetcher::class] = $mockHttp;
111         $mockHttp->shouldReceive('fetch')
112             ->times($times)
113             ->andReturn($returnData);
114     }
115
116     /**
117      * Mock the http client used in BookStack.
118      * Returns a reference to the container which holds all history of http transactions.
119      *
120      * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
121      */
122     protected function &mockHttpClient(array $responses = []): array
123     {
124         $container = [];
125         $history = Middleware::history($container);
126         $mock = new MockHandler($responses);
127         $handlerStack = new HandlerStack($mock);
128         $handlerStack->push($history);
129         $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
130
131         return $container;
132     }
133
134     /**
135      * Run a set test with the given env variable.
136      * Remembers the original and resets the value after test.
137      * Database config is juggled so the value can be restored when
138      * parallel testing are used, where multiple databases exist.
139      */
140     protected function runWithEnv(string $name, $value, callable $callback)
141     {
142         Env::disablePutenv();
143         $originalVal = $_SERVER[$name] ?? null;
144
145         if (is_null($value)) {
146             unset($_SERVER[$name]);
147         } else {
148             $_SERVER[$name] = $value;
149         }
150
151         $database = config('database.connections.mysql_testing.database');
152         $this->refreshApplication();
153
154         DB::purge();
155         config()->set('database.connections.mysql_testing.database', $database);
156
157         $callback();
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         return $response->status() === 302
207             && (
208                 (
209                     $response->headers->get('Location') === url('/')
210                     && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
211                 )
212                 ||
213                 (
214                     $response instanceof JsonResponse &&
215                     $response->json(['error' => 'You do not have permission to perform the requested action.'])
216                 )
217             );
218     }
219
220     /**
221      * Assert that the session has a particular error notification message set.
222      */
223     protected function assertSessionError(string $message)
224     {
225         $error = session()->get('error');
226         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
227     }
228
229     /**
230      * Assert the session contains a specific entry.
231      */
232     protected function assertSessionHas(string $key): self
233     {
234         $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
235
236         return $this;
237     }
238
239     protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
240     {
241         return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
242     }
243
244     /**
245      * Set a test handler as the logging interface for the application.
246      * Allows capture of logs for checking against during tests.
247      */
248     protected function withTestLogger(): TestHandler
249     {
250         $monolog = new Logger('testing');
251         $testHandler = new TestHandler();
252         $monolog->pushHandler($testHandler);
253
254         Log::extend('testing', function () use ($monolog) {
255             return $monolog;
256         });
257         Log::setDefaultDriver('testing');
258
259         return $testHandler;
260     }
261
262     /**
263      * Assert that an activity entry exists of the given key.
264      * Checks the activity belongs to the given entity if provided.
265      */
266     protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
267     {
268         $detailsToCheck = ['type' => $type];
269
270         if ($entity) {
271             $detailsToCheck['entity_type'] = $entity->getMorphClass();
272             $detailsToCheck['entity_id'] = $entity->id;
273         }
274
275         if ($detail) {
276             $detailsToCheck['detail'] = $detail;
277         }
278
279         $this->assertDatabaseHas('activities', $detailsToCheck);
280     }
281 }